text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
parsing JSON file (URL) with JS
since I'm trying this for about 10 hours now I would appreciate any solution.
I need a speciffic value of a JSON but have no Idea how to select it.
So this is my JSON
{
"results" : [
{
"address_components" : [
{
"long_name" : "Buchenberg",
"short_name" : "Buchenberg",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Oberallgäu",
"short_name" : "Oberallgäu",
"types" : [ "administrative_area_level_3", "political" ]
},
{
"long_name" : "Swabia",
"short_name" : "Swabia",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Bavaria",
"short_name" : "BY",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Germany",
"short_name" : "DE",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Buchenberg, Germany",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 47.7525249,
"lng" : 10.286058
},
"southwest" : {
"lat" : 47.6694625,
"lng" : 10.1128175
}
},
"location" : {
"lat" : 47.6960163,
"lng" : 10.239696
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 47.7525249,
"lng" : 10.286058
},
"southwest" : {
"lat" : 47.6694625,
"lng" : 10.1128175
}
}
},
"place_id" : "ChIJA6IwOqmAm0cRxVEUeHkZnrg",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
I need to get the data of lat/lng from formatted address->geometry->bounds->northeast.
I tried this JS code
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address=buchenberg", function(result){
var geoArray = result;
alert(geoArray['status']);
});
and it returns "OK", like it's supposed to.
But how how can I select the lat/lng since it's involved so deep into this array and all this brackets :D pls help me
A:
your url returns results inside an array, at index 0, so you will need to access that first, to access the properties of the geometry object
var lat = geoArray.results[0].geometry.bounds.northeast.lat;
var long = geoArray.results[0].geometry.bounds.northeast.lng;
var result = {
"results" : [
{
"address_components" : [
{
"long_name" : "Buchenberg",
"short_name" : "Buchenberg",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Oberallgäu",
"short_name" : "Oberallgäu",
"types" : [ "administrative_area_level_3", "political" ]
},
{
"long_name" : "Swabia",
"short_name" : "Swabia",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Bavaria",
"short_name" : "BY",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Germany",
"short_name" : "DE",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Buchenberg, Germany",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 47.7525249,
"lng" : 10.286058
},
"southwest" : {
"lat" : 47.6694625,
"lng" : 10.1128175
}
},
"location" : {
"lat" : 47.6960163,
"lng" : 10.239696
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 47.7525249,
"lng" : 10.286058
},
"southwest" : {
"lat" : 47.6694625,
"lng" : 10.1128175
}
}
},
"place_id" : "ChIJA6IwOqmAm0cRxVEUeHkZnrg",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
};
var geoArray = result;
var lat = geoArray.results[0].geometry.bounds.northeast.lat;
var long = geoArray.results[0].geometry.bounds.northeast.lng;
console.log(lat);
console.log(long);
output:
lat 47.7525249
long 10.286058
| {
"pile_set_name": "StackExchange"
} |
Q:
Parameters in AJAX PHP callback function
I am using the below AJAX script to process some operation.
<script type="text/javascript">
function validLogin(){
var uname=$('#uname').val();
var password=$('#password').val();
var dataString = 'uname='+ uname + '&password='+ password;
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="http://www.91weblessons.com/demo/phpAjaxLoginValidation/image/loading.gif" />');
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
$("#flash").hide();
if(result=='correct'){
window.location='update.php';
}else{
$("#errorMessage").html(result);
}
}
});
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
</script>
Here I need to redirect to a dynamic URL update.php?name=somename after success.
Please give any suggestions.
A:
If you need to simulate a redirect, a better way is through window.location.replace(...).
If its the same base protocol and origin, you could use window.location.replace(window.location.origin + '/update.php?name='+uname);
Refer to: How to redirect to another webpage in JavaScript/jQuery? for the difference between window.location.replace() and setting window.location.href
| {
"pile_set_name": "StackExchange"
} |
Q:
how to add an observable property to a knockout.mapping loaded from mvc 4 class
I'm working with mvc4 and knockout trying to understand all the cool stuff you can to with it.
the thing is, i have this code which loads info and sends it to the view.
public ActionResult AdministraContenidoAlumno()
{
Alumno NuevoAlumno = new Alumno();
NuevoAlumno.AlumnoId = 1;
NuevoAlumno.NombreCompleto = "Luis Antonio Vega Herrera";
NuevoAlumno.PlanEstudioActual = new PlanEstudio
{
PlanEstudioId = 1,
NombrePlan = "Ingenieria en sistemas",
ListaMateriasPlan = new List<Materias> {
new Materias{MateriaId=1,NombreMateria="ingenieria 1"},new Materias{MateriaId=2,NombreMateria="Ingenieria 2"}
}
};
return View(NuevoAlumno);
Basically, create a new object alumno, who contains a PlanEstudio, who contains a list of Materias, then send it to the view.
In the view i have this.
@model MvcRCPG.Models.Alumno
@{
ViewBag.Title = "AdministraContenidoAlumno";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
var data;
$(function () {
var jsonModel = '@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);
data = mvcModel;
ko.applyBindings(mvcModel);
});
function Guardar() {
$.ajax({
url: "/DemoKnockuot/GuardarAlumno",
type: "POST",
data: JSON.stringify({ 'NuevoAlumno': ko.toJS(data) }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data == "Success") {
alert('entro')
} else {
alert('trono')
}
},
error: function () {
alert("An error has occured!!!");
}
});
}
</script>
With the mentioned above functions i can read and send data to the server and do stuff on the controller, however i need to add remove or manipulate the information in the view.
So the question is: how do i add a function to 'mvcModel' in order to push a new "materia" in the ListaMateriasPlan object?
Thank you, and if you have more tips in order to understand it better i appreciate your help.
A:
The mvcModel created by the mapping plugin will have observable properties.
For example, to add a new "materia" do something like:
function Materias() {
this.MateriaId = ko.observable();
this.NombreMateria = ko.observable();
}
var newItem = new Materias();
newItem.MateriaId(3);
newItem.NombreMateria("Ingenieria 3");
mvcModel.PlanEstudioActual.ListaMateriasPlan.push(newItem);
And normally, you would wrap the "adding" logic as a method in a view model.
| {
"pile_set_name": "StackExchange"
} |
Q:
Detail about parenthesis in a function type declaration in Haskell
I am currently reading about the identity Monad and one piece defines fmap as this:
fmap :: (a -> b) -> (W a -> W b)
fmap f (W x) = W (f x)
The text says the goal is creating a function which changes an existing function for the types of a and b to another function which applies the original function to the types W a and W b.
From this point of view there are two functions involved and the type signature also looks like this: Its parameter is one function and it delivers a function.
What puzzled me at first is that the actual type of fmap as ghci tells is:
fmap :: (a -> b) -> W a -> W b
Thinking about that reveals that the function fmap gets a function and a parameter of type W a and then applies the function on the a in the W a and returns the result as W b. Which happens to be the description of what the code for fmap does.
I am pretty sure that it does not make any difference in what the function does if one omits the parenthesis in the type definition.
Am I right that this is similar to as if I would say:
addab is a function which creates a function that can add a value to its parameter
And give this example code:
addab :: Int -> (Int -> Int)
addab x y = x + y
add1 :: Int -> Int
add1 = addab 1
Basically just indicating that the function is made to be used without giving all the parameters to it?
Or is there any deeper meaning to it which I did not consider?
A:
Well, for starters it can't make a difference because -> is right-associative, meaning (a->b)->c->d is defined as (a->b) -> (c->d)!
As to why and so on, you're exactly right: it's just currying. The particular reason why that is so popular in Haskell is that partial application lends itself very well to writing computation pipelines in a natural way: stuff like unzip . fmap f . reverse. Here, the fmap doesn't really receive its list argument, only the morphism it's supposed to lift onto lists. The result morphism has a type ([a]->[b]).
This (a->b) -> (F a->F d) is actually the more "fundamental" definition: mathematicians define a functor as mapping morphisms to morphisms; the "function and argument" writing (a->b, F a) -> F b generally doesn't make any sense because there is, in general categories, no meaningful wway to combine morphisms with objects. Only, as nomen sais, in cartesian closed categories morphisms are objects as well.
A:
Both of those types for fmap are correct. They are effectively equivalent.
And your experiment is correct as well.
What is going on here is that the space of functions is a closed cartesian category. In particular, this means that we can do partial function application. It is deep, insofar as there are logics/languages where partial function application is invalid as a rule of inference. Of course, this means that Haskell has more valid ways to factor a program than other languages.
For example, your addab function and a multab function you can define yourself let us do things like:
addab 1 . addab 2 . multab 3 $ 5
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this extra divider line on my Dock?
Mysteriously, this extra divider-line has appeared between any app I launch now and the previously launched apps?
What is the purpose of this 2nd divider line? Why is it appearing now? How can I get rid of it?
See this screenshot, with pink arrow pointing to the mystery divider-line.
A:
Recent apps
This is recently-opened applications, which is on by default in macOS Mojave. To disable, open System Preferences > Dock, and uncheck Show recent applications in Dock.
| {
"pile_set_name": "StackExchange"
} |
Q:
VB.NET LINQ Query: Getting The Sum of All Values For A Specific Structure Member
In VB.NET, let's assume I have the following Structure:
Public Structure Product
Public ItemNo As Int32
Public Description As String
Public Cost As Decimal
End Structure
... and a Generic List of the Products:
Dim ProductsList As New List(Of Product)
Dim product1 As New Product
With product1
.ItemNo = 100
.Description = "Standard Widget"
.Cost = 10D
End With
ProductsList.Add(product1)
Dim product2 As New Product
With product2
.ItemNo = 101
.Description = "Standard Cog"
.Cost = 10.95D
End With
ProductsList.Add(product2)
Dim product3 As New Product
With product3
.ItemNo = 101
.Description = "Industrial Strenght Sprocket"
.Cost = 99.95D
End With
ProductsList.Add(product3)
How would I define a LINQ Query to Sum all of the Product.Cost values in the List? In other words, what would be the LINQ
Query in VB.NET to return the value 120.90, which reflects the sum of all three Product Cost values in a single LINQ Query?
A:
The built in Sum method does this already.
In VB it looks like this:
ProductList.Sum(Function(item) item.Cost)
In C# it looks like this:
ProductsList.Sum( (item) => item.Cost);
A:
One way would be:
Dim s = (From p As Product In products Select p.Cost).Sum()
| {
"pile_set_name": "StackExchange"
} |
Q:
Azure Maps requests monitoring
Does anybody knows, what metric is shown in Azure Maps usage diagrams?
This is what diagram looks like, and number of request in the charts significantly differs from my traffic amounts. It seems like 10-15 requests in the graph per each visitor on the site.
I suppose that charts showing amount of map-tiles loaded, where each tile load is considered as a request.
Update
The question is about using JavaScript maps control
A:
Map loads in map control is tracked as Map tile API requests where each API request renders one tile. On Azure portal on the Azure maps usage page you can click on "Apply splitting" button and group the usage by "API name" to confirm your assumption.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there jQuery like selectors for Java XML parsing?
When I want to find elements from XML in with jQuery, i can just use CSS selectors. Is there any similar selector system for XML parsing in Java?
A:
The query syntax for XML is called XPath.
A:
I am currently creating a sort of "jQuery port to Java". It is called jOOX and will provide most of jQuery's DOM navigation and manipulation methods. In addition to a simple selector expression language, standard XPath and XML transformation is supported, based on the standard Java DOM API
https://github.com/jOOQ/jOOX
Some sample code:
// Find the order at index for and add an element "paid"
$(document).find("orders").children().eq(4)
.append("<paid>true</paid>");
// Find those orders that are paid and flag them as "settled"
$(document).find("orders").children().find("paid")
.after("<settled>true</settled>");
| {
"pile_set_name": "StackExchange"
} |
Q:
Command to stop querying in SQL Server
I have a long SQL Script which I run to pre-populate some temp tables. At the bottom of the script, I have some queries that I run manually, as well as some other ad-hoc queries. I open the query, then get it started (takes a few minutes to run). However, I don't want all the queries at the end of script to run - I only want to the temp tables to populate.
SQL Server 2008 Management Studio has a "breakpoint" function that will stop the script at that point, but if you close the application and re-open it, it will forget the breakpoint (only lasts for the session in which you set it).
I could comment out the queries at the bottom and run them manually. However, the ideal solution for me was to include a command in my script to stop the script from running.
In SQL Server 2008 is there a command I can put into my script that will stop processing at a specific location?
A:
Just put a RETURN at the place where you want to stop executing the script.
A:
Another potential solution is to put a waitfor command so that the script pauses. If you can identify that the script has made it to that point, you can stop it at any time, as long as you don't wait longer than the waitfor. e.g.
-- first part of script
RAISERROR('Finished above section, about to wait...', 0, 1) WITH NOWAIT;
WAITFOR DELAY '23:59:59';
-- rest of script
You could also do this conditionally, e.g.
DECLARE @stop BIT = 0;
-- first part of script
IF @stop = 1
BEGIN
RAISERROR('Finished above section, about to wait...', 0, 1) WITH NOWAIT;
WAITFOR DELAY '23:59:59';
END
-- rest of script
| {
"pile_set_name": "StackExchange"
} |
Q:
htaccess URL Rewriting not working in PHP Slim framework
Here is my .htaccess file code
RewriteEngine On
RewriteBase /api
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
File path
api/
- htaccess
- index.php
This url was working fine
http://localhost/api/index.php/inventory/login/
But http://localhost/api/inventory/login/ showing 404 not found error. How to solve this problem?
A:
Add
this in apache sites enabled file inside <virtualHost> tag
<Directory "/var/www/html">
AllowOverride All
Order allow,deny
Allow from all
</Directory>
and .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
| {
"pile_set_name": "StackExchange"
} |
Q:
OP comments vs votes and accepts
An OP has commented that my answer was correct and resolved his problem, but he didn't vote for it, or accept it. Is there anything to be done, or just let it go?
A:
Well, you should not pressure the OP to vote and/or accept your answer; despite the fact that most of us would obviously agree that voting and accepting is beneficial to the idea of Stackexchange - upvotes or acceptance signals an answer is helpful and thus worthwhile reading - and to the users participating (yeah, virtual internet points as an incentive to provide quality content).
https://raspberrypi.stackexchange.com/help/someone-answers says:
What should I do when someone answers my question?
Decide if the answer is helpful, and then...
Vote on it (if you have earned the appropriate voting privilege). Vote up answers that are helpful and well-researched, and vote down answers that are not. Other users will also vote on answers to your question.
Accept it. As the asker, you have a special privilege: you may accept the answer that you believe is the best solution to your problem.
Note that it says should not must. In this particular case it is however noteworthy that the OP cannot not yet upvote your answer due to the lacking reputation (in other words the answer itself lacks upvotes in the first place). He could still accept your answer though and I am usually fine with a comment indicating just that.
A:
you should not pressure the OP to vote and/or accept your answer
- Ghanima
I'm going to disagree with this, if we take "pressure" to include a polite response. I think there is at least one scenario where it is okay: If this is the OP's first question, or if looking through his/her other questions from the profile link, you notice s/he has never accepted an answer. This is a clue the OP may not understand this part of the system.
Of course, if that person had taken the new user tour and/or read other Q&A's -- both of which I would hope someone would do before asking, but a surprising number of people clearly do not1 -- they would likely have picked up on this. The fact that so many of them do not is testimony to the single-mindedness of people who want help please with their problem now.
That's understandable, and if that person then thanks you in a comment but doesn't tick the check, it's probably because they don't get it. In this case, I think there's nothing wrong with a polite:
If you this answer helped you solve your problem, please accept it by ticking the big checkmark at the top on the left.
I do this occasionally (on my own and other people's answers), and I notice other people having done it, and most of the time the OP does exactly that. Although it may seem aggressive, it is helpful if the OP really didn't understand (and might otherwise continue on asking questions and never accepting an answer). If they already know, I think most reasonable people would take it for what it is: A tip to someone they think needs it. No harm no foul!
You can tell if someone has taken the tour if they have the "Informed" badge. Only ~10% of our members actually have that, despite the fact that you are invited to do so when you sign up (that's not adjusted for people who came from other SE sites where they may have taken the tour). If they don't, and they don't have other SE memberships, that's a clue they did not take the tour.
The majority of people who post questions as answers (go figure), and/or get their first question closed by me for whatever reason, fall into this category (which is why I politely ask them to "Please take the tour...").
| {
"pile_set_name": "StackExchange"
} |
Q:
input in C programming language
I want code receive from user a floating number but store only two digit after decimal point
for example if user input
a=123.123456789
a value will equal 123.12
#include <stdio.h>
int func(int x,int digit,int con,char* s)
{
int v;
v=x/digit;
v=v*digit;
x-=v;
if(con==1){
printf("%d %s(s) de R$ %.2f\n",(v/digit),s,(float)digit/100);
return x;
}
printf("%d %s(s) de R$ %.2f\n",(v/digit),s,(float)digit);
return x;
}
int main() {
int x=0;
float y;//if change to double the result will be true
scanf("%f",&y);
//y = ((int)(100.0 * y)) / 100.0;
x=(int)y;
y=y-x;
printf("NOTAS:\n");
char* arr="nota";
x=func(x,100,0,arr);
x=func(x,50,0,arr);
x=func(x,20,0,arr);
x=func(x,10,0,arr);
x=func(x,5,0,arr);
x=func(x,2,0,arr);
printf("MOEDAS:\n");
arr="moeda";
x=func(x,1,0,arr);
//mod
x=y*100;
x=func(x,50,1,arr);
x=func(x,25,1,arr);
x=func(x,10,1,arr);
x=func(x,5,1,arr);
x=func(x,1,1,arr);
return 0;
}
problem will found in:
https://www.urionlinejudge.com.br/judge/en/problems/view/1021
A:
If you just want to round off to two decimal points you could try something like:
a = ((int) (a*100))/100.0;
A:
The value have only 2 decimal places is a matter of displaying it, so you just need to print the number of decimal places you are interested in, like
float value = 123.123456;
printf("%.2f\n", value);
if you want to dynamicaly specify that number, you can use
float value = 123.123456;
int decimals = 2;
printf("%.*f\n", decimals, value);
If you want to store the value as a string then use sprintf() or better snprintf().
And taking the input with only two decimals does not make sense anyway because the output is what should be filtered instead of the input, note that after all you will ignore the extra decimals inserted by the user.
Also, note that floating point numbers cannot store exact numbers, so even i you leave only two decimal places by doing something like
float value = ((int)(100.0 * 123.1234156)) / 100.0
the actual value that is stored might be
123.1200000001
which has more decimal places.
One thing that you could try is
struct RealNumber
{
int integerPart;
int decimalPart;
};
and then handle the input to read them separately, which will be really dificult.
| {
"pile_set_name": "StackExchange"
} |
Q:
Allow access to Named Pipe Server from remote clients
I would like to ask you how to set up possible access to my named pipe server from remote clients. Until now I thought that NamedPipes can be used just for inter-process communication on same computer, but based on http://msdn.microsoft.com/en-us/library/windows/desktop/aa365150%28v=vs.85%29.aspx it should be possible by setting PIPE_ACCEPT_REMOTE_CLIENTS / PIPE_REJECT_REMOTE_CLIENTS to allow/ not allow to access from remote computers. I did not find simple way how to setup this functionality in .NET. I suppose that PipeSecurity could be somehow used for it but I did not find a simple way.
My current solution allows to access all users to my named pipe on current machine. Can somebody improve my solution to allow access from another machine as well?
Thanks.
public NamedPipeServerStream CreateNamedPipeServer(string pipeName)
{
const int BufferSize = 65535;
var pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite, AccessControlType.Allow));
pipeSecurity.AddAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.ReadWrite, AccessControlType.Allow));
return new NamedPipeServerStream(pipeName, PipeDirection.InOut, countOfServerInstancesToCreate, PipeTransmissionMode.Message, PipeOptions.Asynchronous,
BufferSize,
BufferSize);
}
A:
Yes, named pipes can be from/to remote computers. See http://msdn.microsoft.com/en-us/library/windows/desktop/aa365590(v=vs.85).aspx which details:
Named pipes can be used to provide communication between processes on the same computer or between processes on different computers across a network.
But, this option is not directly supported by .NET. The NamedPipeServerStream constructors translates the PipeTransmisionMode into the natives dwPipeMode parameter so you don't have direct access to that.
Conceivably you could sneak PIPE_REJECT_REMOTE_CLIENTS in there (PIPE_ACCEPT_REMOTE_CLIENTS is zero, so you don't have to do anything to support that). You'd have to OR in a new value for the PipeTransmissionMode parameter. For example:
var transmissionMode =
(PipeTransmissionMode)((int)PipeTransmissionMode.Byte | (0x8 >> 1));
Then create a NamedPipeServerStream instance with transmissionMode. But, don't expect any support for it :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Having virtual methods as templates that receive iterators
I know one cannot use templates for virtual methods in C++ (or vice versa), as for example discussed here and here. Unfortunately I am not sure how to deal with that limitation in my case.
We have a class template that includes a method template:
template <class T>
class BeliefSet : public Belief<T>
{
private:
std::vector<T> m_Facts;
public:
template <class Iter>
void SetFacts(Iter IterBegin, Iter IterEnd, bool Append = false)
{
if(!Append)
{
m_Facts.clear();
}
m_Facts.insert(m_Facts.end(), IterBegin, IterEnd);
}
};
The method SetFacts() should be able to receive two input iterators for an STL container, that's why we are using a method template here.
Now I would like to make this method SetFacts() virtual, which is not possible in C++ the way this code is written at the moment. So what else is the typical approach to deal with this situation?
A:
Something based on the CRTP idiom and a bit of sfinae could probably solve it:
template <class D, class T>
class BeliefSet : public Belief<T>
{
private:
std::vector<T> m_Facts;
template <class Iter>
void SetFactsInternal(char, Iter IterBegin, Iter IterEnd, bool Append = false)
{
if(!Append)
{
m_Facts.clear();
}
m_Facts.insert(m_Facts.end(), IterBegin, IterEnd);
}
template <class Iter, typename U = D>
auto SetFactsInternal(int, Iter IterBegin, Iter IterEnd, bool Append = false)
-> decltype(static_cast<U*>(this)->OverloadedSetFacts(IterBegin, IterEnd, Append), void())
{
static_cast<U*>(this)->OverloadedSetFacts(IterBegin, IterEnd, Append);
}
public:
template <typename... Args>
void SetFacts(Args&&... args)
{
SetFactsInternal(0, std::forward<Args>(args)...);
}
};
Your derived class can implement OverloadedSetFacts member function to overload SetFacts.
Moreover, your derived class must inherit from BeliefSet as it follows:
struct Derived: BeliefSet<Derived, MyTType>
{
//...
};
That is the key concept behind the CRTP idiom after all.
It follows a minimal, working example (in C++14 for simplicity):
#include<iostream>
template <class D>
class Base {
private:
template <class C>
auto internal(char, C) {
std::cout << "internal" << std::endl;
}
template <class C, typename U = D>
auto internal(int, C c)
-> decltype(static_cast<U*>(this)->overloaded(c), void()) {
static_cast<U*>(this)->overloaded(c);
}
public:
template <typename... Args>
auto base(Args&&... args) {
internal(0, std::forward<Args>(args)...);
}
};
struct Overloaded: Base<Overloaded> {
template<typename T>
auto overloaded(T) {
std::cout << "overloaded" << std::endl;
}
};
struct Derived: Base<Derived> {};
int main() {
Overloaded over;
over.base(0);
Derived der;
der.base(0);
}
As you can see, you can provide a default implementation in your base class and override it in the derived class if needed.
See it on wandbox.
A:
If you want to keep a virtual interface, type erasure works if you can find a narrow point of customization.
For example, erasing down to for-each T.
template<class T>
using sink=std::function<void(T)>;
template<class T>
using for_each_of=sink< sink<T> const& >;
Now in Belief<T> we set up two things:
template<class T>
struct Belief{
template <class Iter>
void SetFacts(Iter IterBegin, Iter IterEnd, bool Append = false){
SetFactsEx(
[&]( sink<T const&> const& f ){
for(auto it=IterBegin; it != IterEnd; ++it) {
f(*it);
},
Append
);
}
virtual void SetFactsEx(for_each_of<T const&> elems, bool Append = false)=0;
};
Now we do this in the derived class:
virtual void SetFactsEx(for_each_of<T const&> elems, bool Append = false) override
{
if(!Append)
m_Facts.clear();
elems( [&](T const& e){
m_Facts.push_back(e);
} );
}
And we done.
There is loss of efficiency here, but you can keep enriching the type erasure interface to reduce it. All the way down to erasing "insert into end of vector" for near zero efficiency loss.
I gave it a different name because it avoids some overload annoyances.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to break the loop in Golang
I'm learning programming using Go. The following program should continuously display menu until 0 is chosen. Current behavior: If the users first choice is 0, loop breaks. If first time the choice was 1, 2 or 3, the second time when 0 is chosen, loop doesn't break. What am I doing wrong?
package main
import "fmt"
func main() {
multiline2 := "Welcome! Please make your choice: \n" +
"--------------------------------- \n" +
"1. Option One \n" +
"2. Option Two \n" +
"3. Option Three \n" +
"0. Exit \n" +
"----------------- \n" +
"Your Choice is: "
fmt.Print(multiline2)
var usersChoice int
fmt.Scanln(&usersChoice)
decider(usersChoice)
}
func decider(value int) {
testLoop:for value > 0 {
switch value {
case 1:
fmt.Println("You Chose One, try again \n")
//break
main()
case 2:
fmt.Println("You Chose Two, try again \n")
//break
main()
case 3:
fmt.Println("You Chose Three, try again \n")
//break
main()
case 0:
fmt.Println("You Chose To Quit")
fmt.Println("Good Bye")
value = 0 // doesnt help...
break testLoop
}
}
}
After Updates this is the working code in case if it helps someone.
package main
import "fmt"
func main() {
starter()
}
func starter() {
multiline2 := "Welcome! Please make your choice: \n" +
"--------------------------------- \n" +
"1. Option One \n" +
"2. Option Two \n" +
"3. Option Three \n" +
"0. Exit \n" +
"----------------- \n" +
"Your Choice is: "
fmt.Print(multiline2)
var usersChoice int
fmt.Scanln(&usersChoice)
decider(usersChoice)
}
func decider(value int) {
//for value > 0 {
switch value {
case 1:
fmt.Println("You Chose One, try again \n")
starter()
case 2:
fmt.Println("You Chose Two, try again \n")
starter()
case 3:
fmt.Println("You Chose Three, try again \n")
starter()
case 0:
fmt.Println("You Chose To Quit")
fmt.Println("Good Bye")
//value = 0
//break
}
//}
}
A:
You shouldn't call "main" from inside a for loop like that; when you do it, you're asking for the user input again, but the calling code is still iside that loop, so it will keep running it again. You should just remove that "for" loop at all (and "break testLoop" as well).
| {
"pile_set_name": "StackExchange"
} |
Q:
How are coroutines implemented?
I have a question about coroutine implementation.
I saw coroutine first on Lua and stackless-python. I could understand the concept of it, and how to use yield keyword, but I cannot figure out how it is implemented.
Can I get some explanation about them?
A:
Coroutining is initiated by pushing the target address, then each coroutine switch exchanges the current PC with the top of the stack, which eventually has to get popped to terminate the coroutining.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server 2008 R2 stored procedures
I am facing a problem with my slow improvement in SQL Server 2008 R2 and here is the case:
I want to create a stored procedure that accepts parameters, but I want it to work in a special way so that if I pass 2 parameters in search in a table patient for example where as if I pass to it one parameter I want it to search in a table school and so on.
Any help will be really appreciated
Thank you
USE []
GO
/****** Object: StoredProcedure [dbo].[proc_search_patient_ByID] Script Date: 11/28/2014 07:47:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[proc_search_patient_ByID]
(
@PatID_pk int ,
@Cntid smallint,
@FamID int
)
AS
SET NOCOUNT ON
select cntid AS Center , PatFName AS FirstName , PatMName AS MiddleName , PatLName AS LastName , PatMother AS MotherName ,PatDOB AS DOB
from tbl
where Cntid=@Cntid and PatId_PK = @PatID_pk
i want my procedure to work in this way if i supply 2 param but if i supply @FamID i want it to search in completely another table
A:
Try passing null value for unused parameters and inside the stored procedure put a check for nulls to switch tables.
CREATE PROCEDURE [dbo].[proc_search_patient_ByID]
(
@PatID_pk int ,
@Cntid smallint,
@FamID int
)
AS
SET NOCOUNT ON
IF @Cntid IS NULL
BEGIN
--Use select stmt of a table
END
ELSE
--Use select stmt of another table
BEGIN
END
Likewise switch tables with appropriate parameters.
| {
"pile_set_name": "StackExchange"
} |
Q:
Shell script to get key value pair from JSON object
I have a JSON object like
{
"Men": [
"All Clothing",
"All Clothing",
"All footwear",
"All footwear",
"All Watches",
"All Watches",
"All Sunglasses",
"All Sunglasses"
],
"Electronics": [
"Mobiles",
"Tablets",
"Wearable Smart Devices",
"Mobile Accessories",
"Headphones and headsets",
"Tablet Accessories",
"Computer Accessories",
"Televisions",
"Large Appliances",
"Small Appliances",
"Kitchen Appliances",
"Personal Care",
"Audio and video",
"Laptop"
],
"Women": [
"Ethnic wear",
"Western wear",
"Lingerie & Sleep Wear",
"All Bags, Belts & Wallets",
"All jewellery",
"All Perfumes",
"Spectacle Frames",
"Beauty & Personal Care",
"The International Beauty Shop"
]
}
I want to get key value pair from this object.m using jq filter but it doesnot work.
keys=`jq 'keys' $categories`
$categories is the name of variable of json object. suggestions are welcome.
A:
It's not really clear what you are asking. If $categories contains your JSON data then you need to pipe it to jq somehow. With Bash, you could use a here string:
jq keys <<<"$categories"
or more traditionally (and portably), a pipe:
printf '%s\n' "$categories" | jq keys
To capture the value of the keys into a variable, use a command substitution:
keys=$(jq 'keys' <<<"$categories")
(or `backticks` like in your attempt; but the modern notation is much preferable);
or better yet, obtain this value in the same way you assigned categories in the first place.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mesh generation from points with x, y and z coordinates
Problem: Mesh generation from 3D points (with x, y and z coordinates).
What I have is points in 3D space (with x, y and z coordinates) you can see it in image 1.
What would be the output is image 2 or image 3, or image 4. In short it would be mesh. Material on it can be provided if I have the mesh.
I have seen many people say about Delaunay triangulations or constrained Delaunay triangulations will help me in mesh generation, but what I mostly found is its implementation in 2D points (with only x and Y coordinates).
But my problem is: I have points in 3D as you can see from image 1.
Will Delaunay triangulations or constrained Delaunay triangulations work fine with 3D Points? If yes, then how? Or do I have to find another algorithm for generating mesh from 3D points?
Note: One good explanation of Delaunay triangulations for 2D points can be found here
A:
here are some other good links for mesh generation and its related work.
• TetGen : A Quality Tetrahedral Mesh Generator http://wias-berlin.de/software/tetgen/
• CGal-Computational Geometry Algorithms Library
http://www.cgal.org/.
http://www.cgal.org/Manual/latest/doc_html/cgal_manual/packages.html#Pkg:Triangulation3.
http://www.cgal.org/Manual/latest/doc_html/cgal_manual/contents.html#part_VI.
http://www.cgal.org/Manual/latest/doc_html/cgal_manual/Surface_reconstruction_points_3/Chapter_main.html.
3D Surface Mesh Generation - http://www.cgal.org/Manual/3.3/doc_html/cgal_manual/Surface_mesher/Chapter_main.html
• GTSLibrary – The GNU Triangulated Surface Library.
http://gts.sourceforge.net/index.html
• Jonathan Shewchuk - http://www.cs.berkeley.edu/~jrs/
http://www.cs.cmu.edu/~quake/robust.html
• VTK: The Visualization Toolkit (VTK) is an open-source, freely available software system http://www.vtk.org/.
• Volume and Surface Meshing – http://www.cse.ohio-state.edu/~tamaldey/mesh.htm.
• Poly2Tri: An open source CDT library http://code.google.com/p/poly2tri/.
• CM2Mesh Tools – http://www.computing-objects.com/index.php.
• Adaptive tessellation – http://fluxionsdividebyzero.com/p1/math/geometry/g046.html#_3D
• CUBIT – The CUBIT Geometry and Mesh Generation Toolkit.
http://cubit.sandia.gov/index.html
• Geometry in Action - http://www.ics.uci.edu/~eppstein/geom.html
• SlimDX - SlimDX is a free open source framework that enables developers to easily build DirectX applications using .NET technologies such as C#, VB
http://slimdx.org/
A:
3D Delauny triangulation will result in a (3D) volume mesh. I suppose what you want is a (2D) surface mesh embedded in 3D which approximates the given point set.
Depending on the type of data (little or big noise, outliers, etc.) you can take different approaches. Note that you can always pre-process your data (e.g. to remove outliers, smooth the data, or estimate normals).
For oriented point set with little noise and no outliers, you can consider Poisson Surface Reconstruction (e.g. in Michael Kazhdan, M. Bolitho, and Hugues Hoppe. Poisson Surface Reconstruction. In Symp. on Geometry Processing, pages 61-70, 2005.).
Note that you can pre-process your data to fullfill the requirements, see for example Normal estimation. Here is a C++ library implementing Poisson Surface Reconstruction (with nice explanations): CGAL Surface Reconstruction from Point Sets
For scattered point data see for example Ohtake, Y.; Belyaev, A. & Seidel, H. P. A multi-scale approach to 3D scattered data interpolation with compactly supported basis functions Shape Modeling International, 2003, 2003, 153-161. It uses a hierarchical approach to create multiple interpolation levels.
Another approach for highly non-uniform or noisy scattered data is Zhao, H.-K.; Osher, S. & Fedkiw, R. Fast surface reconstruction using the level set method Variational and Level Set Methods in Computer Vision, 2001. Proceedings. IEEE Workshop on, 2001, 194-201. It uses variatonal methods and PDEs (particularly level set methods).
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP regex periods
How do I put a period into a PHP regular expression?
The way it is used in the code is:
echo(preg_match("/\$\d{1,}\./", '$645.', $matches));
But apparently the period in that $645. doesn't get recognized. Requesting tips on how to make this work.
A:
Since . is a special character, you need to escape it to have it literally, so \..
Remember to also escape the escape character if you want to use it in a string. So if you want to write the regular expression foo\.bar in a string declaration, it needs to be "foo\\.bar".
A:
Escape it. The period has a special meaning within a regular expression in that it represents any character — it's a wildcard. To represent and match a literal . it needs to be escaped which is done via the backslash \, i.e., \.
/[0-9]\.[ab]/
Matches a digit, a period, and "a" or "ab", whereas
/[0-9].[ab]/
Matches a digit, any single character1, and "a" or "ab".
Be aware that PHP uses the backslash as an escape character in double-quoted string, too. In these cases you'll need to doubly escape:
$single = '\.';
$double = "\\.";
UPDATE
This echo(preg_match("/\$\d{1,}./", '$645.', $matches)); could be rewritten as echo(preg_match('/\$\d{1,}\./', '$645.', $matches)); or echo(preg_match("/\\$\\d{1,}\\./", '$645.', $matches));. They both work.
1) Not linefeeds, unless configured via the s modifier.
| {
"pile_set_name": "StackExchange"
} |
Q:
Giving input 22222222222222222 for double but the output is 22222222222222224.000000 Why?
#include <stdio.h>
int main()
{
printf("Enter the number:");
double num;
scanf("%lf",&num);
printf("%lf\n",num);
}
Input:22222222222222222
Output:22222222222222224.000000
Why it is giving output not like given.
A:
A long double is typically implemented in the x86 extended precision format. The fraction part of that has 63 bits and has approximately 18 significant digits. Your number is 17 digits long, and what is happening is that the number is too large to precisely store in the 63 bits available.
If it is always going to be an integer (no decimal portion), then consider using a "long long" to represent this number.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access nested dictionary?
I can print this in the debugger:
(lldb) print params["message"]!
([String : String]) $R5 = 2 key/value pairs {
[0] = (key = "body", value = "iPadUser has started a new stream")
[1] = (key = "title", value = "Stream started")
}
But I am trying to figure out how to access the body and title separately.
I construct params in this way:
let recipients = ["custom_ids":[recips]]
let notificationDetails = "hello there"
let content = [
"title":title,
"body":details
]
let params: [String:Any] = [
"group_id":"stream_requested",
"recipients": recipients,
"message": content
]
A:
print((params["message"] as! [String: Any])["title"] as! String)
You need to cast the Dictionary value as specific type, since the compiler doesn't know what to expect. (Please mind that you mustn't use force unwrap in other way than example code.)
Considering you need to fetch array values when recipients dictionary looks like this:
let recipients = ["custom_ids":["recipe1", "recipe2", "etc"]]
get to the ids like this:
guard let recipients = params["recipients"] as? [String: Any],
let customIDs = recipients["custom_ids"] as? [String]
else { return }
for id in customIDs {
print(id) // Gets your String value
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What exactly does "non-expandable" memory mean?
I am trying to purchase a new laptop and want to put in more RAM manually and the model I'm looking at (Here's the link) says the memory is nonexpandable.
I assumed this meant that there isn't some easily accessible slot, so Toshiba doesn't want you messing around with it. But with a little know-how and a small enough screwdriver, you can get at the slots and upgrade.
However, when I asked the gentleman at best buy, he said that the advertised 4GB RAM is the maximum the motherboard can handle. So I'm not sure if that's true or if that's just something he has to say. Reviews online say that people put in more memory just fine so I'm very confused and don't want to buy it if I can't put at least 8GB of RAM in.
How can I know how much "a motherboard can handle"?
A:
Most Notebooks are cheap because they are exactly what they say they are.
First, you do due diligence by going to the manufacturer's website and look up whether the on-board memory can be upgraded. Non-expandable means that it already comes with maximum memory and there's not anything you can do to increase that. Toshiba specifically says:
4GB DDR3L 1600MHz (Memory is not user upgradeable, factory installed only)
Next, you have to find out what special means these reviews online are using to double the memory and if it's even applicable to your device. You don't want to be desoldering chips since you likely don't have the technical expertise. Several of the people who've tried find that aftermarket memory suppliers don't have any memory specs and therefore don't provide anything specific for this system and those who've tried to plug in 8GB have found it flat doesn't work. One mentions possibly upgrading it to the maximum of 6GB, but where he came up with that is unknown and might only be wishful thinking.
Just buy a laptop that's capable of running with 8GB and you'll be fine. This one's a pass.
Toshiba IS upfront about this so there's no reason to complain about it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Recovering from OutOfMemoryException
I have a method that needs to process a user-supplied file and if the file is complex enough I may encounter an OutOfMemoryException. In these cases I'm fine with the method failing however I would like the application to remain usable, the problem is that after getting an OutOfMemoryException I can't do anything since every course of action consumes memory.
I thought of putting aside some memory which I can free once the exception is throw so the rest of the application can carry on but it seems that the optimizer gets rid of this allocation.
public void DoStuff(string param)
{
try
{
#pragma warning disable 219
var waste = new byte[1024 * 1024 * 100]; // set aside 100 MB
#pragma warning restore 219
DoStuffImpl(param);
}
catch (OutOfMemoryException)
{
GC.Collect(); // Now `waste` is collectable, prompt the GC to collect it
throw; // re-throw OOM for treatment further up
}
}
Long story short my questions are:
Is there a better way to do what I'm attempting?
If not, is there a good reason why this is a bad idea?
Assuming this idea is the way to go, how do I force the JIT to not optimize away my wasted memory?
A:
I wouldn't rethrow an OOM exception, if the memory is already cleaned up.
Otherwise the outer code won't know that, and will think that it needs to free some more memory, whereas it actually doesn't need to.
So I'd opt for throwing a custom exception.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get tokens in Jison?
I'm using Jison for a college project, and I need to make a switch for each recognized token, so I can present to the professor something like:
<identifier, s>
<operator, =>
<identifier, a>
<operator, +>
<identifier, b>
Any way on how to get this done without recurring to regular expressions manually? (I mean, Jison uses regexp internally but that's not my business)
What I tried doing is the following:
var lex = parser.lexer,
token;
lex.setInput('The code to parse');
while (!lex.done) {
token = lex.next();
}
But the only thing I get saved in token is a number, and when a symbol is not defined in the grammar, it returns character-by-character token.
Thanks in advance.
A:
(Warning: Some of this answer was derived by examining code generated by jison. Since the interfaces are not well defined, it may not stand the test of time.)
parser.lexer.next() is not part of the documented lexer interface, although the lexical analyzer produced by jison does appear to implement it. Note that it does not produce a token, if the input consumed corresponds to a lexical rule which does not produce a token. (For example, a rule which ignores whitespace.) It is better to use the documented interface parser.lexer.lex(), which does always produce a token.
Strictly speaking, parser.lexer.lex() is documented as returning the name of a terminal, but for efficiency the lexical analyzers generated by jison will return the internal numerical code for the terminal if jison is able to figure out which terminal the lexical rule will return. So you have a couple of alternatives, if you want to trace the actual names of the terminals recognized:
You can defeat this optimization by avoiding the use of the form return <string>. For example, if you change the lexical rule:
[A-Za-z][A-Za-z0-9] { return 'IDENTIFIER`; }
to
[A-Za-z][A-Za-z0-9] { return '' + 'IDENTIFIER`; }
then the generated lexical analyzer will return the string 'IDENTIFIER' rather than some numeric code.
Alternatively, you can use parser.terminals_, which according to the comment at the top of the generated parser has the form terminals_: {associative list: number ==> name}, to look up the terminal name given the token number.
To get the source character string associated with the lexeme, use parser.lexer.yytext.
Here's a solution using the second alternative:
/* To reduce confusion, I change 'lex' to 'lexer' */
var lexer = parser.lexer,
token;
lexer.setInput('The code to parse');
while (!lexer.done) {
token = lexer.lex();
/* Look up the token name if necessary */
if (token in parser.terminals_) {
token = parser.terminals_[token];
}
console.log('<' + token + ', ' + lexer.yytext + '>')
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a Live Search in HTML for non-list items
I'm trying to create a live-search text box that will allow me to search my collapsible list menu, along with the nested collapsible in the HTML page.
Here is the HTML Code that I'm using (note it includes a .js and .css from external links)
<!DOCTYPE html>
<html>
<head>
<title>Experts List</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<style>
html, body {
padding: 0;
margin: 0;
}
html, .ui-mobile, .ui-mobile body {
height: 765px;
}
.ui-mobile, .ui-mobile .ui-page {
min-height: 765px;
}
.ui-content {
padding: 10px 15px 0px 15px;
}
</style>
</head>
<body>
<div>
<div role="main" class="ui-content">
<div data-role="collapsible" data-collapsed="true" data-theme="a" data-content-theme="a">
<h3>Category</h3>
<p>Description</p>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Sub-Category</h3>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Location</h3>
<p>Point of Contact</p>
</div><!-- /section 1A -->
</div><!-- /section 1 -->
</div>
<div data-role="collapsible" data-collapsed="true" data-theme="a" data-content-theme="a">
<h3>Subject</h3>
<p>Description</p>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Sub Category</h3>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Location</h3>
<p>Point of Contact</p>
</div>
</div>
</div>
<div data-role="collapsible" data-collapsed="true" data-theme="a" data-content-theme="a">
<h3>Subject</h3>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Section</h3>
<p>Defenition</p>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Location</h3>
<p>Point of Contact</p>
</div>
</div>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Subject2</h3>
<p>Defenition2</p>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Location2</h3>
<p>Point of Contact 2</p>
</div>
</div>
</div>
<div data-role="collapsible" data-collapsed="true" data-theme="a" data-content-theme="a">
<h3>Subject 3</h3>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Section 3</h3>
<p>Definition 3</p>
<div data-role="collapsible" data-theme="a" data-content-theme="a">
<h3>Location 3</h3>
<p>Point of Contact 3</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I already tried using and creating a live search in the HTML using the following code (along with .js and .css) from below. The only problem is that when I search through the HTML page using the text box it un-collapses all the sections. And when I delete any input in the text box it just stays as is, it doesn't revert back to it's original collapsed form.
Here is the jfiddle link https://jsfiddle.net/Lxt22gw1/
Can anyone help or at least point me in the right direction of what needs to be coded for the live search to search everything as upon deleting input it reverts the HTML back to the original collapsed version?
Thanks!
A:
As it stood, it looks like your jQuery expression was faulty. I changed it in a fork of your fiddle, and that seemed to work: https://jsfiddle.net/dgaz8n5k/
The faulty code was [data-search-term *= ' + searchTerm + '], which I changed to [data-search-term*="' + searchTerm + '"].
| {
"pile_set_name": "StackExchange"
} |
Q:
Are Mathematica's datasets valid?
I, being an avid Mma user, sometimes use its many datasets (such as ElementData) for golfing purposes. However, these require the Wolfram Research servers to have the data. As I'm not directly connecting to the Internet, I am wondering if this would be considered a loophole.
A:
I do consider them built-ins. Just because you sort of have to update your language (or language's standard library) before you can use them for the first time, doesn't mean you're fetching the result from the internet. Once Mathematica has downloaded the data from Wolfram Research, it's just part of the language and can be reused (even after restarting Mathematica or similar).
Whether built-ins are allowed or not depends on the particular challenge in question. Using built-ins is no longer an accepted standard loophole, so unless the challenge rules them out explicitly, any of the *Data functions should be fair game.
(Of course, it might be polite first to ask the OP if they intended to allow them if it's not mentioned either way in the spec.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Representing a logarithmic graph as a percentage by tending to 100
Preface: I am currently in college in my first year of maths, so some more intricate explanations may not be available to me.
The situation I am modelling is that of an engineer repairing a machine, the more work he does, the less of a result it has overall, a classic diminishing returns problem. I would like to represent the machines efficiency (how repaired it is) as a percentage or a number from one to one hundred.
A logarithmic function $r=\ln(w+1)$ can be used to describe the diminishing returns relationship between work done ($w$, in hours) and result ($r$). My problem lies in the fact that result tends to infinity, where I would prefer it tends to 100: $\lim\limits_{w\to \infty} r=\ln(w+1)=100$
In my understanding of maths, to represent a number from 1 to n as a percentage, you would do $\frac{number}{n}*100$, but obviously I cannot simply divide by infinity.
How could I modify this function so that it tends to 100 instead of infinity?
A:
You could use something like
$$
r(w) = 100 \left(1-\frac{a}{w-a} \right)
$$
and tweak the value of the parameter $a$ to your liking, for example $a=100$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why doesn't the method `shouldNotResolve` catch the rejected promise?
I would expect that a.shouldNotResolve() would 'catch' the rejected promise in a.cancelOrder, and return 'expected this to catch', but instead it resolves, returning 'promise resolved anyway'.
const a = {
cancelOrder: function(){
return Promise.reject('something broke')
.then((x) => {
return x;
})
.catch((e) => {
console.log('this caught the error', e);
});
},
shouldNotResolve: function() {
return this.cancelOrder()
.then(() => {
console.log('promise resolved anyway');
})
.catch(() => {
console.log('expected this to catch');
});
}
}
a.shouldNotResolve(); // "promise resolved anyway"
Why does a.cancelOrder reject, but a.shouldNotResolve resolves anyway?
Thank you.
A:
Because it's already caught ("catched"?) earlier in the chain, as seen in the cancelOrder function. If you want to catch it there but still pass the rejection down the chain you need to throw it again:
cancelOrder: function(){
return Promise.reject('something broke')
.then((x) => {
return x;
})
.catch((e) => {
console.log('this caught the error', e);
throw e;
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I conceal windows without any adhesive or replacing the vertical blinds?
Please see the pictures below. To reduce the light levels to aid in sleeping, how can I block sunlight and the midnight sun for the duration of the midnight sun e.g. 6 months? How can I blacken a bed-room? I must still access the balcony, so the balcony door mustn't be hindered.
I'm shunning any adhesive, because tape can damage surfaces and rip off paint. Let's treat removing the vertical blinds as a last resort.
Top to bottom. https://www.tripadvisor.com/ShowUserReviews-g155019-d8027415-r444957857-Natural_Light_and_Sweeping_City_Views_in_Downtown_Toronto-Toronto_Ontario.html. https://www.houzz.in/photos/vertical-blinds-in-a-downtown-condo-phvw-vp~45007999. https://windowcoveringstoronto.ca/blinds-toronto/condo-blinds/. https://dansblinds.ca/how-to-choose-window-coverings/.
A:
Assuming you have difficulties sleeping when the sun shines even at night, consider using a sleep mask instead of blocking all of those windows. I often sleep with a mask in summer and a well-fitted one stays in place all night long, so you can put it on in the evening and still be protected in the morning.
Unfortunately there are vast differences in quality between different masks.
Make sure it fits you very well around the nose and cheeks. That's where you'll be most bothered by light.
Make sure the material is thick enough to block light. Black fabric is the safest bet, but even a very thin black mask will let some light through.
Make sure it's comfortable enough to sleep with. Some masks are quite bulky and might hurt you when sleeping on your side.
Make sure the strap(s) is/are adjustable to your individual size. If you can handle a needle and thread, you can shorten the strap with a few stitches.
I ended up sewing my own sleep mask, which is a very easy beginners project and lets me adjust the mask to my preferences perfectly.
A:
If you're looking for something lifehacky for this and you're not too bothered about the end result aesthetic you could lifehack upgrade the blinds. I make this recommendation instead of suggesting window films, sleep masks etc because you didn't state this was just for sleeping, or that you want it dark all the time. By having the blinds better able to regulate the light you can hopefully adjust the room brightness on demand, keep a sensible circadian rhythm, mimic the natural day/night cycle, have darker evening hours but still be able to move around the room as normal etc. To this end I think you'll need a solution that doesn't involve wearing masks, making the windows opaque etc
I suggest that you could:
Obtain a roll of paper, such as wallpaper with a reasonable pattern, or colored paper like kids use in arts class
Measure the width and length of a blind slat
Cut a strip of paper the length of the blind slat and twice its width plus 20mm
Fold the paper in half along the length so it's like a very tall book (with two pages)
Fit it onto the blind slat, from the window side ("spine" towards window), so that the "pages" of the fold are either side of the slat
Use a stapler to staple the protruding ~10mm bits of paper together, putting the staple through the "pages" but not the blinds
You could alternatively consider using something like bobby pins/hair grips or paper clips to hold the paper in place - you might not need the protruding 20mm in this case. Tape may also work if you leave a small protrusion but it does tend to degrade in sunlight
The aim is to turn your blinds into blackout blinds by making them more opaque with a thin and cheap material. I picked wallpaper because it's probably quite easy to obtain something good looking and opaque
Fitting the paper so the staples are on the window side will be more awkward but give a better look
If this works well for you physiologically/psychologically you could consider replacing the blind slats with a blackout material - more expensive but worth it if you know it will work
Note: the easiest way to make a good straight cut is with craft knife (x-acto knife, Stanley knife or whatever your country calls it) or razor blade, run down the edge of a long straight bar/ruler with the paper resting on a temporary surface that can be discarded after it has been ruined by the repeated cuts with the knife (an opened out large cardboard box perhaps)
A:
Have you heard of static cling?
Some kinds of plastic film will stick to glass without adhesive using only static electricity. When you do not want the effect, you peel it off and roll it up for storage. Unroll it for reuse. Easy on, easy off.
You would be most interested in Light Block Window Film. There are all different kinds of window films—UV blocking films, IR blocking films, and various kinds of patterns and opacities up to total block out. You might even be interested in gradation from clear to opaque.
Solid white can also block light from the outside and has the added benefit of a bright interior with normal room illumination if you don't want to open blocked windows.
The stuff can be found in major hardware stores and home renovation centres.
Good luck
| {
"pile_set_name": "StackExchange"
} |
Q:
Geometry question with rectangles purely out of curiosity
Apologies in advance, I really cannot think of an intelligent or easy way to explain this.
You start out with a rectangle. Then you draw a straight line out of a right angled corner at 45 degrees until you hit a side of the rectangle at which point you reflect the line at 90 degrees and continue the line. Repeat this process until the line goes into a second corner.
Sorry if that image is hard to imagine.
If you add the length and width of the rectangle (providing they are both integers and have no common factors) that is the number of points of contact the lines have with the outline of the rectangle: (the walls and the 2 corners)
If the lengths aren't integers then you have to make then integers before you add them eg. 0.2cm and 0.3cm = 2cm and 3cm. Or if they have factors then factorise them eg. 6cm and 4cm = 3cm and 2cm
QUESTION
If anyone understands all of that, can anyone explain if and why that is true for every rectangle? Is it just a coincidence or is there maths behind it that I can't find? And can it work if one of the lengths was an irrational number like pi?
A:
Imagine tiling the plane with your rectangles. Then instead of reflecting, you just keep on going through them. You are asking where you hit the image of one of the corners. If your rectangles are $m$ high and $n$ wide with $m,n$ coprime, you will go through $n$ rectangles upward and $m$ rectangles leftward until you hit point $(mn,mn)$
If the ratio of lengths is irrational, you will never hit another corner. The same tiling argument shows it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I calculate percent difference between max and min values in consecutive rows by group?
Request
I was able to identify the minimum and maximum in_state_total values by the group. I would like to add another column that calculates the percent difference between the maximum value and the minimum value for each group. The result should occupy both rows for each group so I can further sort the data before plotting. I would prefer a dplyr approach, but am open to exploring other options in order to deepen my understanding of the issue and the potential solutions.
Current Code
tuition_cost_clean %>%
filter(degree_length == "4 Year") %>%
arrange(state, desc(in_state_total)) %>%
group_by(state_abbr) %>%
slice(which.max(in_state_total), which.min(in_state_total)) %>%
select(name, state_abbr, in_state_total)
Current Output
name state_abbr in_state_total
<chr> <chr> <dbl>
Alaska Pacific University AK 28130
Alaska Bible College AK 15000
Spring Hill College AL 52926
Huntsville Bible College AL 5390
Hendrix College AR 58074
University of Arkansas for Medical Sciences AR 8197
Desired Output
name state_abbr in_state_total pct_change
<chr> <chr> <dbl>
Alaska Pacific University AK 28130 46.6761%
Alaska Bible College AK 15000 46.6761%
Spring Hill College AL 52926 89.816%
Huntsville Bible College AL 5390 89.816%
Hendrix College AR 58074 85.8852%
University of Arkansas for Medical Sciences AR 8197 85.8852%
Data
tuition_cost_clean <- structure(list(name = c("Aaniiih Nakoda College", "Abilene Christian University",
"Abraham Baldwin Agricultural College", "Academy College", "Academy of Art University",
"Adams State University", "Adelphi University", "Adirondack Community College",
"Adrian College", "Advanced Technology Institute", "Adventist University of Health Sciences",
"Agnes Scott College", "Aiken Technical College", "Aims Community College",
"Alabama Agricultural and Mechanical University", "Alabama Southern Community College",
"Alabama State University", "Alamance Community College", "Alaska Bible College",
"Alaska Pacific University", "Albany College of Pharmacy and Health Sciences",
"Albany State University", "Albany Technical College", "Albertus Magnus College",
"Albion College", "Albright College", "Alcorn State University",
"Alderson-Broaddus University", "Alexandria Technical and Community College",
"Alfred University", "Allan Hancock College", "Allegany College of Maryland",
"Allegheny College", "Allegheny Wesleyan College", "Allen College",
"Allen County Community College", "Allen University", "Alliant International University",
"Alma College", "Alpena Community College", "Alvernia University",
"Alverno College", "Alvin Community College", "Amarillo College",
"Amberton University", "American Academy McAllister Institute of Funeral Service",
"American Academy of Art", "American Academy of Dramatic Arts",
"American Academy of Dramatic Arts: West", "American Baptist College",
"American Indian College of the Assemblies of God", "American International College",
"American Jewish University", "American National University: Charlottesville",
"American National University: Danville", "American National University: Harrisonburg",
"American National University: Lynchburg", "American National University: Martinsville",
"American National University: Salem", "American University SystemFor-profit",
"American River College", "American Samoa Community College",
"American University", "American University of Puerto Rico",
"Amherst College", "Amridge University", "Ancilla College", "Anderson University",
"Anderson University", "Andrew College", "Andrews University",
"Angelina College", "Angelo State University", "Anna Maria College",
"Anne Arundel Community College", "Anoka Technical College",
"Anoka-Ramsey Community College", "Antelope Valley College",
"Antioch College", "Antioch University Los Angeles", "Antioch University Midwest",
"Antioch University Santa Barbara", "Antioch University Seattle",
"Apex School of Theology", "Appalachian Bible College", "Appalachian State University",
"Aquinas College", "Aquinas College", "Arapahoe Community College",
"Arcadia University", "Arizona Christian University", "Arizona State University",
"Arizona Western College", "Arkansas Baptist College", "Arkansas Northeastern College",
"Arkansas State University", "Arkansas State University Mid-South",
"Arkansas State University: Beebe", "Arkansas State University: Mountain Home",
"Arkansas State University: Newport", "Arkansas Tech University",
"Arlington Baptist University", "Armstrong State University",
"Art Academy of Cincinnati", "Art Center College of Design",
"Art Institute of Houston", "Art Institute of Philadelphia",
"Art Institute of Phoenix", "Art Institute of Pittsburgh", "ASA College",
"Asbury University", "Asheville-Buncombe Technical Community College",
"Ashford University", "Ashland Community and Technical College",
"Ashland University", "Ashworth College", "Asnuntuck Community College",
"Assumption College", "Assumption College for Sisters", "Athens State University",
"Athens Technical College", "Atlanta Metropolitan State College",
"Atlanta Technical College", "Atlantic Cape Community College",
"Atlantic University College", "Auburn University", "Auburn University at Montgomery",
"Augsburg University", "Augusta Technical College", "Augusta University",
"Augustana College", "Augustana University", "Aultman College of Nursing and Health Sciences",
"Aurora University", "Austin College", "Austin Community College",
"Austin Graduate School of Theology", "Austin Peay State University",
"Ave Maria University", "Averett University", "Avila University",
"Azusa Pacific University", "Babson College", "Baker University",
"Bakersfield College", "Baldwin Wallace University", "Ball State University",
"Baltimore City Community College", "Baptist Bible College",
"Baptist College of Florida", "Baptist College of Health Sciences",
"Baptist Missionary Association Theological Seminary", "Baptist University of the Americas",
"Barclay College", "Bard College", "Bard College at Simon's Rock",
"Barnard College", "Barry University", "Barstow Community College",
"Barton College", "Barton County Community College", "Bastyr University",
"Bates College", "Bates Technical College", "Baton Rouge Community College",
"Bay College", "Bay Mills Community College", "Bay Path University",
"Bay State College", "Bayamon Central University", "Baylor University",
"Beacon College", "Beaufort County Community College", "Becker College",
"Beckfield College", "Beis Medrash Heichal Dovid", "Belhaven University",
"Bellarmine University", "Bellevue College", "Bellevue University",
"Bellin College", "Bellingham Technical College", "Belmont Abbey College",
"Belmont College", "Belmont University", "Beloit College", "Bemidji State University",
"Benedict College", "Benedictine College", "Benedictine University",
"Benjamin Franklin Institute of Technology", "Bennett College for Women",
"Bennington College", "Bentley University", "Berea College",
"Bergen Community College", "Bergin University of Canine Studies",
"Berkeley City College", "Berklee College of Music", "Berkshire Community College"
), state = c("Montana", "Texas", "Georgia", "Minnesota", "California",
"Colorado", "New York", "New York", "Michigan", "Virginia", "Florida",
"Georgia", "South Carolina", "Colorado", "Alabama", "Alabama",
"Alabama", "North Carolina", "Alaska", "Alaska", "New York",
"Georgia", "Georgia", "Connecticut", "Michigan", "Pennsylvania",
"Mississippi", "West Virginia", "Minnesota", "New York", "California",
"Maryland", "Pennsylvania", "Ohio", "Iowa", "Kansas", "South Carolina",
"California", "Michigan", "Michigan", "Pennsylvania", "Wisconsin",
"Texas", "Texas", "Texas", "New York", "Illinois", "New York",
"California", "Tennessee", "Arizona", "Massachusetts", "California",
"Virginia", "Virginia", "Virginia", "Virginia", "Virginia", "Virginia",
"West Virginia", "California", NA, NA, NA, "Massachusetts", "Alabama",
"Indiana", "South Carolina", "Indiana", "Georgia", "Michigan",
"Texas", "Texas", "Massachusetts", "Maryland", "Minnesota", "Minnesota",
"California", "Ohio", "California", "Ohio", "California", "Washington",
"North Carolina", "West Virginia", "North Carolina", "Michigan",
"Tennessee", "Colorado", "Pennsylvania", "Arizona", "Arizona",
"Arizona", "Arkansas", "Arkansas", "Arkansas", "Arkansas", "Arkansas",
"Arkansas", "Arkansas", "Arkansas", "Texas", "Georgia", "Ohio",
"California", "Texas", "Pennsylvania", "Arizona", "Pennsylvania",
"New York", "Kentucky", "North Carolina", "California", "Kentucky",
"Ohio", "Georgia", "Connecticut", "Massachusetts", "New Jersey",
"Alabama", "Georgia", "Georgia", "Georgia", "New Jersey", NA,
"Alabama", "Alabama", "Minnesota", "Georgia", "Georgia", "Illinois",
"South Dakota", "Ohio", "Illinois", "Texas", "Texas", "Texas",
"Tennessee", "Florida", "Virginia", "Missouri", "California",
"Massachusetts", "Kansas", "California", "Ohio", "Indiana", "Maryland",
"Missouri", "Florida", "Tennessee", "Texas", "Texas", "Kansas",
"New York", "Massachusetts", "New York", "Florida", "California",
"North Carolina", "Kansas", "Washington", "Maine", "Washington",
"Louisiana", "Michigan", "Michigan", "Massachusetts", "Massachusetts",
NA, "Texas", "Florida", "North Carolina", "Massachusetts", "Kentucky",
"New York", "Mississippi", "Kentucky", "Washington", "Nebraska",
"Wisconsin", "Washington", "North Carolina", "Ohio", "Tennessee",
"Wisconsin", "Minnesota", "South Carolina", "Kansas", "Illinois",
"Massachusetts", "North Carolina", "Vermont", "Massachusetts",
"Kentucky", "New Jersey", "California", "California", "Massachusetts",
"Massachusetts"), state_code = c("MT", "TX", "GA", "MN", "CA",
"CO", "NY", "NY", "MI", "VA", "FL", "GA", "SC", "CO", "AL", "AL",
"AL", "NC", "AK", "AK", "NY", "GA", "GA", "CT", "MI", "PA", "MS",
"WV", "MN", "NY", "CA", "MD", "PA", "OH", "IA", "KS", "SC", "CA",
"MI", "MI", "PA", "WI", "TX", "TX", "TX", "NY", "IL", "NY", "CA",
"TN", "AZ", "MA", "CA", "VA", "VA", "VA", "VA", "VA", "VA", "WV",
"CA", "AS", "DC", "PR", "MA", "AL", "IN", "SC", "IN", "GA", "MI",
"TX", "TX", "MA", "MD", "MN", "MN", "CA", "OH", "CA", "OH", "CA",
"WA", "NC", "WV", "NC", "MI", "TN", "CO", "PA", "AZ", "AZ", "AZ",
"AR", "AR", "AR", "AR", "AR", "AR", "AR", "AR", "TX", "GA", "OH",
"CA", "TX", "PA", "AZ", "PA", "NY", "KY", "NC", "CA", "KY", "OH",
"GA", "CT", "MA", "NJ", "AL", "GA", "GA", "GA", "NJ", "PR", "AL",
"AL", "MN", "GA", "GA", "IL", "SD", "OH", "IL", "TX", "TX", "TX",
"TN", "FL", "VA", "MO", "CA", "MA", "KS", "CA", "OH", "IN", "MD",
"MO", "FL", "TN", "TX", "TX", "KS", "NY", "MA", "NY", "FL", "CA",
"NC", "KS", "WA", "ME", "WA", "LA", "MI", "MI", "MA", "MA", "PR",
"TX", "FL", "NC", "MA", "KY", "NY", "MS", "KY", "WA", "NE", "WI",
"WA", "NC", "OH", "TN", "WI", "MN", "SC", "KS", "IL", "MA", "NC",
"VT", "MA", "KY", "NJ", "CA", "CA", "MA", "MA"), type = c("Public",
"Private", "Public", "For Profit", "For Profit", "Public", "Private",
"Public", "Private", "For Profit", "Private", "Private", "Public",
"Public", "Public", "Public", "Public", "Public", "Private",
"Private", "Private", "Public", "Public", "Private", "Private",
"Private", "Public", "Private", "Public", "Private", "Public",
"Public", "Private", "Private", "Private", "Public", "Private",
"Private", "Private", "Public", "Private", "Private", "Public",
"Public", "Private", "Private", "Private", "Private", "Private",
"Private", "Private", "Private", "Private", "For Profit", "For Profit",
"For Profit", "For Profit", "For Profit", "For Profit", "Public",
"Public", "Public", "Private", "Private", "Private", "Private",
"Private", "Private", "Private", "Private", "Private", "Public",
"Public", "Private", "Public", "Public", "Public", "Public",
"Private", "Private", "Private", "Private", "Private", "Private",
"Private", "Public", "Private", "Private", "Public", "Private",
"Private", "Public", "Public", "Private", "Public", "Public",
"Public", "Public", "Public", "Public", "Public", "Private",
"Public", "Private", "Private", "For Profit", "For Profit", "For Profit",
"For Profit", "For Profit", "Private", "Public", "For Profit",
"Public", "Private", "For Profit", "Public", "Private", "Private",
"Public", "Public", "Public", "Public", "Public", "Private",
"Public", "Public", "Private", "Public", "Public", "Private",
"Private", "Private", "Private", "Private", "Public", "Private",
"Public", "Private", "Private", "Private", "Private", "Private",
"Private", "Public", "Private", "Public", "Public", "Private",
"Private", "Private", "Private", "Private", "Private", "Private",
"Private", "Private", "Private", "Public", "Private", "Public",
"Private", "Private", "Public", "Public", "Public", "Public",
"Private", "For Profit", "Private", "Private", "Private", "Public",
"Private", "For Profit", "Private", "Private", "Private", "Public",
"Private", "Private", "Public", "Private", "Public", "Private",
"Private", "Public", "Private", "Private", "Private", "Private",
"Private", "Private", "Private", "Private", "Public", "Private",
"Public", "Private", "Public"), degree_length = c("2 Year", "4 Year",
"2 Year", "2 Year", "4 Year", "4 Year", "4 Year", "2 Year", "4 Year",
"2 Year", "4 Year", "4 Year", "2 Year", "2 Year", "4 Year", "2 Year",
"4 Year", "2 Year", "4 Year", "4 Year", "4 Year", "4 Year", "2 Year",
"4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "2 Year", "4 Year",
"2 Year", "2 Year", "4 Year", "4 Year", "4 Year", "2 Year", "4 Year",
"4 Year", "4 Year", "2 Year", "4 Year", "4 Year", "2 Year", "2 Year",
"4 Year", "2 Year", "4 Year", "2 Year", "2 Year", "4 Year", "4 Year",
"4 Year", "4 Year", "2 Year", "2 Year", "2 Year", "2 Year", "2 Year",
"4 Year", "4 Year", "2 Year", "2 Year", "4 Year", "4 Year", "4 Year",
"4 Year", "2 Year", "4 Year", "4 Year", "2 Year", "4 Year", "2 Year",
"4 Year", "4 Year", "2 Year", "2 Year", "2 Year", "2 Year", "4 Year",
"4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "4 Year",
"4 Year", "4 Year", "2 Year", "4 Year", "4 Year", "4 Year", "2 Year",
"4 Year", "2 Year", "4 Year", "2 Year", "2 Year", "2 Year", "2 Year",
"4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "4 Year",
"4 Year", "4 Year", "2 Year", "4 Year", "2 Year", "4 Year", "2 Year",
"4 Year", "2 Year", "2 Year", "4 Year", "2 Year", "4 Year", "2 Year",
"2 Year", "2 Year", "2 Year", "4 Year", "4 Year", "4 Year", "4 Year",
"2 Year", "4 Year", "4 Year", "4 Year", "2 Year", "4 Year", "4 Year",
"2 Year", "4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "4 Year",
"4 Year", "4 Year", "2 Year", "4 Year", "4 Year", "2 Year", "4 Year",
"4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "4 Year",
"4 Year", "4 Year", "2 Year", "4 Year", "2 Year", "4 Year", "4 Year",
"2 Year", "2 Year", "2 Year", "2 Year", "4 Year", "2 Year", "4 Year",
"4 Year", "4 Year", "2 Year", "4 Year", "4 Year", "4 Year", "4 Year",
"4 Year", "2 Year", "4 Year", "4 Year", "2 Year", "4 Year", "2 Year",
"4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "4 Year", "2 Year",
"4 Year", "4 Year", "4 Year", "4 Year", "2 Year", "4 Year", "2 Year",
"4 Year", "2 Year"), room_and_board = c(NA, 10350, 8474, NA,
16648, 8782, 16030, 11660, 11318, NA, 4200, 12330, NA, NA, 8379,
NA, 5422, NA, 5700, 7300, 10920, 8878, NA, 13200, 12380, 12070,
9608, 8860, NA, 12516, NA, NA, 12140, 4000, 7282, 5070, 7230,
NA, 10998, NA, NA, 8546, NA, NA, NA, NA, NA, 17955, 13255, 8640,
6250, 14300, 17362, NA, NA, NA, NA, NA, NA, NA, NA, NA, 14880,
NA, 14740, NA, 9600, 9830, 9890, 10636, 9078, 5500, 9130, 14630,
NA, NA, NA, NA, 7640, NA, NA, NA, NA, NA, 7960, 8304, 9332, NA,
NA, 13800, 10674, 12648, 6700, 8826, NA, 8160, NA, 5280, NA,
NA, 7870, 6500, 11385, 6700, NA, 9600, NA, 10928, 2758, 9500,
7160, NA, NA, NA, 9941, NA, NA, 12694, NA, NA, NA, NA, NA, NA,
NA, 13332, 6980, 10280, NA, 9640, 10572, 8248, NA, 11700, 12527,
NA, NA, 10700, 11436, 9976, 7200, 10076, 16312, 8410, NA, 9554,
10234, NA, 7500, 4612, 2900, 3150, 2500, 9300, 15488, 14916,
17225, 11100, NA, 10120, 5794, 7590, 15224, NA, NA, 3200, NA,
12799, 13300, NA, 12595, 11390, NA, 13800, NA, 4500, 8500, 12250,
NA, 8730, NA, NA, 10355, NA, 12120, 8830, 8408, 6200, 10300,
9480, 12400, 8114, 15610, 16320, 6764, NA, NA, NA, 18180, NA),
in_state_tuition = c(2380, 34850, 4128, 17661, 27810, 9440,
38660, 5375, 37087, 13680, 15150, 41160, 5160, 2281, 9698,
4440, 11068, 2310, 9300, 20830, 35105, 6726, 3246, 32060,
45775, 45306, 7144, 27910, 5416, 33484, 1418, 4140, 47540,
6400, 19970, 3150, 13340, 18000, 40258, 4530, 34885, 28302,
1998, 2670, 12840, 17160, 34100, 35160, 35160, 10950, 958,
35680, 31826, 18735, 18735, 18735, 18735, 18735, 18735, 8150,
1416, 3700, 48459, 6946, 56426, 6900, 17330, 28000, 30450,
17388, 29288, 2625, 8489, 37860, 4110, 5584, 5073, 1420,
35718, 20670, 16210, 22575, 27435, 6200, 14720, 7214, 32574,
23600, 4811, 43580, 26796, 10822, 2520, 8760, 2450, 8608,
3274, 3600, 3570, 3480, 9068, 13190, 6384, 33889, 43416,
24024, 14850, 21645, 23376, 14065, 30198, 2354, 12160, 5310,
21342, 1399, 4404, 40958, 5888, 6810, 3292, 4008, 3350, 5096,
4525, 11276, 10288, 38800, 3494, 10758, 42135, 33018, 18510,
24260, 39985, 2550, 11900, 8411, 20850, 34400, 19900, 38880,
51104, 29830, 1418, 32586, 9896, 2893, 14150, 12300, 14700,
6690, 7800, 19690, 54680, 55732, 55032, 29850, 1391, 30880,
3440, 26166, 53794, 4783, 3981, 4830, 3250, 34225, 27750,
5775, 45727, 39016, 2344, 39200, 4000, 9500, 25300, 42200,
4258, 9390, 22178, 2790, 18500, 4973, 34310, 50040, 8696,
16600, 29530, 34290, 18690, 18513, 54360, 49880, 39990, 5610,
9450, 1432, 42750, 8569), in_state_total = c(2380, 45200,
12602, 17661, 44458, 18222, 54690, 17035, 48405, 13680, 19350,
53490, 5160, 2281, 18077, 4440, 16490, 2310, 15000, 28130,
46025, 15604, 3246, 45260, 58155, 57376, 16752, 36770, 5416,
46000, 1418, 4140, 59680, 10400, 27252, 8220, 20570, 18000,
51256, 4530, 34885, 36848, 1998, 2670, 12840, 17160, 34100,
53115, 48415, 19590, 7208, 49980, 49188, 18735, 18735, 18735,
18735, 18735, 18735, 8150, 1416, 3700, 63339, 6946, 71166,
6900, 26930, 37830, 40340, 28024, 38366, 8125, 17619, 52490,
4110, 5584, 5073, 1420, 43358, 20670, 16210, 22575, 27435,
6200, 22680, 15518, 41906, 23600, 4811, 57380, 37470, 23470,
9220, 17586, 2450, 16768, 3274, 8880, 3570, 3480, 16938,
19690, 17769, 40589, 43416, 33624, 14850, 32573, 26134, 23565,
37358, 2354, 12160, 5310, 31283, 1399, 4404, 53652, 5888,
6810, 3292, 4008, 3350, 5096, 4525, 24608, 17268, 49080,
3494, 20398, 52707, 41266, 18510, 35960, 52512, 2550, 11900,
19111, 32286, 44376, 27100, 48956, 67416, 38240, 1418, 42140,
20130, 2893, 21650, 16912, 17600, 9840, 10300, 28990, 70168,
70648, 72257, 40950, 1391, 41000, 9234, 33756, 69018, 4783,
3981, 8030, 3250, 47024, 41050, 5775, 58322, 50406, 2344,
53000, 4000, 14000, 33800, 54450, 4258, 18120, 22178, 2790,
28855, 4973, 46430, 58870, 17104, 22800, 39830, 43770, 31090,
26627, 69970, 66200, 46754, 5610, 9450, 1432, 60930, 8569
), out_of_state_tuition = c(2380, 34850, 12550, 17661, 27810,
20456, 38660, 9935, 37087, 13680, 15150, 41160, 8010, 13018,
17918, 8880, 19396, 8070, 9300, 20830, 35105, 19802, 5916,
32060, 45775, 45306, 7144, 27910, 5416, 33484, 7898, 9210,
47540, 6400, 19970, 3150, 13340, 18000, 40258, 6840, 34885,
28302, 4818, 5880, 12840, 17160, 34100, 35160, 35160, 10950,
958, 35680, 31826, 18735, 18735, 18735, 18735, 18735, 18735,
8150, 9546, 3700, 48459, 6946, 56426, 6900, 17330, 28000,
30450, 17388, 29288, 5535, 20939, 37860, 12180, 5584, 5073,
9760, 35718, 20670, 16210, 22575, 27435, 6200, 14720, 22021,
32574, 23600, 18671, 43580, 26796, 28336, 9510, 8760, 4250,
15298, 5014, 5760, 5580, 5310, 15848, 13190, 19866, 33889,
43416, 24024, 14850, 21645, 23376, 14065, 30198, 8114, 12160,
18000, 21342, 1399, 13170, 40958, 5888, 12870, 5962, 12088,
6020, 8096, 4525, 30524, 22048, 38800, 6164, 29796, 42135,
33018, 18510, 24260, 39985, 13020, 11900, 24467, 20850, 34400,
19900, 38880, 51104, 29830, 7838, 32586, 26468, 6973, 14150,
12300, 14700, 6690, 7800, 19690, 54680, 55732, 55032, 29850,
9131, 30880, 3440, 26166, 53794, 10214, 8059, 8910, 3250,
34225, 27750, 5775, 45727, 39016, 8104, 39200, 4000, 9500,
25300, 42200, 9689, 9390, 22178, 3460, 18500, 8070, 34310,
50040, 8696, 16600, 29530, 34290, 18690, 18513, 54360, 49880,
39990, 10650, 9450, 9622, 42750, 15589), out_of_state_total = c(2380,
45200, 21024, 17661, 44458, 29238, 54690, 21595, 48405, 13680,
19350, 53490, 8010, 13018, 26297, 8880, 24818, 8070, 15000,
28130, 46025, 28680, 5916, 45260, 58155, 57376, 16752, 36770,
5416, 46000, 7898, 9210, 59680, 10400, 27252, 8220, 20570,
18000, 51256, 6840, 34885, 36848, 4818, 5880, 12840, 17160,
34100, 53115, 48415, 19590, 7208, 49980, 49188, 18735, 18735,
18735, 18735, 18735, 18735, 8150, 9546, 3700, 63339, 6946,
71166, 6900, 26930, 37830, 40340, 28024, 38366, 11035, 30069,
52490, 12180, 5584, 5073, 9760, 43358, 20670, 16210, 22575,
27435, 6200, 22680, 30325, 41906, 23600, 18671, 57380, 37470,
40984, 16210, 17586, 4250, 23458, 5014, 11040, 5580, 5310,
23718, 19690, 31251, 40589, 43416, 33624, 14850, 32573, 26134,
23565, 37358, 8114, 12160, 18000, 31283, 1399, 13170, 53652,
5888, 12870, 5962, 12088, 6020, 8096, 4525, 43856, 29028,
49080, 6164, 39436, 52707, 41266, 18510, 35960, 52512, 13020,
11900, 35167, 32286, 44376, 27100, 48956, 67416, 38240, 7838,
42140, 36702, 6973, 21650, 16912, 17600, 9840, 10300, 28990,
70168, 70648, 72257, 40950, 9131, 41000, 9234, 33756, 69018,
10214, 8059, 12110, 3250, 47024, 41050, 5775, 58322, 50406,
8104, 53000, 4000, 14000, 33800, 54450, 9689, 18120, 22178,
3460, 28855, 8070, 46430, 58870, 17104, 22800, 39830, 43770,
31090, 26627, 69970, 66200, 46754, 10650, 9450, 9622, 60930,
15589)), row.names = c(NA, -200L), class = c("tbl_df", "tbl",
"data.frame"))
A:
You can use diff/lag to calculate difference :
library(dplyr)
tuition_cost_clean %>%
filter(degree_length == "4 Year") %>%
arrange(state, desc(in_state_total)) %>%
group_by(state_code) %>%
slice(which.max(in_state_total), which.min(in_state_total)) %>%
mutate(pct_change = -diff(in_state_total)/max(in_state_total) * 100) %>%
select(name, state_code, in_state_total, pct_change)
# name state_code in_state_total pct_change
# <chr> <chr> <dbl> <dbl>
# 1 Alaska Pacific University AK 28130 46.7
# 2 Alaska Bible College AK 15000 46.7
# 3 Auburn University AL 24608 72.3
# 4 Athens State University AL 6810 72.3
# 5 Arkansas Baptist College AR 17586 4.65
# 6 Arkansas State University AR 16768 4.65
# 7 Arizona Christian University AZ 37470 80.8
# 8 American Indian College of the Assemblies of God AZ 7208 80.8
# 9 American Jewish University CA 49188 80.8
#10 Bergin University of Canine Studies CA 9450 80.8
# … with 62 more rows
| {
"pile_set_name": "StackExchange"
} |
Q:
How to modify create method?
i have this model:
public class UsuarioMusica
{
public int UsuarioMusicaId { get; set; }
public int UserId { get; set; }
public int MusicId {get; set;}
}
And i generate a controller and view, but I'll talk only about the create method.
My problem is, I need to take the UserId from logged user and "MusicId" to do a relation at table, right? So, I created a search view and search method in music controller, that list all music saved at music model, search view:
@model IEnumerable<TestTcc2.Models.Musica>
@{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_LayoutOuvinte.cshtml";
}
<h2>Busca de Música</h2>
<table class="table table-hover table-bordered">
<tr>
<th>
<span>Genero</span>
</th>
<th>
<span>Nome</span>
</th>
<th>
<span>Artista</span>
</th>
<th>
<span>Preço</span>
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.genero.Nome)
</td>
<td>
@Html.DisplayFor(modelItem => item.Nome)
</td>
<td>
@Html.DisplayFor(modelItem => item.NomeArtista)
</td>
<td>
@Html.DisplayFor(modelItem => item.Preco)
</td>
<td>
@Html.ActionLink("Play", "", new { path = item.path }) |
</td>
</tr>
}
</table>
My Idea is, in this view, I'll create a new link for each row like @Html.ActionLink("Add music to my collection", "Create", "UsuarioMusica" }) that will call the create method and will add to usuarioMusica model the userId from logged user and musicId from music listed at table.
But I don't have idea how to do this on create method at UsuarioMusica controller, actually, this is my create method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UsuarioMusica usuariomusica)
{
if (ModelState.IsValid)
{
db.UsuarioMusicas.Add(usuariomusica);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(usuariomusica);
}
The principal dificulty here, is how to modify the create method to take the userID, musicID from music in row that user create on link "Add music to my collection" and save at UsuarioMusica table.
A:
@Html.ActionLink is a redirect to a GET method. You would need to include a <form> element for each row that posts the items ID. However this would mean recreating the view each time you post, so you will greatly improve performance using ajax.
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(m => item.genero.Nome)
</td>
......
<td>
<button type="button" class="addmusic" data-id="@item.MusicaId">Add</button>
</td>
}
Note the items ID is added to the buttons data attributes so it can be retrieved in the script
Script
var url = '@Url.Action("Create", "YourControllerName")'; // adjust to suit
$('.addmusic').click(function() {
var self = $(this);
// Get the ID
var id = self.data('id');
// post the value
$.post(url, { musicaID: id }, function(data) {
if(data) {
// remove the button so the item cannot be added more than once
self.remove();
} else {
// Oops, something went wrong - display message?
}
});
});
Note: to remove the items row from the DOM (not just the button), use
if(data) {
var row = self.closest('tr')
row.remove();
}
And the controller
[HttpPost]
public JsonResult Create(int musicaID)
{
var userID = // you should know this on the server
// call a service that saves the userID and musicaID to the database
var usuariomusica = new UsuarioMusica()
{
UserId = userID,
MusicId = musicaID
};
db.UsuarioMusicas.Add(usuariomusica);
db.SaveChanges();
return Json(true);
}
Note: If the save method fails, then use return Json(null) so the script is informed there was a failure. Note also the absence of [ValidateAntiForgeryToken]. If you want this, then the token also need to be passed in the ajax request as follows
var token = $('input[name="__RequestVerificationToken"]').val();
$.post(url, { musicaID: id, __RequestVerificationToken: token }, function(data) {
| {
"pile_set_name": "StackExchange"
} |
Q:
Load an assembly at run time that references the calling assembly
My application loads all library assemblies located in its executing path and executes preknown methods against contained classes.
I now need to do the same with an assembly that references my application assembly. Is this possible and are there any negative implications that I should be aware of?
Master Assembly:
public abstract class TaskBase
{
public abstract void DoWork();
}
LoadAssemblyFromFile("Assembly0001.dll");
Assembly0001.Task1.DoWork();
Child Assemblies:
public sealed class Task1: MasterAssembly.TaskBase
{
public override void DoWork { /* whatever */ }
}
A:
Yes, this is possible. As long as your master assembly doesn't reference the child assemblies, you should be fine. Otherwise, you'll have a circular dependency.
The master assembly will simply load the child assemblies and know nothing about them except that they implement an interface. That way, the master assembly doesn't need to reference the child assemblies.
No gotchas as far as I'm aware. We use this technique successfully for certain scenarios.
| {
"pile_set_name": "StackExchange"
} |
Q:
In QT 4.6 w/ Webkit: How to handle popup window requests (WebView::createWindow)?
I'm new to QT and have been trying to create a test browser. What I'm trying to do now is to handle js-based popup requests. After reading the QT documentation, I learned that I need to re-implement the QWebView::createWindow method to do just that.
Now I've re-implemented this method, but it seems to be not called when I try to click a link that triggers a popup window.
Can any one help me? Do I need to subclass both the WebView and WebPage classes? If so, how do I do that? I'm quite new to QT and I've done tons of searches and found nothing.
Thank you all in advance for any hint and advice!
A:
Did you remember to set the following options?
view->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
view->settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
And don't forget to call the parent class createWindow() method. The documentation has a note on that:
Note: If the createWindow() method of
the associated page is reimplemented,
this method is not called, unless
explicitly done so in the
reimplementation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Codeigniter .htaccess: Give public access to all files and folders inside the 'public' folder
I'm using Codeigniter 2.0.3 | Apache 2.2.17 | PHP 5.3.4.
I'm want to give access to all the files and subfolders inside the 'public' folder. I've read the articles in the Codeigniter wiki and also all first 5 pages on google results and found nothing that works.
This is the files tree:
- application
- public
- css
- style.css
- img
- js
- system
- .htaccess
And this is the .htaccess I'm using to remove 'index.php' from the URL and try to give access to the folder:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /CodeIgniter_2.0.3
#Removes access to the system folder by users.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [L]
#Checks to see if the user is attempting to access a valid file,
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#Enable access to the images and css folders, and the robots.txt file
RewriteCond $1 !^(index\.php|public|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
The website is working and 'index.php' is no longer needed in the URL, but the last condition is supposed to give access to the public folder, but its not working for me, so this http://localhost/CodeIgniter_2.0.3/public/css/style.css
file is not found.
In config.php I have:
$config['base_url'] = 'http://localhost/CodeIgniter_2.0.3/';
$config['index_page'] = '';
Please help.
Thanks!!!
A:
With your current structure, you need to change the last RewriteCond to:
RewriteCond $1 !^(index\.php|application\/public|robots\.txt)
because your .htaccess is in the same directory as your application folder and your public folder is in your application folder, you need to explicitly mark the application/public folder as accessible.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to stop form submission in AngularJS
You may be amazed why I am intended to do it, but it's necessary to be done. I couldn't solve, so could you please help me.. if yes, let's go!
I have a form, I want that if I click on submit, an action/event should be generated that stops the form submission, and tells me that your form is not submitted. That's it.
Here's my form:
<div ng-app="myApp" ng-controller="myCtrl">
<form>
First Name: <input type="text" ng-model="firstName" required><br>
Last Name: <input type="text" ng-model="lastName" required><br>
<input type="submit" value="submit form"/>
</form>
</div>
Here's the AngularJS controller:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
// Execute form submission
// handle data and prevent redirect
});
</script>
I regret if I am asking something irrelevant, but I think it can be done to which my reach is not possible for now.
Thanks.
A:
Untested by you can try swapping out for your submit button for
<button ng-click="submit($event)">Submit form</button>
And then in your controller:
$scope.submit = function($event) {
$event.preventDefault();
}
By not using the default form submission you get to access the event and control whether to continue with it or not.
| {
"pile_set_name": "StackExchange"
} |
Q:
Class returns empty list
I am trying to write a function which cleans up URLs (strips them of anything like "www.", "http://" etc.) to create a list that I can sort alphabetically.
I have tried to do this by creating a class including a method to detect the term I would like to remove from the URL-string, and remove it. The bit where I am struggling is that I want to add the modified URLs to a new list called new_strings, and then use that new list when I call the method for a second time on a different term, so that step by step I can remove all unwanted elements from the URL-string.
For some reason my current code returns an empty list, and I am also struggling to understand whether new_strings should be passed to __init__ or not? I guess I am a bit confused with global vs. local variables, and some help and explanation would be greatly appreciated. :)
Thanks! Code below.
class URL_Cleaner(object):
def __init__(self, old_strings, new_strings, term):
self.old_strings = old_strings
self.new_strings = new_strings
self.term = term
new_strings = []
def delete_term(self, new_strings):
for self.string in self.old_strings:
if self.term in string:
new_string = string.replace(term, "")
self.new_strings.append(new_string)
else:
self.new_strings.append(string)
return self.new_strings
print "\n" .join(new_strings) #for checking; will be removed later
strings = ["www.google.com", "http://www.google.com", "https://www.google.com"]
new_strings = []
www = URL_Cleaner(strings, new_strings, "www.")
A:
Why are we making a class to do this?
for string in strings:
string.replace("www.","")
Isn't that what you're trying to accomplish?
Regardless the problem is in your class definition. Pay attention to scopes:
class URL_Cleaner(object):
def __init__(self, old_strings, new_strings, term):
"""These are all instance objects"""
self.old_strings = old_strings
self.new_strings = new_strings
self.term = term
new_strings = [] # this is a class object
def delete_term(self, new_strings):
"""You never actually call this function! It never does anything!"""
for self.string in self.old_strings:
if self.term in string:
new_string = string.replace(term, "")
self.new_strings.append(new_string)
else:
self.new_strings.append(string)
return self.new_strings
print "\n" .join(new_strings) #for checking; will be removed later
# this is referring the class object, and will be evaluated when
# the class is defined, NOT when the object is created!
I've commented your code the necessary reasons.... To fix:
class URL_Cleaner(object):
def __init__(self, old_strings):
"""Cleans URL of 'http://www.'"""
self.old_strings = old_strings
cleaned_strings = self.clean_strings()
def clean_strings(self):
"""Clean the strings"""
accumulator = []
for string in self.old_strings:
string = string.replace("http://", "").replace("www.", "")
# this might be better as string = re.sub("http://(?:www.)?", "", string)
# but I'm not going to introduce re yet.
accumulator.append(string)
return accumulator
# this whole function is just:
## return [re.sub("http://(?:www.)?", "", string, flags=re.I) for string in self.old_strings]
# but that's not as readable imo.
| {
"pile_set_name": "StackExchange"
} |
Q:
On my mac. whereis command failed return application path
All
my shell is oh-my-zsh.
“whereis” doesn't work, there is not any response while I'v executed the command.
“which” works normally.
Here are some details
~ ⌚ 3:26:26
$ echo $PATH ‹ruby-2.2.4›
/Users/luoweiguang/.rvm/gems/ruby-2.2.4/bin:/Users/luoweiguang/.rvm/gems/ruby-2.2.4@global/bin:/Users/luoweiguang/.rvm/rubies/ruby-2.2.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Wireshark.app/Contents/MacOS:/Users/luoweiguang/.rvm/bin
~ ⌚ 3:26:28
$ which man ‹ruby-2.2.4›
/usr/bin/man
~ ⌚ 3:26:36
$ whereis Notes ‹ruby-2.2.4›
~ ⌚ 3:26:49
$ whereis XCode ‹ruby-2.2.4›
~ ⌚ 3:41:35
$
I spent much time on the problem for these days. and I didn't find a way to fix it, Hope you guys can help me. Thanks
A:
whereis probably works just fine, there are just no binaries named Notes or XCode in your $PATH. For confirmation, please try to run which Notes and which XCode. Also try whereis man to confirm that whereis is actually working.
XCode and Notes come as App bundle and their executables are not placed in the "normal" places like /usr/bin. Instead their executable is inside their bundle directory, which (or rather the appropriate subdirectory) is usually not part of $PATH. For Notes this the bundle directory is /Applications/Notes.app and the executable is /Applications/Notes.app/Contents/MacOS/Notes.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to print a float value of 6 digit precision in C++?
By default I'm getting 4 digit precision and when I use setprecision(6) the last digits of the variable come in random like 1/3=0.333369.
A:
float has about 7 decimal digits of precision, due to its use of 24 binary digits to store the digits of the number. As far as output is concerned, setprecision(6) does everything you could ask for.
It's likely you are losing precision, for example by subtracting two numbers with similar values and printing the result. The quick solution is to change the computations to use double or long double. But to make any guarantees about the precision of a floating-point result, you need to understand how FP works and analyze how your formula is getting computed.
See What Every Computer Scientist Should Know About Floating-Point Arithmetic.
| {
"pile_set_name": "StackExchange"
} |
Q:
Asp.net Identity: change user role while logged in
I have a page where a logged-in user performs an action and based on that I change the user's role like this:
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
IdentityUser user = manager.FindById(TheMembershipID);
manager.RemoveFromRole(user.Id, "StartUser");
manager.AddToRole(user.Id, "AppUser");
Then, on the client, there's a redirect to another page that requires authentication in the AppUser role. The problem is that the user shows as being still logged in as a StartUser.
How do I change the role of a user while he's logged in?
A:
You need to log them out and back in for the new role to take effect. After your code:
//Get the authentication manager
var authenticationManager = HttpContext.GetOwinContext().Authentication;
//Log the user out
authenticationManager.SignOut();
//Log the user back in
var identity = manager.CreateIdentity(user,DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { IsPersistent = true}, identity);
This isn't exact, but should give you the general idea.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I determine when a UITableViewCell's action buttons are shown and hidden?
Is there a delegate method or something that I can implement that allows me to do something when action buttons of my tableview cell is shown and hidden again?
A:
The tableview delegate methods:
-(void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
and
-(void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath does the trick.
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery: find a particular string of text within a selected value
I am using the code below to hide/show sections based on the selection from a dropdown. I want to say, if the value selected contains the word "-AREA" continue with the code. How do I include a find/search of a particular string with this code base?
$('select#7535').change(function(event) {
var campaignType = $(this).val();
if (campaignType == "Type 1")
{
$('tr.tr-1153-7548').show();
$('tr.tr-1153-7549').show();
}
else
{
$('tr.tr-1153-7548').hide();
$('tr.tr-1153-7549').hide();
}
});
Thank you in advance.
A:
String#indexOf searches for a substring within a string, so:
if (campaignType.indexOf("-VIEW") !== -1) {
// It's there
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove newline character/white space from xml using xslt or xquery transformation
How to remove newline character/white space from xml using xslt or xquery transformation.Means all the elements will come in a single line.
A:
In xslt, you can add a top level element
<xsl:strip-space elements="*"/>
By using a sample input XML below:
<?xml version="1.0" encoding="utf-8"?>
<root>
<a>XXX</a>
<b>YYY</b>
<c>ZZZ</c>
</root>
and the following XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<!-- this is called an identity template -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
produces:
<?xml version="1.0" encoding="utf-8"?><root><a>XXX</a><b>YYY</b><c>ZZZ</c></root>
| {
"pile_set_name": "StackExchange"
} |
Q:
Query sin repetir datos
Tengo el siguiente query de dos tablas, el problema es que solo necesito mostrar el primer registro por CODIGO, no puedo utilizar TOP 1 porque necesito ver todos los codigos, solo el primer registro de cada codigo
select P.CODIGO, P.SEMANA, S.FECHA
from PERSONAS P
Left join SEMANAS S
on P.SEMANA= S.SEMANA
group by P.CODIGO, P.SEMANA, S.FECHA
ORDER BY S.FECHA
PERSONAS
CODIGO INT
SEMANA INT
SEMANAS
SEMANA INT
FECHA DATE
espero haberme dado a entender
Gracias
A:
;WITH CTE AS (
SELECT P.CODIGO,
P.SEMANA,
S.FECHA,
ROW_NUMBER() OVER (PARTITION BY P.CODIGO ORDER BY S.FECHA) AS RN
FROM PERSONAS P
LEFT JOIN SEMANAS S
ON P.SEMANA= S.SEMANA
GROUP BY P.CODIGO, P.SEMANA, S.FECHA
)
SELECT *
FROM CTE
WHERE RN = 1
Detalle:
Usamos un CTE para definir la consulta principal
En esta establecemos un numerador mediante ROW_NUMBER() el cual se reiniciará por cada P.CODIGO y estará ordenado por S.FECHA
Con lo anterior podremos ahora sía obtener solo las filas que se correspondan con la primera de cada código
| {
"pile_set_name": "StackExchange"
} |
Q:
I have simple slideshow in jquery, I want to automatic run
how to use setinterval in this code? I tried different ways but it did not work
This is my html
<img id="picr" src="images/image1.jpg" width="400px" height="400px">
<div>
<div id="prev">
<input type="button" id="testbutton" value="Prev" width="100px" height="100px">
</div>
<div id="next">
<input type="button" id="testbutton" value="Next">
</div>
</div>
and here is jquery,
$(document).ready(function () {
// body...
var pict =["images/image1.jpg", "images/image2.jpg", "images/image3.jpg"];
var picNum=1;
$("#prev, #next").mouseover(function(){
$("#picr").slideUp(2000, function(){
$("#picr").attr("src", pict[picNum]);
picNum++;
if (picNum>2){picNum=0;}
$("#picr").fadeIn(2000);
});
});
});
how to use setinterval in this code? I tried different ways but it did not work
A:
To use setInterval() fun to run automatic you must create function:
function playSlider() {
$("YourButtonNextElement").click();
t = setInterval(function () { playSlider(); }, 4000);
}
and in $(document).ready() call playSlider() fun
$(document).ready(function () {
// body...
var pict =["images/image1.jpg", "images/image2.jpg", "images/image3.jpg"];
var picNum=1;
$("#prev, #next").mouseover(function(){
$("#picr").slideUp(2000, function(){
$("#picr").attr("src", pict[picNum]);
picNum++;
if (picNum>2){picNum=0;}
$("#picr").fadeIn(2000);
});
});
playSlider();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Divide integers with floor, ceil and outwards rounding modes in C++
Recently, I saw this question which asks how you can divide integers with ceil rounding (towards positive infinity). Unfortunately the answers either don't work for signed integers or have problems with underflows and overflows.
For instance, the accepted answer has this solution:
q = 1 + ((x - 1) / y);
When x is zero, there is an underflow to ~0 and the the result is incorrect.
How can you implement ceil rounding correctly for signed and unsigned integers and how do you implement other rounding modes like floor (towards negative infinity) and outwards (away from zero)?
A:
In C++, the / division operation rounds using truncate (towards zero) by default. We can adjust the result of division towards zero to implement other rounding modes.
Note that when the division has no remainder, all rounding modes are equivalent because no rounding is necessary.
With that in mind, we can implement the different rounding modes.
But before we get started, we will need a helper template for the return types so that we don't use auto return types everywhere:
#include <type_traits>
/**
* Similar to std::common_type_t<A, B>, but if A or B are signed, the result will also be signed.
*
* This differs from the regular type promotion rules, where signed types are promoted to unsigned types.
*/
template <typename A, typename B>
using common_signed_t =
std::conditional_t<std::is_unsigned_v<A> && std::is_unsigned_v<B>,
std::common_type_t<A, B>,
std::common_type_t<std::make_signed_t<A>, std::make_signed_t<B>>>;
Ceil (towards +∞)
Ceil rounding is identical to truncate rounding for negative quotients, but for positive quotients and nonzero remainders we round away from zero. This means that we increment the quotient for nonzero remainders.
Thanks to if-constexpr, we can implement everything using only a single function:
template <typename Dividend, typename Divisor>
constexpr common_signed_t<Dividend, Divisor> div_ceil(Dividend x, Divisor y)
{
if constexpr (std::is_unsigned_v<Dividend> && std::is_unsigned_v<Divisor>) {
// quotient is always positive
return x / y + (x % y != 0); // uint / uint
}
else if constexpr (std::is_signed_v<Dividend> && std::is_unsigned_v<Divisor>) {
auto sy = static_cast<std::make_signed_t<Divisor>>(y);
bool quotientPositive = x >= 0;
return x / sy + (x % sy != 0 && quotientPositive); // int / uint
}
else if constexpr (std::is_unsigned_v<Dividend> && std::is_signed_v<Divisor>) {
auto sx = static_cast<std::make_signed_t<Dividend>>(x);
bool quotientPositive = y >= 0;
return sx / y + (sx % y != 0 && quotientPositive); // uint / int
}
else {
bool quotientPositive = (y >= 0) == (x >= 0);
return x / y + (x % y != 0 && quotientPositive); // int / int
}
}
At first glance, the implementations for signed types seem expensive, because they use both an integer division and a modulo division. However, on modern architectures division typically sets a flag that indicates whether there was a remainder, so x % y != 0 is completely free in this case.
You might also be wondering why we don't compute the quotient first and then check if the quotient is positive. This wouldn't work because we already lost precision during this division, so we can't perform this test afterwards. For example:
-1 / 2 = -0.5
// C++ already rounds towards zero
-0.5 -> 0
// Now we think that the quotient is positive, even though it is negative.
// So we mistakenly round up again:
0 -> 1
Floor (towards -∞)
Floor rounding is identical to truncate for positive quotients, but for negative quotients we round away from zero. This means that we decrement the quotient for nonzero remainders.
template <typename Dividend, typename Divisor>
constexpr common_signed_t<Dividend, Divisor> div_floor(Dividend x, Divisor y)
{
if constexpr (std::is_unsigned_v<Dividend> && std::is_unsigned_v<Divisor>) {
// quotient is never negative
return x / y; // uint / uint
}
else if constexpr (std::is_signed_v<Dividend> && std::is_unsigned_v<Divisor>) {
auto sy = static_cast<std::make_signed_t<Divisor>>(y);
bool quotientNegative = x < 0;
return x / sy - (x % sy != 0 && quotientNegative); // int / uint
}
else if constexpr (std::is_unsigned_v<Dividend> && std::is_signed_v<Divisor>) {
auto sx = static_cast<std::make_signed_t<Dividend>>(x);
bool quotientNegative = y < 0;
return sx / y - (sx % y != 0 && quotientNegative); // uint / int
}
else {
bool quotientNegative = (y < 0) != (x < 0);
return x / y - (x % y != 0 && quotientNegative); // int / int
}
}
The implementation is almost identical to that of div_ceil.
Away From Zero
Away from zero is the exact opposite of truncate. Basically, we need to increment or decrement depending on the sign of the quotient, but only if there is a remainder. This can be expressed as adding the sgn of the quotient onto the result:
template <typename Int>
constexpr signed char sgn(Int n)
{
return (n > Int{0}) - (n < Int{0});
};
Using this helper function, we can fully implement up rounding:
template <typename Dividend, typename Divisor>
constexpr common_signed_t<Dividend, Divisor> div_up(Dividend x, Divisor y)
{
if constexpr (std::is_unsigned_v<Dividend> && std::is_unsigned_v<Divisor>) {
// sgn is always 1
return x / y + (x % y != 0); // uint / uint
}
else if constexpr (std::is_signed_v<Dividend> && std::is_unsigned_v<Divisor>) {
auto sy = static_cast<std::make_signed_t<Divisor>>(y);
signed char quotientSgn = sgn(x);
return x / sy + (x % sy != 0) * quotientSgn; // int / uint
}
else if constexpr (std::is_unsigned_v<Dividend> && std::is_signed_v<Divisor>) {
auto sx = static_cast<std::make_signed_t<Dividend>>(x);
signed char quotientSgn = sgn(y);
return sx / y + (sx % y != 0) * quotientSgn; // uint / int
}
else {
signed char quotientSgn = sgn(x) * sgn(y);
return x / y + (x % y != 0) * quotientSgn; // int / int
}
}
Unresolved Problems
Unfortunately these functions won't work for all possible inputs, which is a problem that we can not solve.
For example, dividing uint32_t{3 billion} / int32_t{1} results in int32_t(3 billion) which isn't representable using a 32-bit signed integer.
We get an underflow in this case.
Using larger return types would be an option for everything but 64-bit integers, where there isn't a larger alternative available.
Hence, it is the responsibility of the user to ensure that when they pass an unsigned number into this function, it is equivalent to its signed representation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create relation between an entity and non-entity objects
I have some domain object in my webapp named of Site.
Site would be contains list of IP addresses, that is
@Entity
class Site {
...
@ManyToMany(fetch=FetchType.LAZY)
public Set<String> ips= new HashSet<String>();
...
}
But hibernate is down when I try to start webapp with error:
Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: my.webapp.Site.ips[java.lang.String]
What's the problem?
A:
You cannot use relational annotations (i.e. @ManyToMany) if you don't have a relationship with an Entity. If you have basic type (as in this case - String) you should use @ElementCollection
| {
"pile_set_name": "StackExchange"
} |
Q:
Towards the solution of the Problem : Field Extension problem beyond $\mathbb C$ (Question 1)
I am posting this problem in order to break the problem in my previous post Field Extension problem beyond $\mathbb C$.
Notation: $M(\mathbb C):=$ Field of all meromorphic functions on $\mathbb C$,
$K:=$ a proper subfield between $\mathbb C$ and $M(\mathbb C)$
Question 1: Let $\sigma\in Aut(K)$ and $c$ is a constant function. Is it true $\sigma(c)$ is again a constant function ?
I will post subsequent questions after getting a good answer (either by myself or someone else). Let us try how far we can go!
A:
Yes, it is true that for $c\in\mathbb{C}$ then $\sigma(c)$ is again in $\mathbb{C}$. This is because the subfield $\mathbb{C}$ of $K$ is distinguished by the following algebraic property.
An element $c\in K$ is in $\mathbb{C}$ if and only if $X^n-c+q=0$ has a root in $K$ for each $n\in\mathbb{N}$ and $q\in\mathbb{Q}$.
Being an automorphism of $K$, $\sigma$ preserves the stated property, so maps elements of $\mathbb{C}$ (or, 'constant functions') into $\mathbb{C}$.
The fact that each $c\in\mathbb{C}$ satisfies the stated property above follows from the fact that $\mathbb{C}$ is algebraically closed. On the other hand, if $c\in K\setminus\mathbb{C}$ is a nonconstant meromorphic function then, by the little Picard theorem, it maps onto $\mathbb{C}$ minus at most two points, so its image will contain (infinitely many) rationals $q$ (or you can use the simpler fact that the image of a nonconstant meromorphic function is a connected dense open subset of $\mathbb{C}$). So, $c-q$ has a zero, which must be of a finite order $m\ge1$. Then, $c-q$ does not have an $n$'th root (in the field of meromorphic functions) for any $n$ not dividing $m$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check if user is already logged in?
I've got an ASP.NET site. I want to forbid user to log in with the same login from two computers. If someone is logged in and somebody else wants to log in with the same login it should show him a message that this user is already logged in. I don't have any Forms Authentication or something like that. On button "LOG IN" I just connect to the database and check if user and password are valid.
I thought that when user is logged in, I would update his status in database and when somebody else will try to log in, I will check in database if this user is already logged, but it isn't good idea, because when user doesn't click button "LOG OUT", it will not update his status in database that he's inactive.
Is there any other way to do this without Forms Authentication and something like that?
A:
There is no perfect solution
You can't reliably solve this problem, but you can come close. There will be edge cases where a legitimate user will be frustrated by this restriction.
What you can do
The ASP.Net membership provider keeps track of the last time that a given user was seen, meaning the last time they were logged in and accessed a page. You can follow a similar strategy, also noting the IP address of the user and perhaps the user agent of the browser.
If you see two different IP addresses and/or user agents for the same login credentials within a short window (say, 20 minutes) you can assume they are most likely from different devices.
Be aware
As I said, there are edge cases where you will be wrong. For example, someone on a mobile device will frequently get a new IP address.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing one Method Parameters, To another method - c#
Is it possible to take parameters from one method to another?
Basiclly what I want to do is rename a method (in my case is The - .WriteLine() Method), Is there any way of creating a method with the name I want and have it take the parameters of another method like so:
void Func(Take The parametes of The .WriteLine method) //This is the rename of the method
{
Console.WriteLine(place them here);
}
Basiclly I want to rename a method.
A:
If I understand your question correctly, all you want to do is pass an object to Func which should be passed on to the WriteLine method.
void Func(string SomeParameter) //This is the rename of the method
{
Console.WriteLine(SomeParameter);
}
SomeParameter will be passed to the Func method which calls Console.WriteLine. Use this function as :
Func("Hello World");
This should print the text "Hello World" on the output screen.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between the two train motors 8866-1 and 88002-1?
At the Lego store the other day they were talking about a "more powerful" train motor for the Maersk train (I was asking about adding a second motor to the red cargo train so it would go uphill). But I think it's the same motor that already comes with every other train out now. I bought an spare train motor (was on sale online) and I think THAT is the old version.
What is the difference between the two (beside the power cable)?
https://www.bricklink.com/v2/catalog/catalogitem.page?id=84711#T=S&O=
https://www.bricklink.com/v2/catalog/catalogitem.page?id=99046#T=S&O=
A:
Well the power cable is the main difference, as one motor was made for the short-lived 9V RC system while the other is the current PF one.
However, that doesn't mean the internals are the same. From Philo 's motor comparison page, you'll see that the PF motor is better, and that fortunately the performances are much improved [over the RC one], with an efficiency and power even exceeding the old 9V train motors.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to provide ambiguous reference in scala inherit trait?
I have trait, this trait is already defined in framework and can not change:
trait GenericProfile {
def firstName: Option[String]
def lastName: Option[String]
def fullName: Option[String]
def email: Option[String]
def avatarUrl: Option[String]
}
I want a class inherit it as:
class BasicProfile(
providerId: String,
userId: String,
firstName: Option[String],
lastName: Option[String],
fullName: Option[String],
email: Option[String],
avatarUrl: Option[String]
) extends GenericProfile{
def providerId=this.providerId //ambiguous reference will be here
...
}
But if I do not re-define the unimplemented method, there is still error since the value in BasicProfile is regarded as private and do not regard it as already implemented.
I understand that it can simply write as override, but I have another class in practice:
case class IdProfile(id:String,
providerId: String,
userId: String,
firstName: Option[String],
lastName: Option[String],
fullName: Option[String],
email: Option[String],
avatarUrl: Option[String])extends BasicProfile(providerId,userId,firstName,lastName, fullName,email, avatarUrl){
}
I do not want the IdProfile override the methods from its parents class BasicProfile, just inherit would be OK.
A:
Since BasicProfile has to make sure all that the defined methods of the trait are implemented (since you don't want to use an abstract class), I'd recommend using a case class for the BasicProfile.
You can extend the BasicProfile with an IdProfile class (not case class) and override the specific methods you are interesed in (or leave them be). If I'm not mistaken that's what your trying to accomplish?
trait GenericProfile {
def firstName: Option[String]
def lastName: Option[String]
def fullName: Option[String]
def email: Option[String]
def avatarUrl: Option[String]
}
case class BasicProfile(
providerId: String,
userId: String,
var firstName: Option[String],
var lastName: Option[String],
var fullName: Option[String],
var email: Option[String],
var avatarUrl: Option[String]
) extends GenericProfile{
}
class IdProfile(id:String,
providerId: String,
userId: String,
firstName: Option[String],
lastName: Option[String],
fullName: Option[String],
email: Option[String],
avatarUrl: Option[String])extends BasicProfile(providerId,userId,firstName,lastName, fullName,email, avatarUrl){
}
If you are trying to stay away from case class I'd recommend taking a look at this Question: Simple Scala getter/setter override
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Implement a common function accepting argument of two different classes?
I have two classes A and B and they both have a common field in them, and I want to create a function in which if I pass Class A object then I want to set that common field value to the passed value and if I pass Class B object then I want to set that common field value to the passed value. Can anyone please tell me how can I do this, I am new to Java Generic Classes.
Otherwise I would have to make two different functions OR I would have to make an if and else which would decide that passed object belongs to which class ??
Class A
public class A{
int footer;
public void setFooter(int fo) {
footer = fo;
}
}
Class B
public class B{
int footer;
public void setFooter(int fo) {
footer = fo;
}
}
Class D
public class D{
public void change_footer(T generic_param, int value) {
generic_param.setFooter(value);
}
}
Class HelloWorld
public class HelloWorld{
public static void main(String []args){
Here I want to call
A a = new A();
new D().change_footer(a, 5);
B b = new B();
new D().change_footer(b, 5)
}
}
Thank You
A:
And if I got all of the question wrong, and nor A nor B are generic, AND the type of field is fixed.
then you mean something like:
class D {
/*public <T extends Super> would be muuuch nicer here as well!*/
public /*static*/ <T> void change_footer(T obj, int data) {
//otherwise, you could just cast to Super...and set dat field.
if (obj instanceof A) {
((A) obj).setField(data);
} else if (obj instanceof B) {
((B) obj).setField(data);
} // else ... ?
}
}
Original answer:
Easy peasy (the "straight forward" implementation produces the desired results.):
class A<T> {
T daField;
public void setField(T pField) {
daField = pField;
}
public T getField() {
return daField;
}
}
class B<T> extends A {//empty
}
class Test {
public static void main(String... args) {
B<Object> testB1 = new B<>(); //
testB1.setField(new Object());
System.out.println(testB1.getField());
B<String> testB2 = new B<>();
testB2.setField("blah blah");
System.out.println(testB2.getField());
B<Integer> testB3 = new B<>();
testB3.setField(42);
System.out.println(testB3.getField());
}
}
System.out:
java.lang.Object@6d06d69c
blah blah
42
It get's (little) more complicated, when you want to instantiate Ts ...but still possible/other question. :)
Edit to your comment:
If there's only one common field, then why not:
/*abstract */class Super<T> {
T daField;
public void setField(T pField) {
daField = pField;
}
public T getField() {
return daField;
}
}
? ...and:
class A<T> extends Super { ... }
class B<T> extends Super { ... }
| {
"pile_set_name": "StackExchange"
} |
Q:
Monotonicity of sigma-algebra generator: $A\subset B \rightarrow \sigma(\{E\in A\})\subset \sigma(\{E\in B\})$?
$A,B$ are collections of sets. Does $A\subset B$ implies $\sigma(\{E\in A\})\subset \sigma(\{E\in B\})$? How to prove this?
A:
This is effectively from the definition of a $\sigma$-algebra generated by certain sets.
The $\sigma$-algebra $\sigma(B)$ generated by $B$ is the smallest $\sigma$-algebra which contains the sets $B$, and likewise for $A$. Since $A\subseteq B$, this implies that $\sigma(B)$ is a $\sigma$-algebra which contains the sets in $A$, and therefore $\sigma(A)\subseteq\sigma(B)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic String array dosent work
I'm trying to create a dynamic array of 1000 character long strings using calloc:
int i;
char** strarr =(char**)calloc(argc,sizeof(char)*1000);
if(strarr == NULL)
return 0;
strarr[0][0] ='a';
printf("%c\n",strarr[0][0]);
Every time i try to run this code i get segmentation fault on the printf line, i don't get why does this happen (you can assume that argc is bigger than 0)
Thanks
P.s. im sorry that the code is in text format but im using a mobile so i dont have the code feature
A:
Try this:
const int num_of_strings = 255; //argc ?
const int num_of_chars = 1000;
int i;
char** strarr =(char**)malloc(sizeof(char*)*num_of_strings);
if(strarr == NULL)
return 0;
for (i = 0; i < num_of_strings; i++) strarr[i] = (char*)malloc(sizeof(char)*num_of_chars);
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use the Facebook Javascript SKD with a dynamic script tag insert?
What am I trying to achieve.
To create a module that loads the Facebook Javascript SDK without having to paste that script tag into your HTML and manually enter your app details, yes this may seem like a waste of time but It seems to make more sense to me.
For example this module would take a config with your details and everything could be set via Javascript instead of the initialization code being in your HTML file and the rest of your logic being in your script files.
My problem.
When I dynamically append the script and
<div id="fb-root"></div>
I get an error FB.init has already been called - this could indicate a problem
This seems strange to me because I only have once instance FB.init is called. Effectively my script is the same as if you would manually add the script tag into the html but I'm trying to achieve it dynamically.
What I have tried.
I have read a lot of questions on here about using javascript to append and prepend elements, I have tried mostly all of those methods. I have read topics titled Dynamically Inserting Script with Javascript, these have been no help.
My method seems to be correct, but I still get these Facebook errors.
My Markup.
<!DOCTYPE html>
<head>
<title></title>
<head>
<body>
<script src="facebook.js"></script>
</body>
</html>
My Javascript:
var Facebook = {};
Facebook = {
config: {
APP_ID: 'APP_ID',
APP_URL: 'APP_URL',
CHANNEL_URL: 'CHANNEL_URL'
}
};
var fbEl = document.createElement('div');
fbEl.id = 'fb-root';
document.body.insertBefore(fbEl,document.body.children[0]);
var fbScript = document.createElement('script');
fbScript.type = 'text/javascript';
fbScript.innerHTML = '';
fbScript.innerHTML += 'window.fbAsyncInit = function() {\n';
fbScript.innerHTML += 'FB.init({\n';
fbScript.innerHTML += 'appId : '+Facebook.APP_ID+',\n';
fbScript.innerHTML += 'channelUrl : '+Facebook.CHANNEL_URL+',\n';
fbScript.innerHTML += 'status : false,\n';
fbScript.innerHTML += 'cookie : true,\n';
fbScript.innerHTML += 'xfbml : false \n';
fbScript.innerHTML += '});\n';
fbScript.innerHTML += '};\n';
fbScript.innerHTML += '(function(d, debug){\n';
fbScript.innerHTML += 'var js, id = "facebook-jssdk", ref = d.getElementsByTagName("script")[0];\n';
fbScript.innerHTML += 'if (d.getElementById(id)) {return;}\n';
fbScript.innerHTML += 'js = d.createElement("script"); js.id = id; js.async = true;\n';
fbScript.innerHTML += 'js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";\n';
fbScript.innerHTML += 'ref.parentNode.insertBefore(js, ref);\n';
fbScript.innerHTML += '}(document, /*debug*/ false));';
document.body.insertBefore(fbScript,document.body.children[1]);
I do have the Facebook variables set correctly in my code this is for demonstrations sake.
I have read the Facebook Docs on this many times.
Is there a way to dynamically add the block for tje FB JS SKD using ONLY Javascript?
A:
I'm not sure what's actually going wrong, but you have one more level of indirection than you need and that's making the whole thing too complicated. Why not something like:
var Facebook = {
config:{ //etc
}
};
window.fbAsyncInit = function() {
FB.init(//etc
)
};
(function(d, debug){
var js, id = //etc - this injects the SDK script reference into the dom.
})(document, false);
| {
"pile_set_name": "StackExchange"
} |
Q:
Using NAudio to decode mu-law audio
I'm attempting to use NAudio to decode mu-law encoded audio into pcm audio. My service is POSTed the raw mu-law encoded audio bytes and I'm getting an error from NAudio that the data does not have a RIFF header. Do I need to add this somehow? The code I'm using is:
WaveFileReader reader = new WaveFileReader(tmpMemStream);
using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader))
{
WaveFileWriter.CreateWaveFile(recordingsPath + "/" + outputFileName, convertedStream);
}
I'm also saving the raw data to the disk and doing the decoding in Matlab which is working with no problem. Thanks.
A:
Since you just have raw mu-law data, you can't use a WaveFileReader on it. Instead, create a new class that inherits from WaveStream.
In its Read method, return data from tmpMemStream. As a WaveFormat return a mu-law WaveFormat.
Here's a generic helper class that you could use:
public class RawSourceWaveStream : WaveStream
{
private Stream sourceStream;
private WaveFormat waveFormat;
public RawSourceWaveStream(Stream sourceStream, WaveFormat waveFormat)
{
this.sourceStream = sourceStream;
this.waveFormat = waveFormat;
}
public override WaveFormat WaveFormat
{
get { return this.waveFormat; }
}
public override long Length
{
get { return this.sourceStream.Length; }
}
public override long Position
{
get
{
return this.sourceStream.Position;
}
set
{
this.sourceStream.Position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return sourceStream.Read(buffer, offset, count);
}
}
Now you can proceed to create the converted file as you did before, passing in the RawSourceWaveStream as your input:
var waveFormat = WaveFormat.CreateMuLawFormat(8000, 1);
var reader = new RawSourceWaveStream(tmpMemStream, waveFormat);
using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader))
{
WaveFileWriter.CreateWaveFile(recordingsPath + "/" + outputFileName, convertedStream);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
shared_ptr allocation optimization
Somewhere I saw a post about an optimized way of creating a boost shared_ptr so that it allocated the ptr plumbing and the pointee at the same time. I did a SO search but there are a lot of posts on shared_ptr and I could not find it. Can somebody smart please repost it
edit:
thanks for answer. extra credit question. Whats the correct (preferred?) idiom for returning a null shared_ptr? ie
FooPtr Func()
{
if(some_bad_thing)
return xxx; // null
}
to me
return FooPtr((Foo*)0);
looks kinda klunky
A:
See boost::make_shared():
Besides convenience and style, such a function is also exception safe and considerably faster because it can use a single allocation for both the object and its corresponding control block, eliminating a significant portion of shared_ptr's construction overhead. This eliminates one of the major efficiency complaints about shared_ptr.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to bulk document delete in Alfresco
I am very new Alfresco user. We have uploaded 18000 documents to Alfresco. Then we noticed that some categories are not correct. We would like to upload them again, but we don't know how to delete existing documents. Is there any way to delete all documents that were uploaded yesterday?
A:
The best way is to use a code based method (JavaScript or CMIS).
So, the easiest way is to create a JavaScript file in Data Dictionary/Script folder
with something like this:
// execute a lucene search across the repository for pdf documents in a specific folder created the exact day
var docs = search.luceneSearch("PATH:\"/app:company_home/cm:myFolder//*\" AND @cm\\:content.mimetype:\"application/pdf\" AND @cm\\:created:2013-05-21");
var i;
for (i=0; i<docs.length; i++)
{
docs[i].remove();
}
although 18k documents could probably create some memory issues in your JVM.
Maybe the script will interrupt at some point, and you'll have to restart the machine and execute script again.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where is my Java application's logs?
I am logging issues at my application like that:
private static Logger logger = LoggerFactory.getLogger(Student.class);
...
logger.info(msg);
logger.debug(another_msg);
I use Java and Spring framework running on Apache Tomcat 6 and slf4j for logging. When I debug my application on Intellij IDEA I see two tabs: Server and Tomcat Log. That logs are seen at Server tab. Under tomcat folder there is no file that records that logs. However I want to see it at file end if I can I want to change the log level(debug, info etc.) to see the logs.
How can I do it?
A:
Search for the log4j.properties file in your application.
In the log4j.properties you specify the path for the log file.
See here
| {
"pile_set_name": "StackExchange"
} |
Q:
How to subtract/add time from a csv column in Python?
I'm new to python/programming and haven't dealt with time yet. I have a csv file with a column of time/date information but in the wrong time zone. How can I subtract or add hours? It's formatted like this:
1 Jan 2014 hh:mm
If it helps I've already broken down the data into a list of dicts:
[{datetime: 1 Jan 2014 00:00}, {datetime: 2 Jan 2014 00:01}]
Thanks
A:
You can create datetime objects and use datetime.timedelta to add hours/days etc..
d = {"datetime": "2 Jan 2014 00:01"}
from datetime import datetime ,timedelta
print(datetime.strptime(d["datetime"],"%d %b %Y %H:%M")+timedelta(hours=4))
2014-01-02 04:01:00
| {
"pile_set_name": "StackExchange"
} |
Q:
how to call rails controller with particular id from angularjs
I am working in angularjs and rails and I want to call rails controller like this
.controller('SongController', ['$scope','FileUploader','$stateParams',function($scope, FileUploader,$stateParams) {
$scope.uploader = new FileUploader({url: '/events/$stateParams.id/playlists'});
}]);
$stateParams.id should get replaced by event_id like 1 or 2 and url be like
/events/1/playlists
but it is not so
and it is giving me following error
No route matches [POST] "/events/$stateParams.id/playlists"
how to call the route.
A:
You need to interpolate the actual id:
.controller('SongController', ['$scope','FileUploader','$stateParams',function($scope, FileUploader,$stateParams) {
$scope.uploader = new FileUploader({url: '/events/' + $stateParams.id + '/playlists'});
}]);
| {
"pile_set_name": "StackExchange"
} |
Q:
NSArray of character strings
I'm trying to create an NSMutableArray of characters.
lowerCaseLetters = [NSMutableArray new];
for (char crt = 'a'; crt <= 'z'; crt ++) {
NSString *chrStr = [NSString stringWithCString:&crt encoding:NSUTF8StringEncoding];
[lowerCaseLetters addObject:chrStr];
}
NSLog(@"%@",lowerCaseLetters);
Result:
"a@Ip",
"b@Ip",
"c@Ip",
"d@Ip",
"e@Ip",
"f@Ip",
"g@Ip",
"h@Ip",
"i@Ip",
"j@Ip",
"k@Ip",
"l@Ip",
"m@Ip",
"n@Ip",
"o@Ip",
"p@Ip",
"q@Ip",
"r@Ip",
"s@Ip",
"t@Ip",
"u@Ip",
"v@Ip",
"w@Ip",
"x@Ip",
"y@Ip",
"z@Ip"
)
Why do I get this? Is there a better way to do this?
PS: Sometimes this crashes with "insertObject:atIndex:" can not insert nil object.... Why?
A:
Following on from dasblinkenlight, another approach is
for (unichar crt = 'a'; crt <= 'z'; crt ++) // note crt is now unichar
{
NSString *chrStr = [NSString stringWithCharacters: &crt length: 1];
[lowerCaseLetters addObject:chrStr];
}
Following on from user2734323 another approach is
lowerCaseLetters = [@[ @"a", @"b", @"c", .... , @"x", @"y", @"z" ] mutableCopy];
| {
"pile_set_name": "StackExchange"
} |
Q:
Better way of logic loop while button is pressed?
So I have a button on a WinRT UserControl that I want to increase or decrease a integer value (CurrentValue) while you hold down the button.
I ended up with this implementation below, which works but does not look to good or is it okay?
I searched for an event to use but I got stuck using click and setting the button.clickmode to press.
I use the bool _increasePushed to track if already pushed in so I don't get multiple event triggers.
private bool _increasePushed;
private const int PushDelay = 200;
private async void ButtonIncreaseClick(object sender, RoutedEventArgs e)
{
var button = sender as Button;
if (button == null) return;
if (_increasePushed)
{
return;
}
_increasePushed = true;
while (button.IsPressed)
{
CurrentValue++;
await Task.Delay(PushDelay);
}
_increasePushed = false;
}
XAML on UserControl
<Button x:Name="buttonIncrease" Content="Bla bla"
Click="ButtonIncreaseClick" ClickMode="Press" />
A:
The better way would be to use a RepeatButton which does exactly what you are trying to replicate. It has a Delay property to wait for the first repeated click as well as an Interval property that controls how often the Click event is raised.
| {
"pile_set_name": "StackExchange"
} |
Q:
IOS 5 - CUSTOM EMOJI ICONS
As we all know IOS 5 is gonna bring us emoji keyboard for everyone.
My question is if there is any way to create an app that would install new custom made emoji icons?
Or is there a way to create totally new custom emoji keyboard so it can later be chosen from INTERNATIONAL KEYBOARD SETTINGS.
Any tips? Or sample source codes?
A:
Don't know if I'm right but the Emoji-Icons were created and added by Apple. These "Emoji-Apps" just activate the Emojis for you.
So it isn't and won't be possible to add new Emojis in iOS 5 or earlier. And as Sum already said, iOS 5 is still under NDA and StackOverflow disallow discussions about this.
| {
"pile_set_name": "StackExchange"
} |
Q:
android edit text focus
i have two edit text on the layout and on load the cursor has to be on the second edit text. and how to move the edit text above the keypad on load. Re size property does not work. thanks in advance
A:
Use android:enabled=true in your editText. Use RelativeLayout to create your view and try not to give height of the editText directly. If you do so the property android:windowSoftInputMode="adjustResize" in your manifest will work.
If you need an example just let me know.
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/middle"
android:layout_width="10dip"
android:layout_height="fill_parent"
android:layout_centerVertical="true">
</LinearLayout>
<EditText
android:layout_above="@id/middle"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</EditText>
<EditText
android:layout_below="@id/middle"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</EditText>
</RelativeLayout>
| {
"pile_set_name": "StackExchange"
} |
Q:
EditText field not appending text
I am fairly new to Android. I am making a very simply calculator.
For the Plus button I've written code to getText from the editText field store it in an array index for later addition and then show the + sign to be appended so the user can see the operation.
But for the code posted below, everything else executes except it doesn't show the + sign appended to the EditText view.
button_plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(lower_textfield.length() == 0)
{
Toast.makeText(getApplicationContext(), "Write a number to add first",
Toast.LENGTH_SHORT).show();
}
else
{
tmp = lower_textfield.getText().toString();
arr[0] = Integer.parseInt(tmp);
lower_textfield.append("+");
}
}
});
Here tmp is String and arr is Int Array.
Help would be appreciated.
A:
The method
append()
on the EditText object should must work.
Check the inputType of the EditText object.
May be mistakenly you've written any numeric inputType like.
android:inputType="numberDecimal"
It should be
android:inputType="none"
OR
android:inputType="text"
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to Draw a point cloud, just a single point in the center in opengl
Trying to create a random point cloud in 2D. However, I've got this in the end for now : The background color + 1 single 'grey' point in the center. What might have gone wrong here?
I try writing my own simple shader.
Trying to compile shader by myself.
All are supposed to be baby steps.
Also what would be some tips of debugging these issues?
#include <vector>
#include <algorithm>
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
GLFWwindow* window;
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/norm.hpp>
/* SHADERS */
/* Vertex Shader */
const char *VertexShaderSource="#version 330 core\n"
"layout(location=0) in vec2 pos;\n"
"//layout(location=1) in vec2 da;//distance and angle \n"
"//layout(location=2) in vec4 color;\n"
"\n"
"out vec4 particle_color\n"
"uniform mat4 mvp;\n"
"int main(){\n"
"gl_Position = mvp*vec4(pos, 0.0,1.0));\n"
"//particle_color =;\n"
"}\n";
/* Fragment Shader*/
const char *FragmentShaderSource="#version 330 core\n"
"//in vec4 particle_color;\n"
"out vec4 color;\n"
"//layout(location=2) in vec4 color;\n"
"void main(){\n"
"color = vec4(1.0f,0.0f,0.0f,1.0f);\n"
"}\n";
/* SHADERS END */
// Particle
struct Point{
glm::vec2 pos;
// Create random color in GPU
// unsigned char r,g,b,a;
float distance;
float angle;
};
static const int max_point_number=1000;
Point PointContainer[max_point_number];
int main()
{
// Start GLFW
if(!glfwInit())
{
std::cout<<"Failed to start GLWF\n";
getchar();
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);
//glfwWindowHint(GLFW_RESIZABLE,GL,FALSE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(800, 600, "Rotating Points", NULL, NULL);
if(window == NULL)
{
std::cout<<"Initialization of the window failed\n";
getchar();
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Start GLEW;
glewExperimental = true;
if(glewInit() != GLEW_OK)
{
std::cout<<"Failed to start GLEW\n";
getchar();
return -1;
}
glfwPollEvents();
glClearColor(.0f,0.5f,0.5f,0.0f); // Black is the new orange
// Camera
glm::mat4 Projection = glm::ortho(0.0f,800.0f, 0.0f,600.0f,-5.0f,5.0f); // In world coordinates
glm::mat4 View = glm::lookAt(
glm::vec3(0,0,-1), // Camera is at (0,0,-1), in World Space
glm::vec3(0,0,0), // and looks at the origin
glm::vec3(0,1,0) // Head is up (set to 0,-1,0 to look upside-down)
);
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 mvp = Projection * View * Model; // Remember, matrix multiplication is the other way around
// No need to have depth test
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// Build and compile shaders
// Vertex Shader
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &VertexShaderSource, NULL);
glCompileShader(vertexShader);
// Fragment Shader
int fragmentShader=glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &FragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// Link Shaders
int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
// Delete Shaders after Linking
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
for(auto &p:PointContainer)
{
p.pos.x =rand() % 800;
p.pos.y =rand() % 600;
std::cout<<p.pos.x<<" "<<p.pos.y<<"\n";
}
// Vertex Shader
GLuint tPM = glGetUniformLocation(shaderProgram, "mvp");//mvp
glUniformMatrix4fv(tPM, 1, GL_FALSE, &mvp[0][0]);
GLuint pointsVertexBuffer;
glGenBuffers(1, &pointsVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, pointsVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(PointContainer), PointContainer, GL_STREAM_DRAW); // Start with NULL, update with frames;
do
{
// Clear the screen
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
//glDrawArraysInstanced(GL_POINTS, 0, 2, max_point_number);
glBindBuffer( GL_ARRAY_BUFFER, pointsVertexBuffer );
glEnableClientState( GL_VERTEX_ARRAY );
//glEnableClientState( GL_COLOR_ARRAY );
glVertexPointer( 4, GL_FLOAT, sizeof( Point ), (void*)offsetof( Point, pos ) );
//glColorPointer( 4, GL_FLOAT, sizeof( Vertex ), (void*)offsetof( Vertex, color ) );
glDrawArrays( GL_POINTS, 0, max_point_number);
glDisableClientState( GL_VERTEX_ARRAY );
//glDisableClientState( GL_COLOR_ARRAY );
glBindBuffer( GL_ARRAY_BUFFER, 0 ); // Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while( glfwWindowShouldClose(window) == 0 );
return 0;
}
Edit:
I edited the code, still gives the same result.
#include <vector>
#include <algorithm>
#include <iostream>`
#include <GL/glew.h>
#include <GLFW/glfw3.h>
GLFWwindow* window;
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/norm.hpp>
/* SHADERS */
/* Vertex Shader */
const char *VertexShaderSource=R"(
#version 330 core
layout(location=0) in vec2 pos;
uniform mat4 mvp;
int main(){
gl_Position = mvp*vec4(pos, 0.0,1.0);
}
)";
/* Fragment Shader*/
const char *FragmentShaderSource = R"(
#version 330 core
out vec4 color;
void main(){
color = vec4(1.0f);
}
)";
/* SHADERS END */
// Particle
struct Point{
glm::vec2 pos;
// Create random color in GPU
// unsigned char r,g,b,a;
float distance;
float angle;
};
static const int max_point_number=1000;
Point PointContainer[max_point_number];
int main()
{
// Start GLFW
if(!glfwInit())
{
std::cout<<"Failed to start GLWF\n";
getchar();
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);
//glfwWindowHint(GLFW_RESIZABLE,GL,FALSE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(800, 600, "Rotating Points", NULL, NULL);
if(window == NULL)
{
std::cout<<"Initialization of the window failed\n";
getchar();
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Start GLEW;
glewExperimental = true;
if(glewInit() != GLEW_OK)
{
std::cout<<"Failed to start GLEW\n";
getchar();
return -1;
}
glfwPollEvents();
glClearColor(.0f,0.0f,0.0f,0.0f); // Black is the new orange
// Camera
glm::mat4 Projection = glm::ortho(0.0f,800.0f, 0.0f,600.0f,-5.0f,5.0f); // In world coordinates
glm::mat4 View = glm::lookAt(
glm::vec3(0,0,1), // Camera is at (0,0,-1), in World Space
glm::vec3(0,0,0), // and looks at the origin
glm::vec3(0,1,0) // Head is up (set to 0,-1,0 to look upside-down)
);
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 mvp = Projection * View * Model; // Remember, matrix multiplication is the other way around
// No need to have depth test
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// Build and compile shaders
// Vertex Shader
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &VertexShaderSource, NULL);
glCompileShader(vertexShader);
// Fragment Shader
int fragmentShader=glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &FragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// Link Shaders
int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
// Delete Shaders after Linking
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
for(auto &p:PointContainer)
{
p.pos.x =(rand() % 800)*-1;
p.pos.y =rand() % 600;
std::cout<<p.pos.x<<" "<<p.pos.y<<"\n";
}
// Vertex Shader
GLuint tPM = glGetUniformLocation(shaderProgram, "mvp");//mvp
glUniformMatrix4fv(tPM, 1, GL_FALSE, &mvp[0][0]);
GLuint pointsVertexBuffer;
glGenBuffers(1, &pointsVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, pointsVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(PointContainer), PointContainer, GL_STREAM_DRAW); // Start with NULL, update with frames;
GLuint vao;
glGenVertexArrays( 1, &vao );
glBindVertexArray( vao );
glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0 );
glEnableVertexAttribArray( 0 );
do
{
// Clear the screen
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glDrawArrays( GL_POINTS, 0, max_point_number);
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while( glfwWindowShouldClose(window) == 0 );
return 0;
}
A:
The vertex shader doesn't even compile. A ;is missing affter out vec4 particle_color, the return type of main has to be void and at the end of gl_Position = mvp*vec4(pos, 0.0,1.0)); there is one ) to many.
I recommend to use a Raw string literal:
const char *VertexShaderSource = R"(
#version 330 core
layout(location=0) in vec2 pos;
uniform mat4 mvp;
void main(){
gl_Position = mvp*vec4(pos, 0.0,1.0);
}
)";
Since you use a core profile Context you've to use a Vertex Array Object. e.g.:
GLuint pointsVertexBuffer;
glGenBuffers(1, &pointsVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, pointsVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(PointContainer), PointContainer, GL_STREAM_DRAW); // Start with NULL, update with frames;
GLuint vao;
glGenVertexArrays( 1, &vao );
glBindVertexArray( vao );
glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0 );
glEnableVertexAttribArray( 0 );
do
{
// Clear the screen
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glDrawArrays( GL_POINTS, 0, max_point_number);
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while( glfwWindowShouldClose(window) == 0 );
You've an orthographic projection from (0, 0) to (600, 800), so the view matrix has to be
glm::mat4 View = glm::lookAt(
glm::vec3(0,0,1), // Camera is at (0,0,-1), in World Space
glm::vec3(0,0,0), // and looks at the origin
glm::vec3(0,1,0) // Head is up (set to 0,-1,0 to look upside-down)
);
Note, with your view matrix the points are drawn at the left of the viewport, so you can't see them. The point would be drawn in in the rectangle from (0, 0) to (-800, 600).
Change the color of the points in the fragment shader. The red color is hardly to see on the green ground:
const char *FragmentShaderSource = R"(
#version 330 core
out vec4 color;
void main(){
color = vec4(1.0f);
}
)";
I recommend to verify if the shader succeeded to compile by glGetShaderiv. e.g.:
glGetShaderiv( vertexShader, GL_COMPILE_STATUS, &status );
if ( status == GL_FALSE )
{
GLint logLen;
glGetShaderiv( vertexShader, GL_INFO_LOG_LENGTH, &logLen );
std::vector< char >log( logLen );
GLsizei written;
glGetShaderInfoLog( vertexShader, logLen, &written, log.data() );
std::cout << "compile error:" << std::endl << log.data() << std::endl;
}
and the program succeeded to link by glGetProgramiv. e.g.:
glGetProgramiv( shaderProgram, GL_LINK_STATUS, &status );
if ( status == GL_FALSE )
{
GLint logLen;
glGetProgramiv( shaderProgram, GL_INFO_LOG_LENGTH, &logLen );
std::vector< char >log( logLen );
GLsizei written;
glGetProgramInfoLog( shaderProgram, logLen, &written, log.data() );
std::cout << "link error:" << std::endl << log.data() << std::endl;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to update an integer value depending on the selection of a radiobutton?
This should be a fairly easy problem, but I don't know how to solve it and haven't found any appropriate answer to what I'm trying to do.
I have an html file with some text that, in very simple terms, has a string and two radio buttons. So something like this:
<html>
<head>
<title>Some title</title>
<script src="jquery.js"></script>
</head>
<body>
<div id="main">
<p> 10 GB </p>
</div>
<div class="radioButtons" style="width: 100%">
<p><input type="radio" name="radioLessGB" value="Less" align="absmiddle"/> I want less gigabytes(-3GB) </p>
<p><input type="radio" name="radioMoreGB" value="More" align="absmiddle"/> I want more gigabytes (+5GB)</p>
</div>
</body>
</html>
I need a way to update the value of the text (i.e. "10 GB") depending on the radiobutton that is selected. In particular, when the user selects the first radio button the integer value in the string above should go down by 3 right away (i.e. "10 GB" - 3 = "7 GB"), and if the user selects the second radio button, the integer value should add 5 (i.e. "10 GB" + 5 = "15 GB").
To do this I guess I have to parse the string "10 GB" to get the Integer value and then add or subtract depending on the radiobutton chosen. Then update the string with the result.
I don't want the user to click on some kind of "submit" button, the update of the number should be done 'on-the-fly' as the user toggles between radiobuttons.
I think this could be done with jQuery, I just don't know the way about it. Could someone more experienced help with sample code for a simple solution?!?
Thanks!!
A:
Using jQuery, you can simply do it as follows. try the DEMO HERE
$("input").change(function() {
$("#main").text((10 + parseInt($(this).val())) + " GB");
});
If you need to do this in pure javascript, use the following. try DEMO HERE
function valChanged(ele) {
document.getElementById('main1233').textContent = (10 + parseInt(ele.value)) + " GB";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Isomorphism between Cartesian product of a vector space and the space of linear maps
Let $V$ be a vector space defined over the field $\mathbb{F}$. Given a positive integer $n$, prove that $V^n = V \times V \cdots \times V$ ($n$ times) is isomorphic to $\mathcal{L}(\mathbb{F}^n, V)$ where $\mathcal{L}(\mathbb{F}^n, V)$ is the vector space of linear maps from $\mathbb{F}^n$ to $V$.
I am not sure how to approach this, especially since $V$ is not even assumed to be finite dimensional. What is the isomorphism between the two vector spaces?
A:
An element $f\in\mathcal{L}(\mathbb{F}^n,V)$ is totally determined by its values on the canonical basis $(e_i)_{i=1,\dots,n}$ of $\mathbb{F}^n$.
$$v_i = f(e_i)\in V.$$
You can check that
$$f\longmapsto(f(e_1),\cdots,f(e_n))$$
is an isomorphism.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mongoose virtual with multiple foreignFields
I have a Schema Events which has a key creator which is a reference to the creator and a key musicians which is an array with the musicians.
A Musician can create Events or participate as a musician. I want to create a virtual property named events to the musician which will contain all the events that the musician has created and the events that participates.
I tried this:
MusicianSchema.virtual('events', {
ref: 'Events',
localField: '_id',
foreignField: ['creator, musicians'],
justOne: false,
});
but this returns an empty array. Is there any way to make it work, or mongoose doesn't have this feature (yet)?
EDIT
This is the Event Schema:
const eventSchema = {
title: {
type: String,
trim: true,
required: true
},
description: {
type: String,
trim: true
},
startDate: {
type: Number,
required: true
},
endDate: {
type: Number,
required: true
},
picture: {
type: String,
get: getPicture,
},
location: {
type: [Number],
index: '2dsphere',
get: getLocation
},
creator: {
type: mongoose.Schema.Types.ObjectId,
required: true,
refPath: 'creatorType'
},
musicians: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Musician'
}],
creatorType: {
type: String,
required: true,
enum: ['Musician', 'Entity']
}
};
And the Musicians Schema:
const musiciansSchema = {
name: {
type: String,
trim: true,
required: true
},
picture: {
type: String,
get: getPicture,
},
description: String,
type: {
type: String,
required: true,
enum: ['Band', 'Artist'],
},
};
A:
Mongoose virtual with multiple foreignField feature is not available at the moment, Suggestion for new feature has already requested on GitHub,
For now you need to use separate virtual/populate
MusicianSchema.virtual('creatorEvents', {
ref: 'Events',
localField: '_id',
foreignField: 'creator',
justOne: false,
});
MusicianSchema.virtual('musiciansEvents', {
ref: 'Events',
localField: '_id',
foreignField: 'musicians',
justOne: false,
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Compare large text File in java line by line
Dear fellow developers I am doing a java program which compare two text files line by line, first text file has 99,000 lines and the other file has 1,15,000 lines. I want to read the files and compare in such a way so that if any line matches between the first file and the second file it should print the match.
I have written the code but it is taking almost 10 mins to complete, as it is printing due to the for loop. How can it be made fast, efficient and efficient in terms of memory allocation? How can it be optimized for performance? Please guide me.
public class Main {
static final String file1 = "file1.txt";
static final String file2 = "file2.txt";
static BufferedReader b1 = null;
static BufferedReader b2 = null;
static List<String> list_file1 = null;
static List<String> list_file2 = null;
public static void main(String[] args) {
list_file1 = new ArrayList<String>();
list_file2 = new ArrayList<String>();
String lineText = null;
try {
b1 = new BufferedReader(new FileReader(file1));
while ((lineText = b1.readLine()) != null) {
list_file1.add(lineText);
}
b2 = new BufferedReader(new FileReader(file2));
while ((lineText = b2.readLine()) != null) {
list_file2.add(lineText);
}
compareFile(list_file1,list_file2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void compareFile(List<String> list_file1, List<String> list_file2) {
for(String content1:list_file1){
for(String content2:list_file2){
if(content1.equals(content2)){
System.out.println("Match Found:-"+content1);
}
}
}
}
}
A:
Your program's time complexity is \$O(n*m)\$ and space complexity is \$O(n + m)\$ where 'n' is no. of lines in the first file and 'm' is no. of lines in second file.
Here is an optimised version of the above program, with time complexity \$O(n + m)\$ and space complexity \$O( min(m,n) )\$. I have not tested this program, but it should be able to present output on the screen within few seconds :)
import java.io.*;
import java.util.*;
class Main{
public static void main(String args[]){
try ( BufferedReader reader1 = new BufferedReader(new FileReader("file1.txt"));
BufferedReader reader2 = new BufferedReader(new FileReader("file2.txt")) ){
//assuming file1.txt is smaller than file2.txt in terms of no. of lines
HashSet<String> file1 = new HashSet<String>();
String s = null;
while( ( s = reader1.readLine()) != null){
file1.add(s);
}
while( (s = reader2.readLine()) != null ){
if(file1.contains(s))
System.out.println(s);
}
}
catch(IOException e){
System.out.println(e);
}
}
}
Note: Only one file is in memory at a time and HashSet<> instead of nested loops for comparison.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generic function to test if a position hits on a circle given a direction
I am looking for a function that given start angle, end angle, moving clockwise or anticlockwise, hitting angle and will return if such a movement hits the hitting angle or not.
So for example, if we move from 270 degrees to 50 degrees in a clockwise direction, it will hit the hitting angle = 0 or 360 degree position, but it will not hit if we move in an anticlockwise direction.
Another example is that if we move from 80 degrees to 100 degrees clockwise, it will hit hitting angle = 90 but not in a anticlockwise direction.
A:
First, you don't really need to explicitly pass the direction of travel. You just need a way to specify a particular arc of angle. So you can just adopt the convention that the angle should increase as it moves from the start to the end angle. To specify the inverse of an arc, just pass the start and end in reverse order.
So, let's define a function that works if the angles are in order from 0 to 360 degrees - no modulo required:
bool IsBetween(int low, int high, int target)
{
return (target >= low && target <= high);
}
That will work only if low is not larger than high. If it is (because the angle is sweeping across the 360 degree line), then we can just split the arc into two sections, one from the start angle to 360, and one from 0 to the finish angle.
bool SweepHits(int start, int finish, int target)
{
// check for the simple case
if (start <= finish) return IsBetween(start, finish, target);
// straddling 360 degrees - break into two sections
return IsBetween(start, 360, target) || IsBetween(0, finish, target);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make an Android ViewPager that is continuous?
All of the ViewPager examples that I've found online seem to have a static number of pages that you can swipe through. My app is for my music blog, and I want the user to be able to click a post which opens my SinglePostActivity. It should show the post, then allow the user to swipe the views to be able to see the previous post and next post.
Obviously, I don't want to have to load all of the posts and add them to a ViewPager, but load the post that the user clicked, and the previous and next posts so the user will see them as they're swiping. Once a swipe to the next post is complete, it would have to load the post after that so the user can swipe to that one (and vice versa if they swipe to view the previous post).
Are there any Android examples of how to achieve something like this?
A:
You have to create your own PostStatePagerAdapter class by extending FragmentStatePagerAdapter:
public PostStatePagerAdapter extends FragmentStatePagerAdapter {
private List data = null;
public PostStatePagerAdapter(FragmentManager fm, List data){
super(fm);
this.data = data;
}
@Override
public Fragment getItem(int arg0) {
fragmentdata = data.get(arg0)
// create your new fragment that displays your music blog entry by using fragment data got from data list
return <your fragment>;
}
@Override
public int getCount() {
return data.size();
}
}
and in your activity class' onCreate()
PostStatePagerAdapter adapter = new PostStatePagerAdapter(getSupportFragmentManager(), dataList);
ViewPager viewPager = (ViewPager) findViewById(R.id.postPager); // defined in layout xml
viewPager.setAdapter(adapter);
// pass your clicked item index to this activity and set it as view pager's current item
viewPager.setCurrentItem(index);
Remember to extend this activity class from FragmentActivity
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to save node updates switching between the "Edit" and "View" tabs in Drupal 6
Users are complaining of losing there work when switching between the "Edit" and "View" tabs in Drupal 6. I have tried to explain there is a preview button at the bottom but with multiple users constantly getting this wrong I thought it would be best to have a "autosave" on the switch of views.
I tried the Autosave module but doesn't seem to work with my install. Any ideas?
Many Thanks,
Axel
A:
I went for the onbeforeunload and dirty forms option.
This simply just uses javascript to warn the user that there work is not saved.
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML and CSS Table
I have a table like in picture:
Is it possible to achieve this with pure table (tbody,th,td,tr,thead) css, any example ? Generally I have trouble with rounded corners with border ?
A:
Yes, it is possible. But there will be some issues regarding browser prefixes for some proprieties.
There is many ways to go around it , the best being using a css processor (eg: compass).
or just google rounded corners and you will find what you looking for
Here is a post discussing it in details.
so for the rounded corners this will be:
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px; /* future proofing */
-khtml-border-radius: 10px; /* for old Konqueror browsers */
Regarding the alternating coloring you can use the css3 psudo-selector :
Please take look at this post
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
this will work just fine but in older browsers this wont work so if you want to support older borwers use a seperate class for each .
.even-td {background: #CCC}
.odd-td {background: #FFF}
JSFIDDLE DEMO
| {
"pile_set_name": "StackExchange"
} |
Q:
CAML Query Null Hyperlink Field Causes list to not appear
My list has two hyperlink fields, all new items will have both fields filled but some older items that I have to add do not have both. First, I added a few of the more recent items that have both hyperlinks to test that my CAML Query worked, and it did. Until I added an item that did not have both hyperlink fields filled in.
I've tried adding spaces to the field, does not work.
My query:
var hclientContext = new SP.ClientContext.get_current();
var hList = hclientContext.get_web().get_lists().getByTitle('HRReportsList');
// New caml for getting list based on view
var camlQueryHR = new SP.CamlQuery();
camlQueryHR.set_viewXml('<View Scope="RecursiveAll"><Query><Where><And><Eq><FieldRef Name="Year"/>' +
'<Value Type="Text">2019</Value></Eq><Eq><FieldRef Name="Report_x0020_Type"/>' +
'<Value Type="Choice">Turnover</Value></Eq></And></Where>' +
'<OrderBy><FieldRef Name="YYYYMM" Ascending="False" /></OrderBy>' +
'</Query><RowLimit>50</RowLimit><QueryOptions>' +
'<ViewAttributes Scope="Recursive" /></QueryOptions></View>');
this.hcollListItem = hList.getItems(camlQueryHR);
// end of caml for list view
//this.ncollListItem = nList.getItems("");
hclientContext.load(hcollListItem);
hclientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
to get items I have some HTML, for example:
hListItem.get_item('InfographicLink').get_description() + '</a></br></br>' +
'<a href="' + hListItem.get_item('ReportLink').get_url() + '" target="_blank">' +
hListItem.get_item('ReportLink').get_description() + '</a></div>';
Error in the console is: 'Unable to get property 'get_url' of undefined or null reference'
Not a surprise, I just don't know how to get it to work knowing that I need to allow some hyperlinks to be empty.
A:
Add a check to these two hyperlink fields, make sure they are not null like this:
while (listItemEnumerator.moveNext())
{
var hListItem = listItemEnumerator.get_current();
if(hListItem.get_item("ReportLink") && hListItem.get_item("InfographicLink"))
{
listItemInfo += hListItem.get_item('InfographicLink').get_description() + '</a></br></br>' +
'<a href="' + hListItem.get_item('ReportLink').get_url() + '" target="_blank">' +
hListItem.get_item('ReportLink').get_description() + '</a></div>';
}
}
Here is a similar question for your reference:
JSOM get_url of image null or undefined
| {
"pile_set_name": "StackExchange"
} |
Q:
Solving a set of equations with Newton-Raphson
I want to solve this set of equations with Newton-Raphson.
Can anybody help me?
$$ \cos(x_1)+\cos(x_2)+\cos(x_3)= \frac{3}{5} $$
$$ \cos(3x_1)+\cos(3x_2)+\cos(3x_3)=0 $$
$$ \cos(5x_1)+\cos(5x_2)+\cos(5x_3)=0 $$
Best regards.
A:
I am going to jump start you, but you need to show some work.
The regular Newton-Raphson method is initialized with a starting point $x_0$ and then you iterate $x_{n+1}=x_n-\dfrac{f(x_n)}{f'(x_n)}$.
In higher dimensions, there is an exact analog. We define:
$$F\left(\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix}\right) = \begin{bmatrix}f_1(x_1,x_2,x_3) \\ f_2(x_1,x_2,x_3) \\ f_3(x_1,x_2,x_3)\end{bmatrix} = \begin{bmatrix}\cos x_1 + \cos x_2 + \cos x_3 -\dfrac{3}{5} \\ \cos 3x_1 + \cos 3x_2 + \cos 3x_3 \\ \cos 5x_1 + \cos 5x_2 + \cos 5x_3 \end{bmatrix}= \begin{bmatrix}0\\0\\0\end{bmatrix}$$
The derivative of this system is the $3x3$ Jacobian given by:
$$J(x_1,x_2,x_3) = \begin{bmatrix} \dfrac{\partial f_1}{\partial x_1} & \dfrac{\partial f_1}{\partial x_2} & \dfrac{\partial f_1}{\partial x_3}\\ \dfrac{\partial f_2}{\partial x_1} & \dfrac{\partial f_2}{\partial x_2} & \dfrac{\partial f_2}{\partial x_3} \\ \dfrac{\partial f_3}{\partial x_1} & \dfrac{\partial f_3}{\partial x_2} & \dfrac{\partial f_3}{\partial x_3}\end{bmatrix} = \begin{bmatrix} -\sin x_1 & -\sin x_2 & -\sin x_3 \\ -3\sin 3x_1 & -3\sin 3x_2 & -3\sin 3x_3 \\ -5\sin 5x_1 & -5\sin 5x_2 & -5\sin 5x_3 \end{bmatrix}$$
The function $G$ is defined as:
$$G(x) = x - J(x)^{-1}F(x)$$
and the functional Newton-Raphson method for nonlinear systems is given by the iteration procedure that evolves from selecting an initial $x^{(0)}$ and generating for $k \ge 1$,
$$x^{(k)} = G(x^{(k-1)}) = x^{(k-1)} - J(x^{(k-1)})^{-1}F(x^{(k-1)}).$$
We can write this as:
$$\begin{bmatrix}x_1^{(k)}\\x_2^{(k)}\\x_3^{(k)}\end{bmatrix} = \begin{bmatrix}x_1^{(k-1)}\\x_2^{(k-1)}\\x_3^{(k-1)}\end{bmatrix} + \begin{bmatrix}y_1^{(k-1)}\\y_2^{(k-1)}\\y_3^{(k-1)}\end{bmatrix}$$
where:
$$\begin{bmatrix}y_1^{(k-1)}\\y_2^{(k-1)}\\y_3^{(k-1)}\end{bmatrix}= -\left(J\left(x_1^{(k-1)},x_2^{(k-1)},x_3^{(k-1)}\right)\right)^{-1}F\left(x_1^{(k-1)},x_2^{(k-1)},x_3^{(k-1)}\right)$$
Here is a starting vector:
$$x^{(0)} = \begin{bmatrix}x_1^{(0)}\\x_2^{(0)}\\x_3^{(0)}\end{bmatrix} = \begin{bmatrix}1\\2\\3\end{bmatrix}$$
You should end up with a solution that looks something like:
$$\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix} = \begin{bmatrix} 4.094047142323228 \\ 1.2318378396357232 \\ -0.5601417633888767 \end{bmatrix}$$
Of course, for a different starting vector you are going to get a different solution and perhaps no solution at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
Append comma to character array in java
I have a character array. I want to add comma(,) after each 3rd character. I tried the following code.
public class Comma {
char [] str = {'1','2','3','4','5','6','7','8','9'};
char [] buf = new char[15];
int size = str.length;
int c=1;
public void insert()
{
for(int i=0;i<size;i++)
{
c++;
if(c%3==0)
{
buf[c] = ',';
i++;
}
buf[i]=str[i];
}
System.out.println("Final String");
for(int i=0;i<buf.length;i++)
System.out.print(buf[i]);
}
public static void main(String args[])
{
Comma c = new Comma();
c.insert();
}
}
I am getting the following output:
Final String
1 345 789
Can someone correct me?
A:
output :
Final String
123,456,789
here is the code
public class Comma {
char[] str = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] buf = new char[20];
int size = str.length;
int c = 1;
public void insert() {
for (int i = 0; i < size; i++) {
if (c % 4 == 0) {
buf[c - 1] = ',';
i--;
} else {
buf[c - 1] = str[i];
}
c++;
}
System.out.println("Final String");
for (int i = 0; i < buf.length; i++) {
System.out.print(buf[i]);
}
}
public static void main(final String args[]) {
Comma c = new Comma();
c.insert();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Third Party library requires different version of the same DLL my application does
I'm writing an application that uses both Intel's TBB library, and an API from a company called Maplink, which also uses TBB. The problem is that both my application and the Maplink API want to load TBB.dll from the directory containing my application's binary. The version of TBB.dll that Maplink provided with their API differs from the one my application requires, and they can't both co-exist in the application's executable directory. Do I have any option here other than statically linking TBB into my application so that it doesn't try to load the wrong version of TBB.dll that the Maplink API is using?
A:
In the real world, it is a bad idea to mix different versions of the same DLL. You should really try and get your platform aligned. It is not called package hell for nothing.
That being said, it is very much up to the TBB.dll if it allows for multiple versions at once. You might be able to statically link your code against your version of TBB, but in doing so you will need to make sure the statically linked-in symbols are not dynamically visible (a compiler collection dependant linker option). The code that you have that depends on TBB must probably also be linked in a separate linker step from the one that includes linking to maplink. And the application will need to be linked without relinking against TBB.dll.
At least that is how it could work for so files in Linux.
A:
As mentioned in the comments, you may put the newer version of tbb.dll into your application directory, and it should work properly for both the application and the 3rd party library it uses. For example, the recent version - TBB 4.2 - is binary compatible with old versions back to TBB 2.0.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not able to send GPS data (lat, lon and alt) to journal (systemd)
Working on a data acquisition project where I am trying to send GPS data to cloud.
Board: Customised board based on the schematics of Raspberry Pi Compute Module 3 Lite and I/O baord. Have added GSM and GPS modules to it for my requirements.
OS : Raspbian Stretch Lite (June 2018 release, latest one)
GPS Module used: Ublox EVAM8M
My code:
from systemd import journal
import gps
import time
import threading
import datetime
# Listen on port 2947 (gpsd) of localhost
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
while True:
try:
report = session.next()
# Wait for a 'TPV' report and display the current time
# To see all report data, uncomment the line below
# print report
if report['class'] == 'TPV':
if hasattr(report, 'time'):
timestamp = report.time
print timestamp
journal.send(
channel='gps',
priority=journal.Priority.INFO,
timestamp="%f" % (time.time()*1000),
)
if report['class'] == 'TPV':
if hasattr(report, 'lat'):
lat = report.lat
print lat
journal.send(
channel='gps',
priority=journal.Priority.INFO,
lat='lat',
)
if report['class'] == 'TPV':
if hasattr(report, 'lon'):
long = report.lon
print long
journal.send(
channel='gps',
priority=journal.Priority.INFO,
long='long',
)
if report['class'] == 'TPV':
if hasattr(report, 'alt'):
altitude = report.alt
print altitude
journal.send(
channel='gps',
priority=journal.Priority.INFO,
altitude='altitude',
)
except KeyError:
pass
except KeyboardInterrupt:
quit()
except StopIteration:
session = None
print "GPSD has terminated"
I got this code from an Adafruit tutorial: https://learn.adafruit.com/adafruit-ult ... i?view=all and I installed systemd from pypi: https://pypi.org/project/systemd/ . While I am able to perfectly display timestamp, lat, lon and alt on the terminal, I am not able to send this data to the cloud. I know this because I receive the timestamp alone on the journal but not the other values. I also have another python code which does the exact same thing, and I am able to see all the data on the website. I am using python3 and not python to run that code. But the problem with that code is that, it causes the CPU to get really hot (that's another story altogether) hence I cannot use that code.
Coming back to the code here, what am I missing? I am not getting any error. Just that, I see nothing on the website.
A:
Problem solved!! I wasn't seeing any data on the website because, I need to send the entire data packet together. What I am trying to do is send all the data to the journal and from there I have a pipeline that takes all the data to an interactive tool that displays it in the form of graphs and all. So this is what I modified in my code:
while True:
try:
report = session.next()
# Wait for a 'TPV' report and display the current time
# To see all report data, uncomment the line below
#print report
if report['class'] == 'TPV':
if hasattr(report, 'time'):
timestamp = report.time
print timestamp
if hasattr(report, 'lat'):
latitude = report.lat
print latitude
if hasattr(report, 'lon'):
longitude = report.lon
print longitude
if hasattr(report, 'alt'):
altitude = report.alt
print altitude
journal.send(
channel = 'gps',
priority = journal.Priority.INFO,
timestamp = "%f" % (time.time()*1000),
latitude = "%f" % (latitude),
longitude = "%f" % (longitude),
altitude = "%f" % (altitude),
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Having trouble figuring out where to start with allowing users to subscribe to forums in my rails app
I am trying to make it so users can subscribe to a forum and when a forum is updated the user is alerted. I can't for the life of me figure out how to set up the database to do it. I am pretty sure you are supposed to set up an associative table with user_id and forum_id but I am not to sure. If someone could give me some pointers on how to start this or plan it out or even point me to some resources that would be great.
Thanks in advance.
A:
create a join table called user_forum_subscriptions
class UserForumSubscription < ActiveRecord::Base
self.table_name = "user_forum_subscriptions"
belongs_to :user
belongs_to :forum
end
class User < ActiveRecord::Base
has_many :user_forum_subscriptions
end
class Forum < ActiveRecord::Base
has_many :user_forum_subscriptions
has_many :users, :through => :user_forum_subscriptions
end
Now, forum.users are the ones you need to alert when the forum changes
| {
"pile_set_name": "StackExchange"
} |
Q:
How to end a dashed border after text instead of extending across the page in the right direction?
Dashed border (screenshot and preferred ending point)
As you can see, the border extends towards the end of the page, when I'd rather have it end right after the text ends.. (almost). Is there a specific way to do this?
p.s. I want it to only be this way for this ONE heading, not for anything else.
Here is my code:
<h1 style="border-style:dashed;border-left-width:2px;border-right-width:2px;border-width:2px;border-color:black;"><b><u>Current Projects (in order of importance):</b></u></h1>
<p><ol>
<li>Apartment Life Redux</li>
<li>Sharpshooter Infinite</li>
</ol></p>
A:
You just need to add display:inline; and rest of the thing will be fine.
<h1 style="border-style:dashed;border-left-width:2px;border-right-width:2px;border-width:2px;border-color:black; display:inline;"><b><u>Current Projects (in order of importance):</b></u></h1>
<p><ol>
<li>Apartment Life Redux</li>
<li>Sharpshooter Infinite</li>
</ol></p>
In case you want to set property only for specific element, you can use the element id like.
<div id="foo"><div> //this is in your html
#foo{display:inline;//other styles} //this is part of your css file
Hope it was helpful
| {
"pile_set_name": "StackExchange"
} |
Q:
Include a re-usable text block in query
I am looking for a solution to create a separate text-block (consisting of certain conditions) which I could create just once and later reference it inside a query:
Example:
Re-usable text-block (A1, B1, C1, D1 and G1 are actual column names):
-------------
WHERE
A1 > B1 and
B1 < C1 and
D1 > G1
-------------
and here would be the SELECT command:
SELECT * FROM table 1
---- insert reference to the re-usable text block ---
UNION
SELECT * FROM table 2
---- insert reference to the re-usable text block ---
UNION
SELECT * FROM table 3
---- insert reference to the re-usable text block ---
;
I am using UNION command in between Select statements since I have 30+ tables from which I need to fetch data that corresponds to the same exact criteria defined in this re-usable text bock. If I need to make a change, it will only apply to this re-usable text block.
How can I design this so that I only need to make the change in one place, and not once for each query?
A:
What you need here to solve your problem is a Prepared Statement.
This allows you to create a query you want to run several times, while only changing something minimal, such as a column condition.
In your case, if you want to have a parameterized where clause, you could do something like this:
PREPARE stmnt FROM 'SELECT myColumns FROM myTable WHERE ?';
Then, you can set a variable to match what you want in the where clause, and EXECUTE the statement with the USING keyword:
SET @condition = 'a1 < b1';
EXECUTE stmnt USING @condition;
Note the use of the ? in the prepared statement. This is the placeholder for where the parameter will go. If you have multiple question marks, you will need to have multiple parameters following USING and they replace the question marks in the order that you write them.
| {
"pile_set_name": "StackExchange"
} |
Q:
On Horizon Install - Could not create SSL/TLS secure channel
I am trying to install Horizon. I am not using the self signed certificates that SIF installs. I am using my own cert (Possible source of problem?). Horizon install fails with Could not create SSL/TLS secure channel.:
Invoke-InstallPackageTask : Exception calling "InstallZipPackage" with "2" argument(s):
"System.Web.Services.Protocols.SoapException: Server was unable to process request. --->
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
System.AggregateException: One or more exceptions occurred while processing the subscribers to the 'item:saved' event. --->
System.Net.Http.HttpRequestException: An error occurred while sending the request. --->
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at Sitecore.Xdb.Common.Web.Synchronous.SynchronousExtensions.SuspendContextLock[TResult](Func`1 taskFactory) at Sitecore.ExperienceAnalytics.Core.Repositories.ReferenceData.ReferenceDataSegmentStore.Save(SegmentDefinition segmentDefinition)
at Sitecore.ExperienceAnalytics.Client.Deployment.DeploySegmentDefinitionProcessor.DeploySegment(SegmentDefinition segmentDefinition)
at Sitecore.ExperienceAnalytics.Client.Deployment.DeploySegmentDefinitionProcessor.DeploySegment(Item segmentItem) at Sitecore.ExperienceAnalytics.Client.Deployment.Events.SegmentDeployedEventHandler.OnItemSaved(Object sender, EventArgs args)
at Sitecore.Events.Event.EventSubscribers.RaiseEvent(String eventName, Object[] parameters, EventResult result) --- End of inner exception stack trace ---
at Sitecore.Events.Event.EventSubscribers.RaiseEvent(String eventName, Object[] parameters, EventResult result) at Sitecore.Events.Event.RaiseEvent(String eventName, Object[] parameters)
at Sitecore.Events.Event.RaiseItemSaved(Object sender, ItemSavedEventArgs args)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Sitecore.Data.Engines.EngineCommand`2.RaiseEvent[TArgs](EventHandler`1 handlers, Func`2 argsCreator)
at Sitecore.Data.Engines.EngineCommand`2.Execute()
at Sitecore.Data.Engines.DataEngine.SaveItem(Item item)
at Sitecore.Pipelines.ItemProvider.SaveItem.TriggerDataEngine.Process(SaveItemArgs args)
at (Object , Object )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Data.Managers.DefaultItemManager.SaveItem(Item item)
at Sitecore.Data.Items.ItemEditing.AcceptChanges(Boolean updateStatistics, Boolean silent)
at Sitecore.Data.Items.ItemEditing.EndEdit(Boolean updateStatistics, Boolean silent)
at Sitecore.Data.DataManager.SetWorkflowInfo(Item item, WorkflowInfo info)
at Sitecore.Workflows.Simple.Workflow.SetStateID(Item item, String stateID, StringDictionary commentFields, String workflowID)
at Sitecore.Workflows.Simple.Workflow.PerformTransition(Item commandItem, Item item, ID stateId, StringDictionary commentFields)
at Sitecore.Workflows.Simple.Workflow.CommandActionsComplete(WorkflowPipelineArgs args)
--- End of inner exception stack trace ---
at PackageInstaller.InstallZipPackage(String packagePath, String token)
--- End of inner exception stack trace ---"
At
C:\Program Files\WindowsPowerShell\Modules\SitecoreInstallFramework\2.2.0\Public\Install-SitecoreConfiguration.ps1:641 char:25 + & $entry.Task.Command @paramSet | Out-Default
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-InstallPackageTask], MethodInvocationException
+ FullyQualifiedErrorId : SoapException,Invoke-InstallPackageTask
A:
I was also facing the same issue, then I checked this blog https://kamsar.net/index.php/2017/10/All-about-xConnect-Security/ and System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. paragraph.
To add permission to the certificate, please follow the below steps:
Type mmc on run
Go to File and click on Add/Remove Snap-in
Double click on certificate and select Computer account
Click on Finish
Now select Personal->Certificate
In the right hand side, select your client certificate
Right-click on a certificate and select All Tasks then Manage Private Keys
Click on 'Add' and type IIS APPPOOL\MyAppPoolsName, the location should be Local Computer and grant a Read permission.
If this does not resolve your issue then go to Event Viewer and check which account is failing, in my case, it was 'Network Service'
Then I have added 'Network Service' permission as well and it resolved my issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why I only get the value of the last row in my table when I click the 'AddToCart' in other row
I have this code in php
<div style="width:75%;height: 600px;float: left;overflow-x: auto;">
<form method="POST" action="addtocart.php">
<table class="table" style="overflow-x: auto; width: 900px;">
<tr>
<th class="danger" id="th">Items</th>
<th class="danger" id="th">Price(PhP)</th>
<th class="danger" id="th">Quantity</th>
<th class="danger" id="th">Action</th>
</tr>
<?php
$item=mysqli_query($conn,"select * from store");
while($pqrow=mysqli_fetch_array($item)){
$iid=$pqrow['id_item'];
?>
<tr>
<td class="warning" id="td">
<?php echo $pqrow['item']; ?></td>
<td class="warning" id="td"><input type="hidden" name="price" value="<?php echo $pqrow['price']; ?>"><?php echo $pqrow['price']; ?></td>
<td class="warning" id="td"><input type="number" style="width: 70px;" name="qty" value="1"></td>
<td class="warning" id="td"><input type="hidden" name="item" value="<?php echo $iid; ?>"><input class="btn btn-success btn-md" type="submit" name="addtocart" value="AddToCart<?php echo $iid; ?>"></td>
</tr><?php } ?>
</table></form>
</div>
When I click AddToCart in first row, the value of the last row has been fetch. I want to get the id and the input quantity when I click the AddToCart in 1st row.
A:
As you have only one form tag and multiple inputs with same name on this form, value of next input overwrites previous one. As a result you always have value of the last row.
You can fix it for example with creating a separate form for every row, e.g:
<div style="width:75%;height: 600px;float: left;overflow-x: auto;">
<table class="table" style="overflow-x: auto; width: 900px;">
<tr>
<th class="danger" id="th">Items</th>
<th class="danger" id="th">Price(PhP)</th>
<th class="danger" id="th">Quantity</th>
<th class="danger" id="th">Action</th>
</tr>
<?php
$item = mysqli_query($conn,"select * from store");
while ($pqrow=mysqli_fetch_array($item)) {
$iid=$pqrow['id_item'];?>
<tr>
<td class="warning" id="td">
<?php echo $pqrow['item']; ?></td>
<td class="warning" id="td"><?php echo $pqrow['price']; ?></td>
<td class="warning" id="td"><input type="number" style="width: 70px;" name="qty" value="1"></td>
<td class="warning" id="td">
<!-- Separate form for each record -->
<form method="POST" action="addtocart.php">
<input type="hidden" name="price" value="<?php echo $pqrow['price']; ?>">
<input type="hidden" name="item" value="<?php echo $iid; ?>">
<input class="btn btn-success btn-md" type="submit" name="addtocart" value="AddToCart<?php echo $iid; ?>">
</form>
</td>
</tr>
<?php } ?>
</table>
</div>
In this case you should track with javascript the value of quantity field. Of course, you can move <input type="number"> in a form too, but this will break your markup.
Also, if you're familiar with javascript, you can add some client preprocessing (getting values from inputs of a certain row) and use ajax-request to send these values to server.
| {
"pile_set_name": "StackExchange"
} |
Q:
MongoDB update statement to remove a portion of text in a field
I have a mongoDB collection with a field called "Url". There are many records in this collection. Inside this field, it always contains this text below:
"http://image-assets.s3.us-west-2.amazonaws.com/"
For example "http://image-assets.s3.us-west-2.amazonaws.com/folder1/folder2/blah.jpg"
I would like to remove the portion of "http://image-assets.s3.us-west-2.amazonaws.com/", so the final result should look like "folder1/folder2/blah.jpg"
I would like to write a mongodb update statement, I don't know where to start. I can think of two things: (a) remove the first x number of characters, or (b) replace the text with a null. However the text includes a lot of slashes (/)
Your help is appreciated.
A:
This aggregation query with update on the result will work:
db.urls.aggregate( [
{
$project: {
url: {
$split: [
"$url",
"http://image-assets.s3.us-west-2.amazonaws.com/"
]
}
}
}
] ).forEach( doc => db.urls.updateOne( { _id: doc._id }, { $set: { url: doc.url[1] } } )
With these two input documents:
{ url: "http://image-assets.s3.us-west-2.amazonaws.com/folder1/folder2/blah.jpg" }
{ url: "http://image-assets.s3.us-west-2.amazonaws.com/folder1/folder2/blah2.jpg" }
The updated url field will have values:
folder1/folder2/blah.jpg
folder1/folder2/blah2.jpg
[ EDIT ADD ]
Adding a check for url field with the URL string to be updated. Add this $match stage before the $project stage in the above aggregation query.
Note that in the regex search string ^ means "starts with", and the . (dot) is prefixed with a \ (backslash) so that it is considered as a dot only (not as regex meta-character).
{
$match: {
url: { $regex: '^http://image-assets\.s3\.us-west-2\.amazonaws\.com/' }
}
},
| {
"pile_set_name": "StackExchange"
} |
Q:
Size of an Array by user
I want the user to decide the size of my array
Can i do it?
I tried:
#define max 8
int a[max];
But then, user cant change a constant
I tried:
int i, a[i];
But it gives an error
Help?
A:
Assuming your compiler supports C99 and variable-length arrays, then the following code will work:
int size;
fputs("Array size? ", stdout);
scanf("%d", &size);
int array[size];
If your compiler does not, you'll have to use malloc.
int size;
int* array;
fputs("Array size? ", stdout);
scanf("%d", &size);
array = malloc(size * sizeof(*array));
/* do stuff with array */
free(array); /* don't forget to free() when finished */
Some implementations support alloca, which allocates on the stack like a variable-length array would, but this is non-standard.
A:
You need to define the array after you ask the user for input.
int size;
printf("Please enter the size of the array");
scanf(" %d", &size);
int array[size];
A:
As mentioned in above malloc is best way as it won't depend on compiler. Also because realloc can be done when you find that u need to increase of decrease the size of array.
int size;
printf("What's the array size?\n");
scanf("%d", &size);
array = (int *)malloc(size * sizeof(*array));
.
.
.
.some stuff on array
array = (int *)realloc(array, 1024); // changing size of array according to user.
more details regarding realloc is here resizing buffer using realloc
| {
"pile_set_name": "StackExchange"
} |
Q:
echo PHP variable within CSS
I'm trying to echo a php variable within my styles.php. This variable, which I defined in a separate (and included) php file, contains several values from a database :
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT NumDep, DENS FROM france WHERE DENS BETWEEN '0' AND '45' ";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) )
{
$dens = $db_field['NumDep'] . ",<BR>";
echo $dens;
When I echo the variable $dens in my index.php file, the 20 values are showing normally. But when I echo the $dens variable in my styles.php file, only the last value is printed.
<?php
echo $dens; ?> <?php echo "
{
fill: #FFC285;
fill-opacity:1;
stroke:white;
stroke-opacity:1;
stroke-width:0.5;
stroke-miterlimit: 3.97446823;
stroke-dasharray: none;
}
What I want is to print the 20 values, in the same way they are printed in the index.php file.
Can anyone help me? (Alternative solutions for printing these values from the database into the styles.php are welcome!)
Thanks in advance.
Jonas
A:
Instead
$dens = $db_field['NumDep'] . "\n";
use
$dens .= $db_field['NumDep'] . "\n";
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to send data to two different scripts?
Simple html question. Is it possible to send data from html forms, like normal using "action" to two different scripts? Or is there any other way to do that? Besides using curl.
A:
use jquery to fire off two ajax calls to two seperate scripts..
$('#button').click(function(){
$.ajax({
url: 'script1.php'
});
$.ajax({
url: 'script2.php'
});
)};
that's the quick and dirty way of doing it... Obviously add in error checking and success checking for both of them, in order to make sure both were submitted properly.
The ideal way is to use cURL, it avoids having js/client side issues, as well as avoiding an additional http request that's not necessary.
A:
Why not send it to one script that then sends it to the desired functions to process it?
| {
"pile_set_name": "StackExchange"
} |
Q:
Plotting a line graph from a starting point other than the origin - s3.js
I'm trying to plot data on a line graph where the x-axis are the months January to December.
The issue is: I can't seem to commence the line graph from anything other than the x-axis origin - which would be January.
Question - How can I set a start point, so the data line is plotted from March to December. I could set the data to be 0 for Jan and Feb, but I don't want the line to appear at these months.
Via http://c3js.org/samples/simple_regions.html - I can see you can set start and end regions to specify different types of lines (in this case dashes). Is there a similar way to set a start and end so January and February are hidden.
thanks
A:
You can just use a null data point.
Here's sample code:
var chart = c3.generate({
data: {
columns: [
['data', null, null, 30, 200, 100, 400, 150, 250]
]
}
});
Here's the working fiddle: http://jsfiddle.net/jrdsxvys/1/
| {
"pile_set_name": "StackExchange"
} |
Q:
AWS Amplify. Use existing resources
I have followed the tutorial:
https://aws-amplify.github.io/docs/android/start?ref=amplify-android-btn
To integrate AWS S3 with my android application.
I'm able to download a file, and everything works fine.
I've notice that when i create a enviroment, it creates a new bucket, i don't want to create a new bucket, i want to use an existing one.
I've tried to change the bucket in the awsconfiguration.json. But it does not work.
"S3TransferUtility": {
"Default": {
"Bucket": "somebucket",
"Region": "us-east-1"
}
}
AmazonS3Exception: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: <ID>)
I don't want to create a new bucket, i want to be able to access crated buckets that share objects across other apps.
A:
I solved. For anyone who is interested in.
For using an existing bucket, without creating a environment with amplify. The only thing i done was to add manually the file awsconfiguration.json inside the raw folder. I do not use amplify.
So, my awsconfiguration.json looks like:
{
"Version": "1.0",
"IdentityManager": {
"Default": {}
},
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": "cognito-pool-id",
"Region": "region"
}
}
},
"S3TransferUtility": {
"Default": {
"Bucket": "somebucket",
"Region": "region"
}
}
}
And to download objects from S3 i make my TransferUtility like this:
val transferUtility = TransferUtility.builder()
.context(context)
.awsConfiguration(AWSMobileClient.getInstance().configuration)
.s3Client(getAmazonS3Client())
.build()
private fun getAmazonS3Client(): AmazonS3Client{
if (amazonS3Client == null) {
amazonS3Client = AmazonS3Client(
CognitoCachingCredentialsProvider(
context,
BuildConfig.S3_POOL_ID,
Regions.US_EAST_2
),
Region.getRegion(Regions.US_EAST_2)
)
}
return amazonS3Client!!
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Append Geocode Result to Infowindow Content
I want to ask how to append/display the geocode result into infowindow content. In this case, i have multiple marker. I try by using a div on infowindow content and update the div content after getting the geocode result (using callback), but it not works. How to solve this,,,
<html>
<head>
<title>Reverse Geocoding v3 Example</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="markerwithlabel.js"></script>
<script type="text/javascript">
var locations = [
{"name":"A","lat":"25.113787","lon":"-102.233276"}, {"name":"B","lat":"25.798243","lon":"-102.96936"}, {"name":"C","lat":"27.033032","lon":"-103.974609"}, {"name":"D","lat":"26.370545","lon":"-103.112183"},
{"name":"E","lat":"26.636002","lon":"-100.794067"}, {"name":"F","lat":"25.699288","lon":"-98.827515"}, {"name":"G","lat":"24.805019","lon":"-100.332642"}, {"name":"H","lat":"24.285358","lon":"-101.705933"}
];
var geocoder;
var map;
var marker;
var lat_longs = new Array();
var infoWindow = null;
var markers = new Array();
var poi = new Array();
var fitMap = 0;
var timer = null;
totUpdateOld = new Array();
streetLocation = new Array();
ident = 0;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(26.291773,-100.914917);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
infoWindow = new google.maps.InfoWindow();
updatetimer(function() {
fitMapToBounds();
});
}
var updatetimer = function showCarPosition(){
if (markers.length>0){
ident = 2;
}
for (var i = 0; i < locations.length; i++) {
var coordinate = new google.maps.LatLng(locations[i].lat, locations[i].lon);
var windowContent =[
'<div class="windowcontent"><ul class="nav infowindow nav-pills nav-stacked">',
'<li><div id="pos'+i+'"></div><li>'].join('');
if (ident == 0){
codeLatLng(function(addr, divid){
streetLocation.push(addr);
console.log(divid+'-'+addr);
$("#"+divid).html(addr);
}, coordinate, "pos"+i);
var marker = createMarker({
map: map,
position: coordinate,
labelContent: (locations[i].name),
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
});
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
$('.viewlog').click(function() {
$.history.load($(this).attr('href'));
return false;
});
});
}
}
fitMapToBounds();
};
function codeLatLng(callback, coordinate, divid) {
if (geocoder) {
geocoder.geocode({'latLng': coordinate}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
callback(results[1].formatted_address, divid);
}else {
callback("unknown", divid);
}
}else {
return "Geocoder failed due to: " + status;
}
});
}
}
function createMarker(markerOptions) {
var marker = new MarkerWithLabel(markerOptions);
markers.push(marker);
lat_longs.push(marker.getPosition());
return marker;
}
function updateMarker(markerOptions,id) {
var marker = new MarkerWithLabel(markerOptions);
markers[id] = marker;
lat_longs[id] = marker.getPosition();
return marker;
}
function fitMapToBounds() {
var bounds = new google.maps.LatLngBounds();
if (fitMap == 0){
if (lat_longs.length>0) {
for (var i=0; i<lat_longs.length; i++) {
bounds.extend(lat_longs[i]);
}
map.fitBounds(bounds);
fitMap = 1;
}
}
}
function bindInfoWindow(marker, event, windowContent) {
google.maps.event.addListener(marker, event, function() {
infoWindow.setContent(windowContent);
infoWindow.open(map, marker);
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyDAT9KcSpQ7RNfg5iQHsivb4-72lNLanH0&sensor=false&callback=initialize";
document.body.appendChild(script);
}
$(document).ready(function() {
initialize();
});
</script>
</head>
<body>
<div id="map_canvas" style="height:400px; border:1px 00f solid;"></div>
</body>
</html>
A:
I would only reverse geocode the point when the marker is clicked and append it to the infowindow when the data is returned from the geocoder. Something like this:
function bindInfoWindow(marker, event, windowContent) {
google.maps.event.addListener(marker, event, function() {
infoWindow.setContent(windowContent);
geocoder.geocode({latLng: marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
infoWindow.setContent(infoWindow.getContent()+"<br>"+results[1].formatted_address+"<br>status="+status);
infoWindow.open(map, marker);
}
} else {
infoWindow.setContent(infoWindow.getContent()+"<br>revere geocode failed:"+status);
infoWindow.open(map, marker);
}
});
});
}
working example
You can make it a little more efficient by storing the results of the reverse geocode and not reverse geocoding the point again if it has been clicked before, like this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Probabilities depending on date of last use
I have a set of N questions. Every day I use one question, and I'd like to have a neat random selection:
The first day, each question should have a probability of 1/N to be selected.
Then, during the first month, every questions already used will not be used. Hence, the remaining question would all have a probably on 1/(N-number of questions already used) to be picked.
Until now this is easy. But, starting the second month, I'd love to add back the questions which were used more than 30 days ago. But those questions should have less probability of getting picked than the one which were never picked, and the questions used the most time ago should have a bigger probability than questions which were used only 30 days ago. To summarize the order of probability:
1 > p(questions never used) > p(oldest question used) > p(second oldest question used) > ... > p(question used 30 days ago) > 0
with p(questions never used) being the same for all never used questions.
The question used more than one year ago would be considered as never used. I could run out of questions never used before 1 year.
Of course, all the numbers I gave (one question per day, reused after 1 month, same as never used after one year) and the probabilistic distribution can be changed.
I'm sorry if I'm not clear enough, my probabilities lessons are far behind me.
Is there a formula or an algorithm to do that?
A:
One relatively simple way to do this would be to draw the questions from a (probably virtual) hat in which you put one slip of paper for each question each day. If a question is used, you remove all its slips and only start putting new ones in again after $30$ days. Then the probability for a question to be drawn would be proportional to the number of corresponding slips. If this is too quick of an increase, you could reduce it by adding another slip for a question only every couple of days. A nice feature of this approach is that it’s self-normalizing. Whereas if you had some real-valued formula to produce these probablities, you’d have to add them all up and divide them by the sum to normalize their sum to $1$. The slips take care of that themselves; each one is equally likely to be picked (though of course if you do the draw virtually, you do have to know the total number of slips to generate an appropriate pseudorandom number).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it correct to create a class instance through malloc and instead placement new?
Here is a class.
class A
{
public:
A()
private:
int m_a;
};
Can we create an object of a class instead placement operator new and using malloc, like this:
void* a = malloc(sizeof(A)); // allocate raw memory
A* obj = reinterpret_cast< A* > ( a ); // assign to the adress
a->A() // call the constructor
Is it correct? If not, can we construct an object using malloc and instead placement new (using some other C techniques)?
A:
You'll need to use placement new after getting the raw memory from malloc.
class S
{};
...
void *mem = malloc(sizeof(S));
S* s = new (mem) S(); //this is the so called "placement new"
Then explicitly call its destructor.
s->~S();
free(mem);
| {
"pile_set_name": "StackExchange"
} |
Q:
Please explain the following graph for a quantum mechanical harmonic oscillator
Graphs such as the above keep coming up when talking about harmonic oscillators in a quantum mechanical sense. However, I simply cannot make sense of them. What does each line represent why are they waves and what is the parabola? Also, I see sometimes graphs such as:
These seem to follow on from the initial graph. It's something to do with the recovery of classical behavior but I don't understand the first graph so stand no chance of getting the second ones at high n - perhaps you could explain the relation between the first and second graph please? Thanks
A:
Background
Let's start by considering the case of 2 hydrogen atoms separated by a large distance. If they happen to be on a trajectory that brings them closer together they can interact with one another. If they get close enough together they can form a bond and create a hydrogen molecule. This process is pictured in the following graph.
image source
This "potential well" is often referred to as a "Morse potential". Out on the right edge of the curve (say 5 angstroms), we have our 2 separated hydrogen atoms. As the distance between them lessens, stabilization occurs, they can fall into the well and form a hydrogen molecule.
The red lines in the Morse potential represent different vibrational states of the hydrogen molecule. Initially, the hydrogen atom is formed in one of the higher vibrational states. It can either absorb more energy through collisions and go back to 2 dissociated atoms or it can give away some excess energy through collisions and fall to a lower vibrational level.
The classical view of the hydrogen atom is two weights connected by a spring. The more energy in the system, the wider the oscillation of the spring. With lower energy the oscillations are smaller. The energy of the spring system (y-axis) as a function of separation (x-axis) is given by Hooke's Law as
$$E(x)={1\over2}kx^2$$
This is really an equation that describes a parabola, so the lower part of a Morse potential can be accurately described by a parabola. Your top drawing represents the lower part of the Morse potential diagram.
While we have used hydrogen as our model in the above explanation, the same reasoning applies to any bond formation (and subsequently bond stretch) process. For example, we could describe a $\ce{C-H}$ bond stretch in a completely analogous manner.
Your Questions
What does each line represent
Different vibrational levels, as explained above
why are they waves
Each energy state (vibrational level) is described by its own wavefunction ($\Psi_n$). The square of the wavefunction (${\Psi_{n}^2}$) describes the probability of finding the electron at a certain point on the x-coordinate for that specific vibrational energy level. From the solution to the wavefunction we find that as we go to higher and higher energy levels, the number of nodes (a point where the wavefunction = 0) in our wave continually increases. The square of the wavefunction produces positive values (the "upside-down" parabolas). We always have the same number of nodes in the wavefunction and the probability distribution. For example, in the lowest vibrational energy level (n=0) there is no node in either the wavefunction or the probability distribution. In the n=1 vibrational level there is one node in the wavefunction and probability distribution.
what is the parabola?
Explained in the background section
| {
"pile_set_name": "StackExchange"
} |
Q:
Subview not loading, but not crashing
So I've been struggling all day, trying to get a subview to show up on my app. I'm not getting any errors or crashes, but the subview just isn't showing up.
code that calls the subview from the main ViewController (calls when a button is tapped):
- (IBAction)SettingsButtonTapped:(id)sender {
SettingsView *settings= [[SettingsView alloc]initWithFrame:CGRectMake(0,0,100,100)];
//Thank you to Calman for fixing the init!
[self.view addSubview:settings];
}
and here is the subview .h file:
#import <UIKit/UIKit.h>
@interface SettingsView : UIView
@property (weak, nonatomic) IBOutlet UITextField *username;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *BackButton;
@end
and the .m file:
#import "SettingsView.h"
#import "ViewController.h"
@implementation SettingsView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *name = [prefs stringForKey:@"name"];
NSString *number = [prefs stringForKey:@"number"];
username.tag=1;
phoneNumber.tag=2;
//if username is there
if(name!=NULL)
{
username.text = name;
}
//if phone number is there
if(number!=NULL)
{
phoneNumber.text=number;
}
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
@synthesize username;
@synthesize phoneNumber;
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *data=textField.text;
if(textField.tag==1){
//username was edited
[prefs setObject:data forKey:@"name"];
}
else if (textField.tag==2){
//phone number was edited
[prefs setObject:data forKey:@"number"];
}
}
@end
If anyone knows or has any ideas what might be going wrong, I'd love to hear!
A:
If you're using a xib file, then you're using the wrong init method. You need to load the nib like this:
- (IBAction)SettingsButtonTapped:(id)sender {
UINib *nib = [UINib nibWithNibName:@"SettingsView" bundle:nil];
SettingsView *settings= [nib instantiateWithOwner:self options:nil][0];
[self.view addSubview:settings];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
smarty not working on new server PHP Version 5.2.6
Warning: preg_match() [function.preg-match]: Compilation failed: repeated subpattern is too long at offset 18454 in /Smarty_Compiler.class.php on line 454
Fatal error: Smarty error: [in login.tpl line 1]: syntax error: unrecognized tag: php (Smarty_Compiler.class.php, line 455)
this message coming.. it was working perfect on dev server but on live server its not working.
Dev php version was 5.2.14
new server has PHP Version 5.2.6
is this the problem?
A:
What smarty version are you using?
This thread seems to imply it has to do with a combination of Smarty versions and php version:
http://www.smarty.net/forums/viewtopic.php?t=14563
For most users the sollution seems to be to downgrade Smarty from 2.6.21 to 2.6.20
It's kind of an old thread though, so check if it applies, but it seems akin to your problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
"tf get" when file has local changes and a new version is available
I have a preference of using the command line with TFS, but I'm not sure how to accomplish the equivalent of what VS2010 does when you have local changes on a file and a new version is available. VS asks the question of whether you'd like to merge, etc.
Is there a way to automerge when I do a tf get on a file in which I've made local changes and a new version of a file is available?
A:
If you have a pending change on a file and there are newer contents on the server, then when you do a tf get, you will be notified that you have conflicts, and the content will not be downloaded.
At that point, you can run tf resolve to raise the conflict resolution dialog, similar to what you see in Visual Studio, allowing you to automerge, merge in the three-way merge tool, or simply take the server or local version.
If you would prefer a fully automated experience (or you're using the tf command-line client on Unix), then you can also provide a resolution option to tf resolve. For example, to automerge a file:
tf resolve $/Project/File.txt /auto:AutoMerge
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.