text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Azure Database Sync
Not sure to understand the best way to do this. I have an application which runs with a ms sql db in a local server and I want to migrate this to Azure. I want to establish a sync between local and cloud db and be able to switch my connections string between local and cloud regularly to test if it's suitable to work with azure before switching completely to Azure.
I am have this issue with the MS SQL Data sync preview:
Unable to apply a row that exceeds the Maximum Application Transaction Size for table 'dbo.XXXXXX'. Please increase the transaction size to be greater than the size of the largest row being synchronized
Shall I use the Microsoft.Synchronization framework to do my custom sync ? Is this a lot of work ? Or is there a way to allow the sync agent to synchronize heavy tables ?
A:
The root cause of your sync failure is the row size of table dbo.XXX is 32278KB, which larger than the Data Sync support size of 24576KB. Here is a doc describing the limitations of Data Sync Service.
http://msdn.microsoft.com/en-us/library/jj590380.aspx.
| {
"pile_set_name": "StackExchange"
} |
Q:
Splitting Python module into many files
My Python module has become too big. So instead of a single file
paradigms.py
class Hub: ...
class Virement: ...
class Bond: ...
class Credit: ...
I'd like to have a directory paradigms, with two files in it:
transfer.py
class Hub: ...
class Virement: ...
credit.py
class Bond: ...
class Credit: ...
(Of course, both the number of files, and the number of classes in a file, are much bigger.)
The problem is that I would like to continue using paradigms like I have been before:
import paradigms
paradigms.Hub(...).clear()
or
from paradigms import Credit
or even
from paradigms import *
So, in a way, I would like transfer and credit names to disappear in an external interface, and my module (I guess now it is a package) to appear to the outside like a single module. Can this be done relatively easily?
A:
You can create a paradigms package, containing your two modules transfer.py and credit.py, importing their classes to the package
level in __init__.py:
paradigms/
__init__.py
credit.py
transfer.py
__init__.py would be:
from credit import *
from transfer import *
You can then do:
import paradigms
paradigms.Bond
etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamic return status from restler
If I put an @status 201 in my function comments then that's what gets returned always on success. Is there a way to make that dynamic?
For example, I have a putChild($child_id, $team_id) method defined. If the child is not already on the team, then I insert them and return a 201. If they are already on the team though, I just don't do anything. In that case I'd want a 200 status to go back, not a 201.
Not sure how to handle this situation.
A:
With the latest version in the v3 branch, you can do the following in the api method to override the status code at runtime
$this->restler->responseCode = 201;
| {
"pile_set_name": "StackExchange"
} |
Q:
jsp create scripting variable like jsp:usebean does
I would like to do something like
<test:di id="someService"/`>
<%
someService.methodCall();
%>
where <test:di
gets and instantiates a service bean and creates a scripting variable for use. similar to how jsp:usebean works for example
<jsp:useBean id="someDate" class="java.util.Date"/>
<%
someDate.getYear();
%>
how do i make my own objects available as a scritping variable?
A:
The way this is done in a Tag Library is by using a Tag Extra Info (TEI) class.
You can find an example here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Render .h Blender Export to iPhone with openGL ES 1.1
I have a blender image exported using Jeff LaMarche .h export script. I am trying to get it to render in OpenGL ES 1.1. I don't think I am passing my vertices, normals, and texture coords right. Can someone help me out. Here is what I have.
This is the .h file with my vertices,etc.
struct vertexDataTextured
{
GLKVector3 vertex;
GLKVector3 normal;
GLKVector2 texCoord;
};
typedef struct vertexDataTextured vertexDataTextured;
typedef vertexDataTextured* vertexDataTexturedPtr;
static const vertexDataTextured MeshVertexData[] = {
{/*v:*/{0.351562, 0.828125, -0.242188}, /*n:*/{0.183599, 0.982971, 0.005310}, /*t:*/{0.199397, 0.671493}},
{/*v:*/{0.445312, 0.781250, -0.156250}, /*n:*/{0.715171, 0.222724, 0.662465}, /*t:*/{0.216226, 0.665719}},
{/*v:*/{0.476562, 0.773438, -0.242188}, /*n:*/{0.964446, 0.263863, 0.012665}, /*t:*/{0.216737, 0.679097}},
{/*v:*/{-0.476562, 0.773438, -0.242188}, /*n:*/{-0.964446, 0.263863, 0.012665}, /*t:*/{0.052251, 0.677297}},
{/*v:*/{-0.445312, 0.781250, -0.156250}, /*n:*/{-0.715171, 0.222724, 0.662465}, /*t:*/{0.053356, 0.663955}},
...
and here is my drawing code
...
glClearColor(1.0f, 1.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f,-0.3f,-0.5f);
glVertexPointer(3, GL_FLOAT, 0, MeshVertexData);
glEnableClientState(GL_VERTEX_ARRAY);
glNormalPointer(GL_FLOAT, 0 , MeshVertexData);
glEnableClientState(GL_NORMAL_ARRAY);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glTexCoordPointer(2, GL_FLOAT,0,MeshVertexData);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
//glTranslatef(0.0f,-1.0f,-1.5f);
glDrawArrays(GL_TRIANGLES, 0, sizeof(MeshVertexData)/ sizeof(vertexDataTextured));
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
Basically it looks like my screen threw up triangles everywhere. Any help for this N00B is very appreciated. Thanks
A:
You're setting your stride to 0. It should be sizeof (vertexDataTextured). It tells OpenGL how many bytes there are between one vertex (or normal, or texture coord) and the next.
| {
"pile_set_name": "StackExchange"
} |
Q:
why am I getting a "was not declared in this scope" error?
I get 5 errors at the following snippet of code
4 of the errors are
expected unqualified-id before '('
token|
and 1 error
'GetEntityIterator' was not declared
in this scope|
GetEntityIterator() returns vector<*Entity>::iterator EntityIterator
GetAABB() returns an AABB
I can post more code if needed
void Bomb::CreateExplosion(Game_Manager* EGame_Manager)
{
BombTexture->LoadTexture("Bomb.bmp");
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
for(int iteration = 1; iteration <= 3; iteration++)
{
if(this->GetAABB()->CheckForCollision(this->GetAABB(), EGame_Manager->getEntityManager()->(*GetEntityIterator())->GetAABB()) == true)//check for collision against the unbreakable blocks or player and does what is necessary for each
{
if(EGame_Manager->getEntityManager()->(*GetEntityIterator())->GetType() == unbreakableblock)
{
break;
}
else if(EGame_Manager->getEntityManager()->(*GetEntityIterator())->GetType() == player)
{
EGame_Manager->getEntityManager()->(*GetEntityIterator())->GetLives() -= 1;
}
}
else
glBegin(GL_QUADS);
glColor4f( 1.0f, 0.0f, 0.0f, 0.0f); //color red
glTexCoord2f(0.0, 0.0); //uv coordinates
glVertex3f( -2.0f + x,2.0f + y, 0.0f); //top left
//----------------------------------------------------
glColor4f( 0.0f, 1.0f, 0.0f, 0.0f); //color green
glTexCoord2f(1, 0.0 ); //uv coordinates
glVertex3f( 2.0f + x,2.0f + y, 0.0f); //top right
//----------------------------------------------------
glColor4f( 0.0f, 0.0f, 1.0f, 0.0f); //color blue
glTexCoord2f(1, 1);
glVertex3f( 2.0f + x, -2.0f + y, 0.0f); //bottom right
//----------------------------------------------------
glColor4f( 1.0f, 1.0f, 0.0f, 0.0f); //color red
glTexCoord2f(0.0, 1); //uv coordinates
glVertex3f(-2.0f + x, -2.0f + y, 0.0f); //bottom left
glEnd();
}
glDisable(GL_TEXTURE_2D); //disable 2d textures
}
A:
Maybe because of this syntax:
getEntityManager()->(*GetEntityIterator())
?
I'm not sure what you were trying to do, but the -> operator is supposed to be followed by the name of a member of the class.
Edit
After reading iaamilind's comment, I finally think I understand what you were trying to do. You were trying to dereference the iterator, but then you still had to dereference the pointer (Entity*) it returned, so the -> operator was not enough. You're correct that you have to use parentheses and the * operator - but you've put them in the wrong place. This is what you should do:
(*EGame_Manager->getEntityManager()->GetEntityIterator())->GetType()
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a backup array
I would like to store testArray in tempArray, and then erase testArray. In the code below tempArray gets erased along with testArray. Please explain why this isn't working along with a computationally minimal way of achieving this.
var testArray = new Array();
testArray.push("green");
alert(testArray.length);//returns one
var tempArray = new Array();
var tempArray = testArray;
alert(tempArray.length);//returns one
testArray.length = 0;
alert(tempArray.length);//returns zero
A:
var tempArray = testArray.slice();
Creates a copy of the testArray
A:
This is a pass-by-value vs a pass-by-reference issue. When you do
var tempArray = testArray;
you are creating a reference to testArray. Basically tempArray is just another name for the same object. As the other answers point out, what you need is a method like slice() which copies the data in testArray.
If you find this confusing you might want to do some research into pass by reference, vs pass by value -- it very much varies language to language. I did a quick google on 'Javascript pass by reference vs pass by value' and found a few articles. For example this looks like it might be a decent place to start.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pandas data frame. Column consistency. Bring integer values to fixed length
I open the .tsv file in a following way:
cols = ['movie id','movie title','genre']
movies = pd.read_csv('movies.dat', sep='::', index_col=False, names=cols, encoding="UTF-8",)
+---+----------+-------------------------------------+
| | movie id | movie title |
+---+----------+-------------------------------------+
| 0 | 8 | La sortie des usines Lumière (1895) |
| 1 | 12 | The Arrival of a Train (1896) |
| 2 | 91 | Le manoir du diable (1896) |
| 3 | 417 | Le voyage dans la lune (1902) |
+---+----------+-------------------------------------+
In the initial .tsv file all the values in movie id column are fixed length and start with 0, for example 0000008, 0000012, 0000091, 0000417.
I need to merge this column later with another data frame, that has numbers in the format tt0000008, tt0000012. For this I try to get the numbers fully, without omitting 0.
What would be the way to have full numbers like 0000008, 0000012, 0000091, 0000417?
A:
I will recommend convert to str , then format with pad or rjust
s.astype(str).str.rjust(7,'0')
Out[168]:
0 0000008
1 0000012
2 0000091
3 0000417
dtype: object
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to have Ad-Hoc polymorphism with runtime dispatch?
As I did understand, and as it's described here, ad-hoc polymorphism is limited to compile-time dispatch. That is, if we have a function that expects an argument that belongs to a typeclass, we must know the concrete type of the argument at compile time to be able to use this function.
So the following (in Haskell-like pseudocode) will be invalid:
// C-style comments
typeclass Num(X) where:
add :: X -> X -> X
one :: X
implementation Num for Int:
add x y = x + y
one = 1
implementation Num for Rational:
// analogous thing…
veryCleverFunction :: Num a -> a -> a
veryCleverFunction x = add x one
tooCleverFunction :: Int -> Num(?)
tooCleverFunction x = {
y =
if (x > 0)
x
else
Rational(x, 2) // `y` has a value of unknown type,
// but we know it's under `Num` typeclass
veryCleverFunction y // can work with any `Num`s, but here the concrete type is unknown…
}
(I hope it's clear what I want to depict in this snippet)
At least in Scala I'm almost sure there's no way to express this. Or I'm wrong?
And is it possible in theory? Are there any languages which allow this?
A:
There are different mechanisms of polymorphism. Except for parametric polymorphism, these dispatch control flow depending on the type of function arguments. In other words: they are some kind of function overloading. The arguments can either be considered for their static type or for their dynamic type. If we dispatch a call on a static type, we call this ad-hoc polymorphism. If we dispatch on the dynamic type, this is either single dispatch if we only consider the dynamic type of one argument (typically an object on which a method is called), or multiple dispatch if we consider the dynamic type of all arguments.
All OOP languages must at least offer single dispatch. The Visitor Pattern can be used to fake multiple dispatch by using additional levels of indirection, but is impractical for more than two arguments. Multi-dispatch in general solves the same kind of problems that ad-hoc polymorphism does, except that it happens at runtime and can therefore be more expressive. Noteworthy examples of languages with multi-dispatch (sometimes called multi-methods) are the Common Lisp Object System (CLOS) and the Julia language.
The blog post you linked to does demonstrate ad-hoc polymorphism, but in an overly complicated fashion. The simplest example might be:
abstract class Pet
class Cat extends Pet
class Dog extends Pet
object Owner {
def pet(cat: Cat) = "You can haz cuddles!"
def pet(dog: Dog) = "Who's a good boy?"
}
val cat: Cat = new Cat()
val dog: Dog = new Dog()
val pet: Pet = new Cat()
Owner pet cat // works
Owner pet dog // works
Owner pet pet // fails, because implementation is chosen *statically*
It's the same story in Java and C++. The blog post then goes on a tangent on how using implicit parameters can be used to implement extension methods, and how they can be used to hide the visitor pattern. None of this is really relevant to ad-hoc polymorphism.
Your code example runs into problems because the return types of tooCleverFunction but more importantly of the conditional assigned to the variable y are not well defined. As y can either be Int or Rational, the type checker must reject your code. To safely allow this ambiguity, we could introduce a Union type. But if we have y :: Union Int Rational, then veryCleverFunction can't be applied to y (except of course if Union is a functor so we can do fmap veryCleverFunction y, which returns another Union for you to deal with). If we use such an Union, no static type information is lost. Instead, you have to deal with the mess you created throughout the remaining program.
You would like y to have the type Num a instead. But Num a is not a type, but a type class, i.e. a restriction on the type a.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get HTML code, based on a template with data from Google Sheets
I have some HTML template. I also have a list of products with some data in my spreadsheet. I need HTML code for each of product(So I can copy&paste it where I need it). Additionally, all product data should be populated to HTML template.
For example:
I have some product "A" in google sheets.
pirce
color
size
The price, color and size are inserted into my HTML template
I get the HTML code.
The same for product B, product C and so on
I just built some functions on JavaScript to handle some calculations, but I was not able to find how it actually works with HTML. Any high-level or preferably low-level steps are fine. Any links and / or suggestion will be also good.
A:
This function produces html for a table. Data is from a Products sheet which is shown at the bottom. Data is displayed as a dialog but could easily become a webapp.
function getProductData() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Products');
var rg=sh.getDataRange();
var vA=rg.getValues();
var html='<style>th,td{border:1px solid black;}</style><table><tr><th>Item</th><th>Name</th><th>Color</th><th>Size</th><th>Price</th></tr>';
for(var i=1;i<vA.length;i++) {
html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',vA[i][0],vA[i][1],vA[i][2],vA[i][3],vA[i][4]);
}
html+='</table>';
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'My Products');
}
This is what my Products sheet looks like:
| {
"pile_set_name": "StackExchange"
} |
Q:
Jupyter notebook magic command - use %who DataFrame to get list of DataFrames?
I can print all interactive variables, with some minimal formatting using %who.
If I only want defined DataFrames, %who DataFrame works great.
Is there a way to send the output of %who DataFrame to a list?
A:
I believe %who_ls is what you're looking for:
Return a sorted list of all interactive variables.
If arguments are given, only variables of types matching these arguments are returned.
Example use -
In [1]: x, y, z = 1, 1, 1
In [2]: ints = %who_ls int
In [3]: print(ints)
['x', 'y', 'z']
| {
"pile_set_name": "StackExchange"
} |
Q:
Unexpected form url with mixed aspx & controller MVC .Net routes
I have two routes defined thus:
//Custom route for legacy admin page
routes.MapPageRoute(
"LocaliseRoute", // Route name
"Admin/Localise", // URL
"~/Views/Admin/Localise.aspx" // File
);
routes.MapRoute(
"Admin", // Route name
"Admin/{action}/{id}", // URL with parameters
new { controller = "Admin", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
both the following GETs work fine:
http://pegfect.local/Admin/PegModelUpload
http://pegfect.local/Admin/Localise
However, the form action of the former is /Admin/Localise?action=UploadPegModel&controller=Admin
resulting in an expression of "WTF?!"
the code for the form is:
@using (Html.BeginForm("UploadPegModel", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "return validateForm();" }))
{
<input type='file' name='file' id='file' />
<input type="submit" value="submit" />
}
A:
The answer is right here: http://bartwullems.blogspot.co.uk/2011/04/combining-aspnet-webforms-and-aspnet.html
Answers on a postcard as to why this would work...
| {
"pile_set_name": "StackExchange"
} |
Q:
Can a דבר חריף transfer בליעות into a כלי without heat?
An onion is cut into small pieces with a fleishig knife. Then the pieces of onion are chopped in a food processor that was recently used to proses dairy. The onion is obviously treif, but what is the status of the food processor?
A:
There is a conflict of opinions whether or not a davar charif (sharp food) transfers taste from a meat knife, that it was first cut with, into another [neutral] utensil (see Magen Avraham 451:31) or not (see Even Ha'ozer 96:3). It therefore may be argued that in OP's case the meat taste from the knife became pagum (soiled) and therefore no issur (prohibited food) was transferred into the blender (cf. Rabbi MT Dinkel's 'Davar Charif' pg. 56). Additionally, there is the opinion that a sharp food can only emit absorbed flavor by duchka de'sakina (when pressure is applied) (cf. Pri Megadim, EA 447:32) and a blender may or may not fit this category. If the blender was not used that same day on which the onion was processed there may be different opions at play to be lenient with regards to the bender's status (cf. Dinkel, op. cit., pg. 58).
| {
"pile_set_name": "StackExchange"
} |
Q:
Fullcalendar Rails- Event does not appear on the calendar
i have git clone fullcalendar_assets and it's running smoothly and event showing.
my application rails 3.2.6 using postgresql for dbms. I try to apply fullcalendar in my application. but event not appear.
to the point.
on routes.rb
namespace admin do
resources :events
end
on admin/events_conttroler.rb
class Admin::EventsController < ApplicationController
include Tenantable::Schema::Controller
before_filter :authenticate_admin!
def index
@events = Event.scoped
@events = Event.between(params['start'], params['end']) if (params['start'] && params['end'])
respond_to do |format|
format.html # index.html.erb
format.json { render json: ([:admin, @events]) }
end
end
on event.rb
class Event < ActiveRecord::Base
include Tenantable::Schema::Model
scope :between, lambda {|start_time, end_time|
{:conditions => [
"starts_at > ? and starts_at < ?",
Event.format_date(start_time), Event.format_date(end_time)
] }
}
# need to override the json view to return what full_calendar is expecting.
# http://arshaw.com/fullcalendar/docs/event_data/Event_Object/
def as_json(options = {})
{
:id => self.id,
:nama => self.nama,
:keterangan=> self.keterangan || "",
:start => starts_at.rfc822,
:end => ends_at.rfc822,
:allDay => self.all_day,
:recurring => false,
:url => Rails.application.routes.url_helpers.adminsekolah_event_path(id),
#:color => "red"
}
end
def self.format_date(date_time)
Time.at(date_time.to_i).to_formatted_s(:db)
end
end
and on events.js.coffee
$(document).ready ->
$('#calendar').fullCalendar
editable: true,
header:
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
defaultView: 'month',
height: 500,
slotMinutes: 30,
eventSources: [{
url: '/admin/events',
}],
timeFormat: 'h:mm t{ - h:mm t} ',
dragOpacity: "0.5"
eventDrop: (event, dayDelta, minuteDelta, allDay, revertFunc) ->
updateEvent(event);
eventResize: (event, dayDelta, minuteDelta, revertFunc) ->
updateEvent(event);
updateEvent = (the_event) ->
$.update "/events/" + the_event.id,
event:
nama: the_event.nama,
starts_at: "" + the_event.start,
ends_at: "" + the_event.end,
keterangan: the_event.keterangan
i try to add one event and event put on database (schema : subdomain / not public), it's smoothly but i run localhost:3000/admin/events , event does not appear on the calendar (not error)
following command such as
Started GET "/admin/events?start=1353776400&end=1357405200&_=135557072567
2" for 127.0.0.1 at 2012-12-15 18:25:25 +0700
Processing by Admin::EventsController#index as JSON
Parameters: {"start"=>"1353776400", "end"=>"1357405200", "_"=>"1355570725672"}
Admin Load (2.0ms) SELECT "public"."admins".* FROM "public"."admins" WHERE "public"."admins"."id" = 25 LIMIT 1
Event Load (2.0ms) SELECT "events".* FROM "events" WHERE (starts_at > '2012-11-25 00:00:00' and starts_at < '2013-01-06 00:00:00')
Completed 200 OK in 10ms (Views: 3.0ms | ActiveRecord: 4.0ms)
i try the query in psql
education_development=# SELECT * FROM subdomain.events WHERE (starts_at > '2012-11-25 00:00:00' and starts_at < '2013-01-06 00:00:00')
education_development-# ;
id | name | starts_at | ends_at | all_day| description | created_at | updated_at
----+---------------+------------------------+------------------------+---------+-----------------+----------------------------+----------------------------
1 | New Year 2013 | 2013-01-01 00:00:00+07 | 2013-01-01 00:00:00+07 | f | New Year 2013 | 2012-12-15 06:53:50.695456 | 2012-12-15 06:53:50.695456
(1 row)
any idea for this issue?
A:
Apparently this is because the JSON returned from the controller, it should return an array of events but instead it returns an array of 'admin' as the first element and array of events as the second element, which fullcalendar doesn't expect. Simply use
format.json { render json: @events }
and it should work.
UPDATE: Also you localized the hash keys of the JSON representation of your event object, you must use the the same keys in fullcalendar model/event.rb.
| {
"pile_set_name": "StackExchange"
} |
Q:
Async split/aggregate gateway flows
I'm trying to build a recipe for asynchronous orchestration using spring integration gateways (both inbound and outbound). After seeing an example here, I tried using scatter-gather like this:
@Configuration
public class IntegrationComponents {
@Value("${rest.endpoint.base}")
private String endpointBase;
@Bean
public HttpRequestHandlingMessagingGateway inboundGateway() {
return Http.inboundGateway("/test-inbound-gateway-resource")
.requestMapping(mapping -> mapping.methods(HttpMethod.POST))
.requestTimeout(3000)
.replyTimeout(3000)
.get();
}
@Bean
public HttpRequestExecutingMessageHandler outboundGateway1() {
return Http.outboundGateway(endpointBase + "/test-resource-1")
.httpMethod(HttpMethod.POST)
.expectedResponseType(String.class)
.get();
}
@Bean
public HttpRequestExecutingMessageHandler outboundGateway2() {
return Http.outboundGateway(endpointBase + "/test-resource-2")
.httpMethod(HttpMethod.POST)
.expectedResponseType(String.class)
.get();
}
@Bean
public StandardIntegrationFlow integrationFlow() {
ExecutorService executor = Executors.newCachedThreadPool();
IntegrationFlow flow1 = IntegrationFlows.from(MessageChannels.executor(executor))
.handle(outboundGateway1())
.get();
IntegrationFlow flow2 = IntegrationFlows.from(MessageChannels.executor(executor))
.handle(outboundGateway2())
.get();
return IntegrationFlows
.from(inboundGateway())
.transform(String.class, String::toUpperCase)
.channel(MessageChannels.executor(executor))
.scatterGather(
scatterer -> scatterer
.applySequence(true)
.recipientFlow(flow1)
.recipientFlow(flow2),
gatherer -> gatherer
.outputProcessor(messageGroup -> {
List<Message<?>> list = new ArrayList<>(messageGroup.getMessages());
String payload1 = (String) list.get(0).getPayload();
String payload2 = (String) list.get(1).getPayload();
return MessageBuilder.withPayload(payload1 + "+" + payload2).build();
}))
.get();
}
}
This executes, but my payloads are swapped, because in this case outboundGateway1 takes longer to execute than outboundGateway2. Payload 2 comes first, then payload 1.
Is there a way to tell scatter-gather to define/maintain order when sending to the output processor?
On a similar note, maybe split/aggregate and/or using a router is a better pattern here? But if so, what would that look like?
I tried the following split/route/aggregate, but it failed saying "The 'currentComponent' (org.springframework.integration.router.RecipientListRouter@b016b4e) is a one-way 'MessageHandler' and it isn't appropriate to configure 'outputChannel'. This is the end of the integration flow.":
@Configuration
public class IntegrationComponents {
@Value("${rest.endpoint.base}")
private String endpointBase;
@Bean
public HttpRequestHandlingMessagingGateway inboundGateway() {
return Http.inboundGateway("/test-inbound-gateway-resource")
.requestMapping(mapping -> mapping.methods(HttpMethod.POST))
.requestTimeout(3000)
.replyTimeout(3000)
.get();
}
@Bean
public HttpRequestExecutingMessageHandler outboundGateway1() {
return Http.outboundGateway(endpointBase + "/test-resource-1")
.httpMethod(HttpMethod.POST)
.expectedResponseType(String.class)
.get();
}
@Bean
public HttpRequestExecutingMessageHandler outboundGateway2() {
return Http.outboundGateway(endpointBase + "/test-resource-2")
.httpMethod(HttpMethod.POST)
.expectedResponseType(String.class)
.get();
}
@Bean
public StandardIntegrationFlow integrationFlow() {
ExecutorService executor = Executors.newCachedThreadPool();
IntegrationFlow flow1 = IntegrationFlows.from(MessageChannels.executor(executor))
.handle(outboundGateway1())
.get();
IntegrationFlow flow2 = IntegrationFlows.from(MessageChannels.executor(executor))
.handle(outboundGateway2())
.get();
return IntegrationFlows
.from(inboundGateway())
.transform(String.class, String::toUpperCase)
.split()
.channel(MessageChannels.executor(executor))
.routeToRecipients(r -> r
.recipientFlow(flow1)
.recipientFlow(flow2))
.aggregate()
.get();
}
}
A:
Can you not simply Collections.sort() the list in the output processor? Each message will have a IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER header since you set applySequence.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get table column header text in Watin?
I am using Watin for automation testing with IE browser. I am new to Watin. I got blocked in a task of getting the column header text for a table.HTML code for that table is something like below:
<table id="gvVoiceCallReport" style="width: 100%; border-collapse: collapse; height: 100%;" border="1" rules="all" cellSpacing="0" cellPadding="0">
<tbody>
<tr style="background-color: slategray; height: 20px; color: white;">
<th scope="col">
<a style="color: white;" href="javascript:__doPostBack('gvVoiceCallReport','Sort$Caller GCI')">
Text - Caller GCIstyle
<th scope="col">
<a style="color: white;" href="javascript:__doPostBack('gvVoiceCallReport','Sort$Callee GCI')">
Text - Callee GCI
<th scope="col">
<a style="color: white;" href="javascript:__doPostBack('gvVoiceCallReport','Sort$Originator-Default Bearer Apn')">
Text - Originator-Default Bearer Apn
<tr style="cursor: hand;" onmouseover="this.style.cursor='hand';">
<td align="left" onclick="window.open('TestResult.aspx?testSuite=Job.139.1_1504100010110027884023126', 'TestResult', 'height=600,width=900,resizable=yes,scrollbars=yes');">
Text - 310;410;FFFE;9210;B9F
<td align="left" onclick="window.open('TestResult.aspx?testSuite=Job.139.1_1504100010110027884023126', 'TestResult', 'height=600,width=900,resizable=yes,scrollbars=yes');">
Text - 310;410;FFFE;9210;B9F
.....
......
</table>
Header text for that column is Caller GCI.
I am able to get the text for values in that column by using something like that
string columnValueText = mytable.OwnTableRows[1].TableCells[1].Text;
When I am trying to get the column header text by making OwnTableRows[0] (Index to zero), It gives me exception: array out of bounds.
Anyone, Please help me to get the table column header text.
A:
var gridTableRows = page.Document.Frame(Find.ById("ctl00_MainContentPlaceHolder_ifrmReport")).Table("gvVoiceCallReport").TableRows[0];
StringCollection abc = GetAllColumnDataFromRow(gridTableRows, true);
private StringCollection GetAllColumnDataFromRow(TableRow tableRow, bool isTableHeaderRow)
{
StringCollection RowValues = new StringCollection();
if (isTableHeaderRow)
{
foreach (Element e in tableRow.Elements)
{
if (e.TagName == "TH")
{
RowValues.Add(e.Text);
}
}
}
return RowValues;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Re-query a query in Laravel
For example, if I have this:
$user = User::where('color', 'red')
->get();
How can I query this variable, like:
$requery = $user->where('age', '25')
->get();
Thanks.
A:
Simply don't invoke get() int the first place.
$user_query = User::where('color', 'red');
Now:
$users = $user_query->get(); // to get all color red
$users = $user_query->where('age', '25'); // to get all color red of age 25
get() performs the actual query. Until you invoke that method, you can keep modifying your query, adding to it, etc.
If you have performed the query already, that is invoked get(), and you no longer have a Laravel collection, but a normal array. You can create a new collection like this:
$users = collection($users);
With this can "filter" with the wheredocs method:
$users_of_age = collection($users)->where("age", 25);
I prefer that my models return a query rather than the actual items. That way you can modify the query in your controller, say for paging, or whatever.
| {
"pile_set_name": "StackExchange"
} |
Q:
ridiculously high storage usage in iPhone 6+
I'm working (helping out) on an iOS app. On most devices the app's stabilized storage use is within 60-80MB. The same app (and same revision) on the iPhone 6+ starts using Gigabytes of data within minutes ... to the point of filling up the storage and I can't even run the app from XCode anymore. I've only been able to get it on the iPhone 6 once, but it's a regular occurrence on the 6+. I've also tried on a range of other devices from 5th gen iPod touch to the iPhone 5 and no other device goes over the 80MB.
The only portion of code that uses a significant amount of storage is the image caching, which caches the (static) images downloaded from the server keyed on the image id. Then again this code is (or seems to be) working fine on other devices. It is also a portion of the codebase that hasn't changed in a while.
Can anyone think of a reason why this issue is only seen on the iPhone6+ (and to a much lower extent the iPhone6)?
A:
The problem was that malloc stack logging was enabled and not set to compact. It logged every single allocation made by the app and it was the log file that grew so large.
As to why it only occured on the iPhone6 and iPhone6+, I still don't have an answer.
The problematic file was stack-logs.773.1006c8000.REDACTED.wmQj2k.index. It grew to 700MB almost right after login.
Much thanks to @jrturton because his answer really lead to this.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass smart pointers in function?
In the following example, when I pass p to a function, It gets destroyed as soon as the function func exits
void func(std::auto_ptr<int> p)
{
// deletes p
}
int main()
{
std::auto_ptr<int> p(new int);
func(p);
*p = 1; // run-time error
}
I'm also told that passing smart pointers by reference is very bad design from the book "The C++ Standard Library - Reference by Nicolai M. Josuttis".
Quote:
Allowing an auto_ptr to pass by reference is very bad design and you
should always avoid it .....
..... According to the concept of auto_ptrs, it is possible to transfer ownership into a function by using a constant reference.
Is it not possible to pass smart pointers or have I got the wrong idea?
A:
Is it not possible to pass smart pointers or have I got the wrong idea?
It only applies to auto_ptr. Also, as per the new C++11 standard auto_ptr is deprecated and unique_ptr is the superior alternative if you are using c++11.
The auto_ptr template class ensures that the object to which it points gets destroyed automatically when control leaves a scope, If you pass auto_ptr by value in a function, the object is deleted once the scope of the function ends. So essentially you transfer the ownership of the pointer to the function and you don't own the pointer beyond the function call.
Passing an auto_ptr by reference is considered a bad design because auto_ptr was specifically designed for transfer of ownership and passing it by reference means that the function may or may not take over the ownership of the passed pointer.
In case of unique_ptr, If you pass an unique_ptr to function by value then you are transferring the ownership of the unique_ptr to the function.
In case you are passing a reference of unique_ptr to the function if, You just want the function to use the pointer but you do not want to pass it's ownership to the function.
shared_ptr operates on a reference counting mechanism, so the count is always incremented when copying functions are called and decremented when a call is made to destructor.
Passing a shared_ptr by reference avoids calls to either and hence it can be passed by reference. While passing it by value appropriately increments and decrements the count, the copy constructor for shared_ptr is not very expensive for most cases but it might matter in some scenarios, So using either of the two depends on the situation.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to make snippet trimmed to a human readable sentence - php
First i like to thank for helping me create a really nice search result query.
I hope you friends can help me improve it.
here is the query
$searchresult = $mysql->query("SELECT * FROM pages WHERE PageContent LIKE '%$searchTerm%'");
if($searchresult->num_rows > 0) {
while (($row = $searchresult->fetch_assoc()) !== null)
{
echo '<h3>' . $row["PageTitle"] . '</h1>';
$position = strpos($row["PageContent"], $search);
$snippet = substr($row["PageContent"], $position - 200, $position + 200);
echo $snippet . '<hr><br />';
}
} else {
echo "<p>Sorry, but we can not find an entry to match your query</p><br><br>";
}
What I like to do is to make the snippet trim in such a way that it do not break any word so that the sentence is readable .... and if possible to make the search term appear in bold.
Dear friends i need your help in doing so.
Thank you all in advance.
A:
There's a lot of room for improvement, but here's an approach:
<?php
echo trimsnippet("Some really, really, really reaaally long text I don't really care about, at all.", "text", 30) . "\n";
function trimsnippet($text, $query, $max_length){
$position = strpos($text, $query);
$snippet = substr($text, max($position - $max_length - 1, 0), strlen($query) + $max_length*2 + 1);
echo "<$snippet>\n";
preg_match("/[^\w](?P<pre>.*)".$query."(?P<post>.*)[^\w]/", $snippet, $extracted);
return $extracted["pre"]."<strong>".$query."</strong>".$extracted["post"];
}
Output:
really, really reaaally long text I don't really care about,
How to use it:
Disregard the first line (echo...), it's just a demo.
Place the function anywhere in the php that uses it, and then replace your lines:
$position = strpos($row["PageContent"], $search);
$snippet = substr($row["PageContent"], $position - 200, $position + 200)
with:
$snippet = trimsnippet($row["PageContent"], $search, 200);
Some improvemets you could make to this function:
check that $query really appears in the $text
add an ellipsis (...) to the beginning or the end of the result
control what happens when the $query is near the beginning and the end (and avoid adding the ellipsis in that case)
sanitize the $query (and probably the $text also) so it cannot contain "regex syntax" that could mess with your regex pattern.
| {
"pile_set_name": "StackExchange"
} |
Q:
What type of data return /dev/random by default?
What type of data return /dev/random by default without any formatting with od (for example)?
I mean, what is the data type of these random symbols which we see when run cat /dev/random ?
A:
If you try to cat it, it will result in jibberish. You need to read it as a binary data. od, for example will work. Otherwise, you can read it in with c's read function, for example.
It is stored as a random stream of binary digits.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can society (under state rule) function without police?
Minneapolis has voted to disband its police department. This is in response to the BLM protests.
Every developed society in the world has police forces. The police are one of the state's institutions tasked with enforcing the state’s laws. Are there any examples of states (as opposed to anarchic societies) functioning without a police force? What form did law enforcement take in those states?
A:
The Minneapolis police department was founded in 1867 (and is still the second-oldest department in Minnesota).
More generally, police in its modern form was only invented in the early 1800s and mid-1800s in the US.
As with the Minneapolis police, most police forces were not respected by citizens and acted more like organized crime syndicates (eg extorting protection money, a trend that can still be seen today, where police take more money from citizens than burglars).
On the other hand, the Minneapolis police only solved 50% of murder cases in 2016 and has hundreds of untested rape kits, with a clearance rate of 22% for rape. At the same time, the MPD arrests black people for low-level offenses ten times more often than white people.
Minneapolis would not be the first city to disband a department in response to rampant misconduct, though generally other departments then take over.
More broadly, the demand to defund the police is most often not for the immediate disbanding of police, but about re-allocating funds from the police to services which serve the community and suffered under defunding themselves (like schools, hospitals, housing).
In general, there are alternatives to a heavily armed and oppressive police force though, like mediation and intervention teams, decriminalization of low-level crimes, community courts & patrols. See also the ACLU, which recommends raising the threshold for the use of lethal force, civilian-led crisis intervention teams (esp. for non-violent offenses), more teachers instead of police & diverting funds from the police to the communities.
A:
The real question is: Can 2020 society function without police?
A good way to look for an answer is to observe situations where the police have been withdrawn from regular appearances. Specifically the south side of Chicago.
This 2016 article covers the aftermath of Chicago PD withdrawing from regular patrols on the south side, in mid 2015, following an unjustified police shooting of a knife armed suspect, and subsequent riots. Granted, this is the NY Post, so a hyperbole filter is in order, but there are some meaningful facts that can be drawn.
Through the end of May, shooting incidents in Chicago were up 53 percent over the same period in 2015, which already had seen a significant increase over 2014. Compared with the first five months of 2014, shooting incidents in 2016 were up 86 percent. Shootings in May citywide averaged nearly 13 a day, a worrisome portent for summer.
So... not quite the utopian society. Crime and violence appear to have risen substantially since that article was written in 2016. This recent Sun-Times article details the carnage.
From 7 p.m. Friday, May 29, through 11 p.m. Sunday, May 31, 25 people were killed in the city, with another 85 wounded by gunfire, according to data maintained by the Chicago Sun-Times.
To consider all angles, the more affluent suburban neighborhoods already have almost no regular police presence, because there is very low crime. So, yes, they could get by without police, unless the crime from the impoverished communities comes seeking a wealthier and less prepared prey.
Based on this, I conclude that society can function without police, but it will be in a very different form from what we experience today... especially in the impoverished neighborhoods.
A:
Of course, it can (because it did before police was a thing) but much less efficiently
A dedicated police force is basically division of labor. Enforcing order and investigating crimes is a skill, and like with any other skill, it requires specific knowledge, experience and equipment to do it well, and some people are naturally better at it than others.
Before dedicated police was a thing -- and in remote and sparsely populated places that don't warrant a dedicated person -- people did and do their job themselves.
In traditional villages, there were so few people and almost no travel that everyone knews everyone around personally and had a more or less accurate picture of what everyone had and did.
So if you e.g. stole something, this would immediately become known because a thing just like what disappeared from someone suddenly appeared at you with no other explanation of where you could get it from.
Whenever a new person was introduced into a community, they had to be especially careful since until everyone gets to know them well, they would be the prime suspect for any kind of trouble.
As you can imagine, for crimes that left no conclusive evidence, people had to guess around based on random stuff and "his word against mine", and most of the time, no-one ever got to know what actually happened. Books are rife with tales of mutual suspicions and ensuing feuds that could last for generations.
In urban areas, people naturally reused the above practice by splitting a city into close-knit "areas" where everyone (more or less) knew each other. Outside trespassers were typically unwelcome there without a good escort from locals (good = able to keep them under control and not give them any means to potentially cause trouble now or in the future) and were in for trouble if anyone noticed an unfamiliar person around (a practice that survived well into the industial age).
Wealthier people who had more to lose and were a natural target for crimes typically split these areas even more, each having a protected close-knit area of their property where even fewer people were allowed in -- by erecting strong fences, gates and locks and using guard dogs and night watchers and such.
Law enforcement was likewise in the hands of whoever was in power and boiled down to how much effort they could and wished to put into it. A ruler's job was more like a negotiator between influential parties to try and keep them from cutting each others' throats than any kind of objective justice. As such, they typically didn't interfere in district-local matters and only required locals to brings up serious stuff to them that could destabilize the entire settlement if left unchecked. They usually judged cases themselves, with likewise sketchy evidence and "his word against mine" testimony.
As settlements grew, that kind of law enforcement was increasingly proving inadequte (by not being able to keep a settlement stable), ruling bodies had to increasingly hire their own trustees and guards independent from local cliques to keep order on settlement scale on an ongoing basis and investigate and judge at least that "serious stuff", being in a position to make a better resolution due to being independent from the locals.
E.g. by one of the hypotheses, in the summoning of the Varyagians, Riurik was actually hired by the Novgorod's ruling body to work as a policeman and/or independent arbiter.
In some areas, citizens organized citizen patrols where most of the able people were required to take turns participating in. Naturally, they only reacted to whatever they spotted during their patrols so they couldn't catch anything besides the most obvious stuff.
| {
"pile_set_name": "StackExchange"
} |
Q:
Split a complex file into a hash
I am running a command line program, called Primer 3. It takes an input file and returns data to standard output. I am trying to write a Ruby script which will accept that input, and put the entries into a hash.
The results returned are below. I would like to split the data on the '=' sign, so that the has would something like this:
{:SEQUENCE_ID => "example", :SEQUENCE_TEMPLATE => "GTAGTCAGTAGACNAT..etc", :SEQUENCE_TARGET => "37,21" etc }
I would also like to lower case the keys, ie:
{:sequence_id => "example", :sequence_template => "GTAGTCAGTAGACNAT..etc", :sequence_target => "37,21" etc }
This is my current script:
#!/usr/bin/ruby
puts 'Primer 3 hash'
primer3 = {}
while line = gets do
name, height = line.split(/\=/)
primer3[name] = height.to_i
end
puts primer3
It is returning this:
Primer 3 hash
{"SEQUENCE_ID"=>0, "SEQUENCE_TEMPLATE"=>0, "SEQUENCE_TARGET"=>37, "PRIMER_TASK"=>0, "PRIMER_PICK_LEFT_PRIMER"=>1, "PRIMER_PICK_INTERNAL_OLIGO"=>1, "PRIMER_PICK_RIGHT_PRIMER"=>1, "PRIMER_OPT_SIZE"=>18, "PRIMER_MIN_SIZE"=>15, "PRIMER_MAX_SIZE"=>21, "PRIMER_MAX_NS_ACCEPTED"=>1, "PRIMER_PRODUCT_SIZE_RANGE"=>75, "P3_FILE_FLAG"=>1, "SEQUENCE_INTERNAL_EXCLUDED_REGION"=>37, "PRIMER_EXPLAIN_FLAG"=>1, "PRIMER_THERMODYNAMIC_PARAMETERS_PATH"=>0, "PRIMER_LEFT_EXPLAIN"=>0, "PRIMER_RIGHT_EXPLAIN"=>0, "PRIMER_INTERNAL_EXPLAIN"=>0, "PRIMER_PAIR_EXPLAIN"=>0, "PRIMER_LEFT_NUM_RETURNED"=>0, "PRIMER_RIGHT_NUM_RETURNED"=>0, "PRIMER_INTERNAL_NUM_RETURNED"=>0, "PRIMER_PAIR_NUM_RETURNED"=>0, ""=>0}
Data source
SEQUENCE_ID=example
SEQUENCE_TEMPLATE=GTAGTCAGTAGACNATGACNACTGACGATGCAGACNACACACACACACACAGCACACAGGTATTAGTGGGCCATTCGATCCCGACCCAAATCGATAGCTACGATGACG
SEQUENCE_TARGET=37,21
PRIMER_TASK=pick_detection_primers
PRIMER_PICK_LEFT_PRIMER=1
PRIMER_PICK_INTERNAL_OLIGO=1
PRIMER_PICK_RIGHT_PRIMER=1
PRIMER_OPT_SIZE=18
PRIMER_MIN_SIZE=15
PRIMER_MAX_SIZE=21
PRIMER_MAX_NS_ACCEPTED=1
PRIMER_PRODUCT_SIZE_RANGE=75-100
P3_FILE_FLAG=1
SEQUENCE_INTERNAL_EXCLUDED_REGION=37,21
PRIMER_EXPLAIN_FLAG=1
PRIMER_THERMODYNAMIC_PARAMETERS_PATH=/usr/local/Cellar/primer3/2.3.4/bin/primer3_config/
PRIMER_LEFT_EXPLAIN=considered 65, too many Ns 17, low tm 48, ok 0
PRIMER_RIGHT_EXPLAIN=considered 228, low tm 159, high tm 12, high hairpin stability 22, ok 35
PRIMER_INTERNAL_EXPLAIN=considered 0, ok 0
PRIMER_PAIR_EXPLAIN=considered 0, ok 0
PRIMER_LEFT_NUM_RETURNED=0
PRIMER_RIGHT_NUM_RETURNED=0
PRIMER_INTERNAL_NUM_RETURNED=0
PRIMER_PAIR_NUM_RETURNED=0
=
$ primer3_core < example2 | ruby /Users/sean/Dropbox/bin/rb/read_primer3.rb
A:
#!/usr/bin/ruby
puts 'Primer 3 hash'
primer3 = {}
while line = gets do
key, value = line.split(/=/, 2)
primer3[key.downcase.to_sym] = value.chomp
end
puts primer3
A:
For fun, here are a couple of purely-functional solutions. Both assume that you've already pulled your data from the file, e.g.
my_data = ARGF.read # read the file passed on the command line
This one feels sort of gross, but it is a (long) one-liner :)
hash = Hash[ my_data.lines.map{ |line|
line.chomp.split('=',2).map.with_index{ |s,i| i==0 ? s.downcase.to_sym : s }
} ]
This one is two lines, but feels cleaner than using with_index:
keys,values = my_data.lines.map{ |line| line.chomp.split('=',2) }.transpose
hash = Hash[ keys.map(&:downcase).map(&:to_sym).zip(values) ]
Both of these are likely less efficient and certainly more memory-intense than your already-accepted answer; iterating the lines and slowly mutating your hash is the best way to go. These non-mutating variations are just a mental exercise.
Your final answer should use ARGF to allow filenames on the command line or via STDIN. I would write it like so:
#!/usr/bin/ruby
module Primer3
def self.parse( file )
{}.tap do |primer3|
# Process one line at a time, without reading it all into memory first
file.each_line do |line|
key, value = line.chomp.split('=', 2)
primer3[key.downcase.to_sym] = value
end
end
end
end
Primer3.parse( ARGF ) if __FILE__==$0
This way you can either call the file from the command line, with or without STDIN, or you can require this file and use the module function it defines in other code.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I pass multiple entries through an input parameter mapped from a Table Function in SAP HANA
How do I pass multiple entries through an input parameter mapped from a Table Function in SAP HANA ?
I've written a Table Function with an Input Parameter say IN_FORMAT_CD.
I've mapped this parameter to the one created in my calculation view.
I'm able to retrieve the data when I'm passing only one value say 100.
But it gives no result when I'm passing more than one value.
Is there any workaround for the same ?
My table function :
FUNCTION "HADMIN"."RA.Test.Prathamesh::PH_DEMO" (IN IN_FORMAT_CD NVARCHAR(500))
RETURNS TABLE (NAME NVARCHAR(10), ID NVARCHAR(10), FORMAT_CD NVARCHAR(3))
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER AS
BEGIN
RETURN
SELECT NAME,ID,FORMAT_CD
FROM
HADMIN.PH_DEMO
WHERE FORMAT_CD IN (select :IN_FORMAT_CD as FORMAT_CD from dummy);
END;
A:
it is not possible to produce(!) many items from a single sql variable unless you split them
In your SQL subselect query will return only rows that FORMAT_CD column values are exactly same with IN_FORMAT_CD parameter.
If this parameter represents more than one value, then this parameter is a concatenated string representation of each sub items. So we can split them back.
Splitting will produce a table on the fly which can be used for selection.
Please create the user-defined HANA Split function fnsplit that source codes can be found at referenced document
Then you can alter your function as follows assuming that each value is seperated with "," from others
ALTER FUNCTION "HADMIN"."RA.Test.Prathamesh::PH_DEMO" (IN IN_FORMAT_CD NVARCHAR(500))
RETURNS TABLE (NAME NVARCHAR(10), ID NVARCHAR(10), FORMAT_CD NVARCHAR(3))
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER AS
BEGIN
RETURN
SELECT NAME,ID,FORMAT_CD
FROM
HADMIN.PH_DEMO
WHERE FORMAT_CD IN (
select str from fnsplit(:IN_FORMAT_CD,',')
);
END;
| {
"pile_set_name": "StackExchange"
} |
Q:
python setting columns as value
I have a txt file with roughly 1000 lines, i want to setup colum 1 as the soruce destination and column 2 as the transfer to destination and using shutil.copyfile(src, dst) copy these files.
I have it setup as a simple print (src, dst) right now so i can see whats going on. I'm not doing something right in the for src in vld to add in the linux value.
Am i way off with this current setup to get the value of src lined up with the corresponding value of dst ? I'm using Python 2.4
import csv
import operator
import sys
import os
import shutil
inf = csv.reader(open('data.txt','r'))
sortedlist = sorted(inf, key=operator.itemgetter(2), reverse=True)
def dothis(x):
for row in sortedlist:
print row[x]
vld = dothis(0)
linux = dothis(1)
for src in vld:
dst = linux
print (src, dst)
current error message:
Traceback (most recent call last): File "test.py", line 16, in ? for src in vld:
TypeError: iteration over non-sequence
A:
You almost had it, but veered off-track somewhere there. :) dothis doesn't return anything, so vld and linux are both going to be empty.
csv.reader already "lines up" the values for you; it yields rows at a time. You're actually breaking them apart again when there's no need.
inf = csv.reader(open('data.txt','r'))
sortedlist = sorted(inf, key=operator.itemgetter(2), reverse=True)
for row in sortedlist:
src = row[0]
dst = row[1]
print src, dst
| {
"pile_set_name": "StackExchange"
} |
Q:
How to customize Feature image for a sandbox solution?
I'd like to add my own icon graphic to a feature. I found out that the ImageUrl attribute in the feature.xml definition points to the /_layouts/IMAGES folder which is out of scope for sandboxed solutions.
Is there a way to add a custom image instead of using ?
A:
No there is unfortunatley no possibility to do that.
| {
"pile_set_name": "StackExchange"
} |
Q:
local and global variable usage in Python
I am testing a reverse function. My code is as follow:
def deep_reverse(L):
new_list = []
for element in L:
new_list += [element[::-1]]
L = new_list[::-1]
L = [[1, 2], [3, 4], [5, 6, 7]]
deep_reverse(L)
print(L)
I expect my output L can be like [[7, 6, 5], [4, 3], [2, 1]], but it only works inside my function.
I wasn't able to change it in the global variable. How can I make it happen? Thank you
A:
L is just a local variable, and assigning a new object to it won't change the original list; all it does is point the name L in the function to another object. See Ned Batchelder's excellent explanation about Python names.
You could replace all elements in the list L references by assigning to the [:] identity slice instead:
L[:] = new_list[::-1]
However, mutable sequences like lists have a list.reverse() method, so you can just reverse the list in-place with that:
L.reverse()
Do the same for each sublist:
def deep_reverse(L):
""" assumes L is a list of lists whose elements are ints
Mutates L such that it reverses its elements and also
reverses the order of the int elements in every element of L.
It does not return anything.
"""
for element in L:
element.reverse()
L.reverse()
| {
"pile_set_name": "StackExchange"
} |
Q:
Resources for learning Joomla 1.6
I've been about 2 months into Joomla 1.5 and there are a lot of great training/learning resources for that version out there. Now my web host has put 1.6 in as that the default/only installation via Fantastico and I'm have mixed feelings about it - it's good to be on the latest, but my 1.5 knowledge doesn't always translate to using 1.6. I'm getting a bit lost and the help files are not actually helpful.
Does anyone have any good resources (preferably video training and/or tutorials) on learning 1.6? Especially things like "if you did X in 1.5, you'll do Y in 1.6"?
thanks in advance
A:
There's an in depth article about migrating from 1.5 to 1.6 here:
http://docs.joomla.org/Tutorial:Migrating_from_Joomla_1.5_to_Joomla_1.6
Official documentation for Joomla 1.6 is here:
http://docs.joomla.org/Category:Joomla!_1.6
Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Behavior of a Transistor?
I've read a topic on Transistors about "Using a Transistor as a switch" and then it says "To use a Transistor as a switch you have to work the Transistor on either Cut-Off mode or in Saturation mode". And then it says that "A Transistor behaves as an open switch in cut-off mode and as a closed switch in saturation mode".
So I wanted to ask as to why a Transistor behaves as an open switch in cut-off mode though it is not open and as a closed switch in saturated mode though it has some resistance? (In CE configuration)
A:
Consider these four circuits:
simulate this circuit – Schematic created using CircuitLab
How much current is flowing through BAT1 and SW1? The circuit is open so no current can flow. \$0A\$.
How much current is flowing through BAT2 and R1? By Ohm's law: \$9V/100000000\Omega = 0.00000009A\$. That's so close to 0A it like an open switch.
How much current is flowing through BAT3 and SW2? There's no resistance to limit the current, so it is unlimited. \$\infty A\$ (through in practice this can't happen, we are talking about ideals)
How much current is flowing through BAT4 and R2? Again by Ohm's law: \$9V / 0.001 = 9000A\$. That's so much current it's like infinite current, like a closed switch.
An ideal open switch is equivalent to an infinitely large resistor, \$\infty \Omega\$. An ideal closed switch is equivalent to a resistor with no resistance, \$0\Omega\$.
So while a BJT in saturation has some resistance, the resistance is small enough that we can usually consider it to be like a closed switch. Also, though you don't mention it, a BJT in cutoff has some small leakage current, that is, its resistance is very large, but not infinite. Still, we can usually consider it to be like an open switch.
You have to work the transistor in saturation or cutoff mode because if you don't, you get a transistor that's somewhere in between, like a resistor, but not a switch. Instead of almost \$0\Omega\$ or almost \$\infty\Omega\$ you get a number in between. There are many applications of transistors like this (amplifiers), but an amplifier is not like a switch.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP str_replace is not replacing value
I've been bashing my head against the wall for a couple of days on this, because all indications are that this SHOULD work, so I'm obviously missing something simple.
First I am using a function to grab an array of user submitted comments
function get_id_comment_info($id) {
global $connection;
$pdo = new PDO('mysql:host='.DB_SERVER.'; dbname='.DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
$sql = "SELECT parks.parkid, parks.state, pcomment.parkid, pcomment.comment, pcomment.logname
FROM parks
LEFT JOIN pcomment
ON parks.parkid=pcomment.parkid
WHERE parks.id = '$id'";
$result = $pdo->query($sql);
$cominfo = $result->fetchAll();
return $cominfo;
}
Then, inside of a foreach loop which processes each park by id, I am working with the data:
foreach ($display_result as $parkrow) {
$id = $parkrow['parkid'];
$comments = get_id_comment_info($id);
$cleancom = str_replace("'", '', $comments);
print_r($cleancom);
.
.
.
}
The output for $cleancom is:
Array ( [0] => Array ( [parkid] => 462 [0] => 462 [state] => KS [1] =>
KS [2] => 462 [comment] => I have noticed some others here say don't
waste your time, but I think it's ok. Yes, it's smaller than most, but
there is fun to be had if you are an avid rider. [3] => I have noticed
some others here say don't waste your time, but I think it's ok. Yes,
it's smaller than most, but there is fun to be had if you are an avid
rider. [logname] => John32070 [4] => John32070 ) )
It does not remove the '. If I use preg_replace then the output is simply blank. I am missing something simple, but I just can't see it!
A:
I have tested the str_replace() function and got the following results:
$myArray = array("h'i", array("hi'hi", "yo"));
print_r($myArray);
//RESULT: Array ( [0] => h'i [1] => Array ( [0] => hi'hi [1] => yo ) )
After applying the filter:
$filtered = str_replace( "'", "", $myArray);
print_r($filtered );
//RESULT: Array ( [0] => hi [1] => Array ( [0] => hi'hi [1] => yo ) )
What the previous results show is that any string values inside the top array are indeed being converted (h'i converted to hi) while any values that form part of the multidimensional array (any arrays within arrays) are not hi'hi remained the same. This seems to be how the function was created to work.
One solution is:
$cleancom = [];
foreach ($comments as $key => $value)
{
$cleancom[$key] = str_replace( "'", "", $value );
}
The reason the previous code works is because str_replace() is never being applied to a multidimensional array, while in your previous code it was. The previous code will not work however if you have something like an array within an array within another array, so if that ends up being the case in the future, I suggest you try finding a solution with callback functions.
Let me know if this worked for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to execute events from database at specific time
I have a table in my database called reminders. So a row may look like
Id Subject Time
1 "Foo" 2014-14-03 13:30:00
I will then like to send an email on 2014-14-03 13:30:00. What is the best way of doing so? The only solution that I can think of is querying the database every minute to see what emails I need to send. Now I need a windows service and my website because the windows service needs to constantly be running. I think there may be a better solution.
A:
You can use a library like Quartz.NET, and read your table when your service starts and periodically.
| {
"pile_set_name": "StackExchange"
} |
Q:
Attempt to split string on '//' in Jenkinsfile splits on '/' instead
What is the correct way to tokenize a string on double-forward-slash // in a Jenkinsfile?
The example below results in the string being tokenized on single-forward-slash / instead, which is not the desired behavior.
Jenkinsfile
An abbreviated, over-simplified example of the Jenkinsfile containing the relevant part is:
node {
// Clean workspace before doing anything
deleteDir()
try {
stage ('Clone') {
def theURL = "http://<ip-on-lan>:<port-num>/path/to/some.asset"
sh "echo 'theURL is: ${theURL}'"
def tokenizedURL = theURL.tokenize('//')
sh "echo 'tokenizedURL is: ${tokenizedURL}'"
}
} catch (err) {
currentBuild.result = 'FAILED'
throw err
}
}
The Logs:
The log output from the preceding is:
echo 'theURL is: http://<ip-on-lan>:<port-num>/path/to/some.asset'— Shell Script<1s
[ne_Branch-Name-M2X23QGNMETLDZWFK7IXVZQRCNSWYNTDFJZU54VP7DMIOD6Z4DGA] Running shell script
+ echo theURL is: http://<ip-on-lan>:<port-num>/path/to/some.asset
theURL is: http://<ip-on-lan>:<port-num>/path/to/some.asset
echo 'tokenizedURL is: [http:, <ip-on-lan>:<port-num>, path, to, some.asset]'— Shell Script<1s
[ne_Branch-Name-M2X23QGNMETLDZWFK7IXVZQRCNSWYNTDFJZU54VP7DMIOD6Z4DGA] Running shell script
+ echo tokenizedURL is: [http:, <ip-on-lan>:<port-num>, path, to, some.asset]
tokenizedURL is: [http:, <ip-on-lan>:<port-num>, path, to, some.asset]
Note that the logs show that the string is being tokeni on / instead of on //.
A:
tokenize takes string as optional argument that may contain 1 or more characters as delimiters. It treats each character in string argument as separate delimiter so // is effectively same as /
To split on //, you may use split that supports regex:
theURL.split(/\/{2}/)
Code Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Solr delete statement error
I'm trying out solr...I get the following error when trying a delete query:
curl http://localhost:8983/solr/update --data-binary '<delete><id>SP2514N</id></delete>'
the error is:
Error 400 missing content stream
Problem accessing /solr/update. Reason: missing content stream
A:
The other answer seems correct but doesn't explain the reason.
You only need to change the content type you're using to text/xml, otherwise curl uses the default application/x-www-form-urlencoded with the --data-binary option (or -d).
You should use the following command:
curl -H 'Content-Type: text/xml' http://localhost:8983/solr/update --data-binary '<delete><id>SP2514N</id></delete>'
You might want to add the commit=true parameter to the url to immediately issue a commit, otherwise you'll still see the document you wanted to delete (until the next commit).
You can also pass the xml directly within the url via GET like suggested in the other answer, using the stream.body parameter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Total length of pieces after splitting
If I consider the number line from $0$ to $n$ and cut it into $x$ pieces, it is well known that there is at least one stretch of length at least $n/x$. My question is what is the minimum total length of all the pieces of length at least $y$.
For example, if I split the line into three pieces and set $y = \frac{n}{3}$ then by making one piece fractionally greater than $\frac{n}{3}$ and the other two smaller, we can make the total length fractionally greater than $\frac{n}{3}$. If we set $y=\frac{n}{4}$ keeping $x=3$ then the minimum total length seems to be just over $\frac{n}{2}$. From this one can guess an answer of $n-(x-1)y$. Is this the correct answer and how can one prove it?
A:
Here's a full edit to correct my statement and provide a proof:
I claim the minimum is
$$\begin{cases} n - (x-1)y & \text{whenever } xy < n, \\ 0 & \text{otherwise.}\end{cases}$$
Here's how we may prove the claim. Observe that the minimum total length of the parts with length at least $y$ is $n$ minus the maximum total length of the parts less than $y$. Now whether we consider parts of length $< y$ or $\leq y$ isn't quite important, because by replacing $y$ by $y - \epsilon$, where $\epsilon$ is a very very small positive number, we get the same answer. Let us find the maximum total length of the parts of length less than or equal to $y$.
Suppose $xy < n$, and divide the interval $[0,n]$ into $x$ parts of lengths $s_1,s_2,\ldots, s_x$. Since $s_1 + \ldots + s_x = n$, there are at most $x - 1$ parts of length less than or equal to $y$ (otherwise $s_1 + \ldots + s_x \leq xy < n$). Thus, $$\sum_{s_k \leq y} s_k \leq (x-1)y$$
Now notice that the solution $s_1 = s_2 = \ldots = s_{x-1} = y, s_x = n - (x-1)y$ achieves this maximum, so we're done.
If, on the other hand, $xy \geq n$, then we can easily find a solution with $\sum_{s_k \leq y} s_k = n$. Since the sum of all $s_k's$ is $n$, this must be the maximum.
Therefore, the maximum is $$\begin{cases} (x-1)y & \text{whenever } xy < n, \\ n & \text{otherwise,}\end{cases}$$
which completes the proof.
| {
"pile_set_name": "StackExchange"
} |
Q:
React and Socket.io
I'm trying to create a simple app using ReactJS and Socket.io
In my component I want to be able to communicate with the server, but the problem is that I don't know how to do io.connect()
1.Do I need to explicitly specify the IP address like io.connect("http://myHost:7000") or is it enough to say : io.connect() ? As we can see in this piece of code :
https://github.com/DanialK/ReactJS-Realtime-Chat/blob/master/client/app.jsx
2.I do more or less the same as this code , but I receive error when I do npm start as io is undefined. I think , io is provided globally by including the socket.io script. How can I solve this problem ?
'use strict';
var React = require('react');
var socket = io.connect();
var chatWindow = React.createClass({
displayName: 'chatWindow',
propTypes: {},
getDefaultProps: function() {
return ({
messages: 0
});
},
componentDidMount: function() {
socket = this.props.io.connect();
socket.on('value', this._messageRecieve);
},
_messageRecieve: function(messages) {
this.setState({
messages: messages
});
},
getInitialState: function() {
return ({
messages: 0
});
},
_handleSend: function(){
var newValue = parseInt(this.refs.messageBox.value) + this.props.messages;
this.setState({
messages: newValue
});
socket.emit('clientMessage', { message: newValue});
},
render: function() {
var window =
<div>
<div>{this.props.messages}</div>
<input type="text" id="messageBox" refs="messageBox"></input>
<input type="button" onClick={this._handleSend} value="send" id="send"/>
</div>;
return (window);
}
});
module.exports = chatWindow;
This is the code :
https://github.com/arian-hosseinzadeh/simple-user-list
A:
Answers:
1) No, you don't need to specify the IP, you can even use / and it will go through the default HTTP 80 port, anyway, you can find more examples on the socket.io site.
2) Require io too, remember to add socket.io-client to your package:
var React = require('react'),
io = require('socket.io-client');
Anyway, if you want to include the client script that socket.io server provides as a static file, then remember to add it into your HTML using a <script/> tag, that way you'll have io on the global scope avoiding the require part, but well, I prefer to require it.
NOW, WHAT ABOUT...
Trying my lib: https://www.npmjs.com/package/react-socket
It will handle the socket connection on mount and disconnection on unmount (the same goes for socket event listeners), give it a try and let me know.
Here you have an example:
http://coma.github.io/react-socket/
var App = React.createClass({
getInitialState: function() {
return {
tweets: []
};
},
onTweet: function(tweet) {
var tweets = this
.state
.tweets
.slice();
tweet.url = 'https://twitter.com/' + tweet.user + '/status/' + tweet.id;
tweet.at = new Date(tweet.at);
tweet.avatar = {
backgroundImage: 'url(' + tweet.img + ')'
};
tweets.unshift(tweet);
this.setState({
tweets: tweets
});
},
renderTweet: function (tweet) {
return (
<li key={tweet.id}>
<a href={tweet.url} target="_blank">
<div className="user">
<div className="avatar" style={ tweet.avatar }/>
<div className="name">{ tweet.user }</div>
</div>
<div className="text">{ tweet.text }</div>
</a>
</li>
);
},
render: function () {
return (
<div>
<ReactSocket.Socket url="http://tweets.socket.io"/>
<ReactSocket.Event name="tweet" callback={ this.onTweet }/>
<ul className="tweets">{ this.state.tweets.map(this.renderTweet) }</ul>
</div>
);
}
});
React.render(<App/>, document.body);
| {
"pile_set_name": "StackExchange"
} |
Q:
Flair font color unreadable
The default and clean theme for user flairs have unreadable font colors.
A:
I changed the default link color in this setting to #888E84 which is based on the physics logo color.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get all the females?
I would like to get the gender for calculations, for example the male and female options are in one column. I would like to get all male or all female for calculation.
I have a "computed property" which gives me list of all the items along with calculation. Here is the code:
partial void MeanFemale_Compute(ref string result)
{
// Set result to the desired field value
int totalAge = 0;
int count = 0;
foreach (InsuranceQuotation i in his.DataWorkspace.ApplicationData.InsuranceQuotations)
{
totalAge += i.mAge;
count++;
}
if (count != 0)
{
result = (totalAge / count).ToString();
}
}
How do I get to filter the gender in this "computed property".
A:
You can use LINQ. It would look something like this:
int averageAge = this.DataWorkspace.ApplicationData.InsuranceQuotations.
Where(iq => iq.Gender == Gender.Female).
Average(iq => iq.mAge);
| {
"pile_set_name": "StackExchange"
} |
Q:
Info Web Page For Raspberry Pi Application
I have an application running on rPi2. Which reads sensor values and logs them with Time marks on file(written in java). I need to setup a webpage to show these logs. Since Pi will be a headless, i decided to go with webpage way. I picked charts.js as chart drawing library. And it accepts chart data like this :
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [1.1,2.2,3.3,4.4,5.5,6,7,8,9]
}
]
}
I need to change data and labels values on JSON programatically. And serve this page to local network. I tried to generate my Log with this JSON format but turns out JS cannot load Local File without a user picking a file from dialog. So any ideas on this?
A:
This is a cool project. I did the following:
tmp_data.txt (generated via java on the raspi after measurements):
{"labels" : ["January","February","March","April","May","June","July"],
"datasets" : [
{
"label": "My First dataset",
"fillColor" : "rgba(220,220,220,0.2)",
"strokeColor" : "rgba(220,220,220,1)",
"pointColor" : "rgba(220,220,220,1)",
"pointStrokeColor" : "#fff",
"pointHighlightFill" : "#fff",
"pointHighlightStroke" : "rgba(220,220,220,1)",
"data" : [1.1,2.2,3.3,4.4,5.5,6,5]
}
]
}
tmp_data.html:
<html>
<head>
<script src="../Chart.js"></script>
<script>
function loadXMLDoc() {
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var lineChartData = JSON.parse(xmlhttp.responseText);
var ctx = document.getElementById("canvas").getContext("2d");
new Chart(ctx).Line(lineChartData, {responsive: true});
}
}
xmlhttp.open("GET","tmp_data.txt",true);
xmlhttp.send();
}
</script>
</head>
<body onload="loadXMLDoc()">
<div style="width:30%">
<div>
<canvas id="canvas" height="450" width="600"></canvas>
</div>
</div>
</body>
</html>
The 'fields' in the data file has to be surrounded with quotes. The onload function is called when the site is loaded. The txt file will be read via a httprequest and has to be in the same directory as the html page. I would recommend that some webserver on the raspi will deliver the html.
As far as i know js cannot load a local file on the client without user interaction because this could be a serious security issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ftp : limit transfer speed
I'm writing a c# app (.Net 4.5) to download files from an ftp server.
I would like, now, to be able to set a maximum download speed.
I can't configure the server, so I will have to do it in the client.
Could anyone explain me how to do so ?
Thanks !
A:
Assuming you have the source code for the ftp client, you do this by transfer chunks of data, comparing the transfer rate compared to your desired limit rate and inserting delays if the transfer is going too fast. See How can I rate limit an upload using TcpClient? for proof of concept code
| {
"pile_set_name": "StackExchange"
} |
Q:
Please suggest an e-book for anti design pattern?
I would like to know "anti-design". Please suggest an e-book for anti design pattern.
A:
You may like to check out:
The daily wtf & Anti patterns
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: importing many variables using a function
Background
I have two files in a project. 'main.py' and 'auxillary_functions.py'. 'main.py' contains the basic code and the other file contains supporting information.
In the main file, I iterate over several cases. For each case, I have to initialize a large number of parameters e.g.
for i in range(10):
zP1HHSet, zH1HHSet, zISHHSet, zEEHHSet = [], [], [], []
dP1HHSet, dH1HHSet, dISHHSet, dEEHHSet = [], [], [], []
mP1HHSet, mH1HHSet, mISHHSet, mEEHHSet = [], [], [], []
nP1HHSet, nH1HHSet, nISHHSet, nEEHHSet = [], [], [], []
kP1HHSet, kH1HHSet, kISHHSet, kEEHHSet = [], [], [], []
tP1HHSet, tH1HHSet, tISHHSet, tEEHHSet = [], [], [], []
a_IS = 0
b_IS = 10401
and so on
This is a small subset of parameters that I need to initialize for every run.
Problem
What I want to do is to write a function, say, foo:
def foo(case):
zP1HHSet, zH1HHSet, zISHHSet, zEEHHSet = [], [], [], []
dP1HHSet, dH1HHSet, dISHHSet, dEEHHSet = [], [], [], []
mP1HHSet, mH1HHSet, mISHHSet, mEEHHSet = [], [], [], []
nP1HHSet, nH1HHSet, nISHHSet, nEEHHSet = [], [], [], []
kP1HHSet, kH1HHSet, kISHHSet, kEEHHSet = [], [], [], []
tP1HHSet, tH1HHSet, tISHHSet, tEEHHSet = [], [], [], []
One option known to me is to return all the variables one by one and then unpack them in the main file.
Is there any better way of handling this problem?
Question
How to import a large number of variables? In short I want to reduce the main code size by transferring this group of lines to another file.
A:
If your paramters have a structure (which seems to be the case given your example), it's a good idea to store them in a structured way instead of "flat" as a bunch of variables. This structure can then easily be returned by functions or passed as a parameter. There are a lot of different options to build structures in Python (lists, dicts, namedTuples, dataclasses, simpleNamespaces, ...). One possible solution using SimpleNamespace and NamedTuple could look like this:
from types import SimpleNamespace
from typing import NamedTuple, List
class ParamSet(NamedTuple):
P1HHSet: List
H1HHSet: List
ISHHSet: List
EEHHSet: List
def foo(case):
return SimpleNamespace(
z=ParamSet([], [], [], []),
d=ParamSet([], [], [], []),
m=ParamSet([], [], [], []),
n=ParamSet([], [], [], []),
k=ParamSet([], [], [], []),
t=ParamSet([], [], [], []),
)
if __name__ == "__main__":
p = foo(None)
# access members using attribute syntax
print(p.z.P1HHSet)
print(p.k.ISHHSet)
Please note that this will only work on a sufficiently new version of Python. The advantage of using NamedTuple and SimpleNamespace is that individual parameters can be accessed using convenient attribute syntax (e.g. p.z.P1HHSet) instead of dict (e.g. p["z"]["P1HHSet"]) or index (e.g. p[0][0]) syntax.
Does this answer your question?
| {
"pile_set_name": "StackExchange"
} |
Q:
How does ChannelFactory (WCF/C#) use an Interface as a type?
Looking at creating Channels explicitly in WCF, you do this:
IService channel = new ChannelFactory<IService>(binding, address).CreateChannel();
Why am I allowed to 'type' the channel factory as an interface? I know that the IService interface has to be decorated to allow this. what is ChannelFactory doing behind the scenes to allow this?
A:
Internally, ChannelFactory<TChannel> creates an object of type ServiceChannelProxy, which derives from System.Runtime.Remoting.Proxies.RealProxy, allowing it to create a transparent proxy over the TChannel interface.
| {
"pile_set_name": "StackExchange"
} |
Q:
Undefined index: collation laravel 5.1 mysql connection
I m using laravel 5.1 to make connection to mysql host.Here is the
sample.
\Config::set('database.connections.mysql', array(
'driver' => 'mysql',
'host' => "host name",
'port' => 3306,
'database' => 'db name',
'username' => 'username',
'password' => 'password'
));
$data = \DB::connection('mysql')
->table('tablename')
->get();
When i run the above code i get the error::
[ErrorException]
Undefined index: collation
A:
I think Laravel is looking for the collation value to use for the connection, but that key doesn't exist in the array you are providing. Does it work if you add a collation key => value like this? (Note - you should make sure to use the correct collation for your database.)
\Config::set('database.connections.mysql', array(
'driver' => 'mysql',
'host' => "host name",
'port' => 3306,
'database' => 'db name',
'username' => 'username',
'password' => 'password',
'collation' => 'utf8mb4_unicode_ci'
));
$data = \DB::connection('mysql')
->table('tablename')
->get();
| {
"pile_set_name": "StackExchange"
} |
Q:
Get XML nodes from certain tree level
I need a method like Document.getElementsByTagName(), but one that searches only tags from a certain level (ie, not nested tags with the same name)
Example file:
<script>
<something>
<findme></findme><!-- DO NOT FIND THIS TAG -->
</something>
<findme></findme><!-- FIND THIS TAG -->
</script>
Document.getElementsByTagName() simply returns all findme tags in the document.
A:
Here is an example with XPath
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class TestXPath {
private static final String FILE = "a.xml" ;
private static final String XPATH = "/script/findme";
public static void main(String[] args) {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
DocumentBuilder builder;
try {
builder = docFactory.newDocumentBuilder();
Document doc = builder.parse(FILE);
XPathExpression expr = XPathFactory.newInstance().newXPath().compile(XPATH);
Object hits = expr.evaluate(doc, XPathConstants.NODESET ) ;
if ( hits instanceof NodeList ) {
NodeList list = (NodeList) hits ;
for (int i = 0; i < list.getLength(); i++ ) {
System.out.println( list.item(i).getTextContent() );
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
With
<script>
<something>
<findme>1</findme><!-- DO NOT FIND THIS TAG -->
</something>
<findme>Find this</findme><!-- FIND THIS TAG -->
<findme>More of this</findme><!-- FIND THIS TAG AS WELL -->
</script>
It yields
Find this
More of this
| {
"pile_set_name": "StackExchange"
} |
Q:
Does my ZF app cause "request exceeded the limit of 10 internal redirects" errors?
We've an eCommerce site developed with ZendFrameWork v1.10. Sometimes site is loads extremely slowly, and many pages are not loading at all and are timing out. The homepage is taking upwards of 15 seconds to load, and many product pages do not load at all and simply time out.
Often times for this case we restart our apache server and site up as normal . Then we inquired the server providers they said our server health is good and they produce our server health status as like this
(~) # uptime
12:00:17 up 655 days, 10:51, 2 users, load average: 0.87, 0.65, 0.58
(~) # uptime
12:00:29 up 177 days, 6:46, 1 user, load average: 0.64, 0.53, 0.47
Also they advised us to check our server error_log because they found many php errors are loading to it. When we checking the server erro_log and it's old files. We found many of the following error in all our log files.
[Sun Dec 30 02:35:32 2012] [error] [client 66.249.76.16] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
If I checked the above error for certain IP in the error_log file eg : 66.249.76.16 I found 6 results and if I checked the IP stripping off the last two digits from it (66.249.76) I can see more than 20 errors per day like above in our error_log file.
I think, the first problem I should solve is the above "Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace" Apache log problem.
We have gone through logs and it happens daily as mentioned above, so I need to find out what code is actually causing this bug. We asked our server support to enable "Loglevel debug" (I'm not too familiar with this) but I still cannot see anything useful or any difference in our error log after enabling this.
My question is - what can I do to find out where in our site this error is being generated? It would be very helpful to know which PHP script (we have 100s) is actually making this "Request exceeded the limit of 10 internal redirects" redirect happen.
Any recommendations of how I can proceed?
A:
We also had some issues like this. We made a log in the index.php, which gave us a pretty good idea which request is causing the issue. You can implement the same and check from which requests are taking most execution time.
<?php
define('EXECUTION_START', microtime(true));
.
.
.
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH .DS. 'configs'.DS.'application.ini'
);
$application->bootstrap()
->run();
$endTime = microtime(true);
$executionTime = $endTime-EXECUTION_START;
$ipaddress = $_SERVER['REMOTE_ADDR'];
$url = $_SERVER['REQUEST_URI'];
$logString="$ipaddress|$url|$startTime|$endTime|$executionTime\n";
$file = 'executiontime.txt';
file_put_contents($file, $logString, FILE_APPEND | LOCK_EX);
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Using span with SocketAsyncEventArgs
I would like to use new Span to send unmanaged data straight to the socket using SocketAsyncEventArgs but it seems that SocketAsyncEventArgs can only accept Memory<byte> which cannot be initialized with byte * or IntPtr.
So please is there a way to do use span with SocketAsyncEventArgs?
Thank you for your help.
A:
As already mentioned in the comments, Span is the wrong tool here - have you looked at using Memory instead? As you stated, the SetBuffer method does accept that as a parameter - is there a reason you can't use it?
See also this article for a good explanation on how stack vs heap allocation applies to Span and Memory. It includes this example, using a readonly Memory<Foo> buffer:
public struct Enumerable : IEnumerable<Foo>
{
readonly Stream stream;
public Enumerable(Stream stream)
{
this.stream = stream;
}
public IEnumerator<Foo> GetEnumerator() => new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public struct Enumerator : IEnumerator<Foo>
{
static readonly int ItemSize = Unsafe.SizeOf<Foo>();
readonly Stream stream;
readonly Memory<Foo> buffer;
bool lastBuffer;
long loadedItems;
int currentItem;
public Enumerator(Enumerable enumerable)
{
stream = enumerable.stream;
buffer = new Foo[100]; // alloc items buffer
lastBuffer = false;
loadedItems = 0;
currentItem = -1;
}
public Foo Current => buffer.Span[currentItem];
object IEnumerator.Current => Current;
public bool MoveNext()
{
if (++currentItem != loadedItems) // increment current position and check if reached end of buffer
return true;
if (lastBuffer) // check if it was the last buffer
return false;
// get next buffer
var rawBuffer = MemoryMarshal.Cast<Foo, byte>(buffer);
var bytesRead = stream.Read(rawBuffer);
lastBuffer = bytesRead < rawBuffer.Length;
currentItem = 0;
loadedItems = bytesRead / ItemSize;
return loadedItems != 0;
}
public void Reset() => throw new NotImplementedException();
public void Dispose()
{
// nothing to do
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how to access form controls from another class
How can I use every control in my form from another Class?
So as an example I can use txtName.text in class to edit it and do that for every control in my form
A:
If my understanding is correct mean.You want to control your form control object from another class
1.You can pass the form object to another class via constructor(Form this)
2.Use MVP pattern .Buy creating control as properties in mainform and create interface and for that form and pass the same interface to another class where you need to control the same
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find the number of strings with even and odd number of zeroes?
Any hints please for this question ? Im stuck.How to find the number of strings with even and odd number of zeroes ?
A:
Hint Here is how you count the number of strings with $k$ zeroes:
There are $\binom{n}{k}$ possible positions for the zeroes. For each of the remaining $n-k$ positions you have 3 choices of digits.
So the number of strings with exactly $k$ zeroes is
$$
\binom{n}{k}3^{n-k}
$$
Hint 2
Prove that
$$
E_n-O_n =(3+(-1))^n \\
E_n+O_n=(3+1)^n
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting a Number to Alphanumeric in VBA
I am using the below code as a portion of a much larger code to convert a number to its alphanumeric equal i.e 1=A, 2=B, etc. While this does work it is crazy long code and I am sure there is a better way to do this and was hoping you guys could assist.
Sub Convert()
Time = Range("A1")
If Time = 1 Then
E = "A"
Else
If Time = 2 Then
E = "B"
Else
If Time = 3 Then
E = "C"
Else
If Time = 4 Then
E = "D"
Else
If Time = 5 Then
E = "E"
Else
If Time = 6 Then
E = "F"
Else
If Time = 7 Then
E = "G"
Else
If Time = 8 Then
E = "H"
Else
If Time = 9 Then
E = "I"
Else
If Time = 10 Then
E = "J"
Else
If Time = 11 Then
E = "K"
Else
If Time = 12 Then
E = "L"
Else
If Time = 13 Then
E = "M"
Else
If Time = 14 Then
E = "N"
Else
If Time = 15 Then
E = "O"
Else
If Time = 16 Then
E = "P"
Else
If Time = 17 Then
E = "Q"
Else
If Time = 18 Then
E = "R"
Else
If Time = 19 Then
E = "S"
Else
If Time = 20 Then
E = "T"
Else
If Time = 21 Then
E = "U"
Else
If Time = 22 Then
E = "V"
Else
If Time = 23 Then
E = "W"
Else
If Time = 24 Then
E = "X"
Else
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
MsgBox E
End Sub
A:
Easier and more solid way is to use what Excel already offers, which means "every letter is associated to a number in the ranges":
Public Function numberToLetter(ByVal myNumber As Integer) As String
numberToLetter = Split(Cells(1, myNumber).Address, "$")(1)
End Function
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: fill column based on first charakter of another columns content
I have a pandas dataframe looking like this:
+-----+------+
| No | type |
+-----+------+
| 123 | C01 |
| 123 | C02 |
| 123 | T01 |
| 345 | C01 |
| 345 | H12 |
| 345 | H22 |
+-----+------+
and a numpy array like this:
arr = [Car, Tree, House]
Desired output:
+-----+------+----------+
| No | type | category |
+-----+------+----------+
| 123 | C01 | Car |
| 123 | C02 | Car |
| 123 | T01 | Tree |
| 345 | C01 | Car |
| 345 | H12 | House |
| 345 | H22 | House |
+-----+------+----------+
So I would like to add a column containing the element of the arr, where the first charakter matches to the first charakter of column type.
There is ony one element within the array for each first charakter.
What is the best way to achieve this? I could do this manually for each first charakter but I would like to do this within one run e.g. with apply-function.
Thank you,
MaMo
A:
Full example:
import pandas as pd
data = '''\
No type
123 C01
123 C02
123 T01
345 C01
345 H12
345 H22'''
df = pd.read_csv(pd.compat.StringIO(data),sep='\s+')
arr = ['Car', 'Tree', 'House']
d = {x[0]:x for x in arr} # Create a map
df['category'] = df['type'].str[0].map(d) # Apply map to str[0]
Results in:
No type category
0 123 C01 Car
1 123 C02 Car
2 123 T01 Tree
3 345 C01 Car
4 345 H12 House
5 345 H22 House
Explanation:
Create dictionary by first values of arr
Select first value of type column by str[0] and map by dict
| {
"pile_set_name": "StackExchange"
} |
Q:
If you Consolidate the Satipatthana Instruction from the Tripitaka what would the additions and variation in Comparison to Maha Satipatthana Sutta
If you consolidate the instructions from the Tripitaka and other sources what would be the variations and additions to the instructions given in the Maha Satipatthana Sutta?
A:
Here are four comparison tables that expose the similarities and discrepancies in satipaṭṭhāna discourses from the Pāḷi Nikāyas and Chinese Āgamas:
From Mindfulness in Early Buddhism by Tse-Fu Kuan, p.166-169. Click the images to enlarge.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Regular Expressions to replace a select instance of a character
First and foremost, this is not a homework/school question. This is something I needed for a personal project and was able to generalize the problem using simple characters as follows:
Create a regular expression which can be used in the java string replaceAll function for an input string aaabaabaa (or similar) and converts each a to A, UNLESS it is preceded by a b. So the expected output is AAAbaAbaA. I've been trying this for at least 2 hours now... The best I could come up with was:
replaceAll("^a|([^b])a", "$1A");
This fails on aaa, where the return value is AaA
I'm trying to say "Any 'a' without a 'b' before it should be an A. Any ideas for a RegEx novice? Thanks very much!
A:
Try using a negative lookbehind:
str.replaceAll("(?<!b)a", "A");
This will match any a not immediately preceded by a b.
| {
"pile_set_name": "StackExchange"
} |
Q:
Behavior when dereferencing the .end() of a vector of strings
I'm wondering if it's "safe" to set a string equal to whatever is returned by dereferencing the off-the-end iterator of a vector of strings. When I run the program
#include <vector>
#include <string>
int main()
{
std::vector<std::string> myVec;
std::cout << *myVec.end();
return 0;
}
I get the following error.
/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/debug/safe_iterator.h:181:
error: attempt to dereference a past-the-end iterator.
Objects involved in the operation:
iterator "this" @ 0x0xffdb6088 {
type = N11__gnu_debug14_Safe_iteratorIN9__gnu_cxx17__normal_iteratorIPSsN10__gnu_norm6vectorISsSaISsEEEEEN15__gnu_debug_def6vectorISsS6_EEEE (mutable iterator);
state = past-the-end;
references sequence with type `N15__gnu_debug_def6vectorISsSaISsEEE' @ 0x0xffdb6088
}
Disallowed system call: SYS_kill
You can view it at http://codepad.org/fJA2yM30
The reason I'm wondering about all this is because I have a snippet in my code that is like
std::vector<const std::string>::iterator iter(substrings.begin()), offend(substrings.end());
while (true)
{
this_string = *iter;
if (_programParams.count(this_string) > 0)
{
this_string = *++iter;
and I want to make sure something weird doesn't happen if ++iter is equal to offend.
A:
You said:
I'm wondering if it's "safe" to set a string equal to whatever is returned by dereferencing the off-the-end iterator of a vector of strings
No, it is not safe. From http://en.cppreference.com/w/cpp/container/vector/end
Returns an iterator to the element following the last element of the container.
This element acts as a placeholder; attempting to access it results in undefined behavior.
| {
"pile_set_name": "StackExchange"
} |
Q:
Notify thread when data is added in queue
I have one thread which is adding data in the queue, now I want that other thread should get notified when the data is added so that it can start processing data from queue.
one option is thread will poll the queue continuously to see if count is more than zero but I think this is not good way, any other suggestion will be greatly appreciated
Any suggestion how I can achieve this, I am using .net framework 3.5.
and what if i have two thread one is doing q.Enqueue(data) and other is doing q.dequeue(), in this case do i need to manage the lock..?
A:
You can use ManualResetEvent to notify a thread.
ManualResetEvent e = new ManualResetEvent(false);
After each q.enqueue(); do e.Set() and in the processing thread, you wait for items with e.WaitOne().
If you do processing inside a loop, you should do e.Reset() right after e.WaitOne().
| {
"pile_set_name": "StackExchange"
} |
Q:
Add Calendar list to WikiPage using Powershell
I have inserted a Calendar list to a page(SitePages/Home.aspx) using a powershell script, But I want to insert it in to a specific location as shown in image. When I insert the calendar list it insert it to the Bottom of the page by default even If I specify zone as right. The SitePages/Home.aspx has only "Bottom" zone(verified using SPD) and I assume that's the reason its inserting in to Bottom Zone by default. Even if I try to edit the Page it doesn't display the Bottom Zone with calendar.
How do I Specify the Zone location and Index?
$wpManager.AddWebPart($wpView,"Right",0)
Any suggestions appreciated...
A:
Found the solution. I have blogged about it here. http://kannabirank.wordpress.com/2012/06/23/sharepoint-power-shell-script-to-add-webpart-to-wiki-page/
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any native php function that adds 2 array's value together?
Is there any native php function that adds 2 array's value together ?
Like lets say:
$array1= array(1 => 10, 2 =>20, 3=>3);
$array2= array(1 => 11, 2 =>22, 3=>33);
$somearray = array1 + array2;
and the output of that will be:
array(1 => 21, 2 => 42, 3=>36);
Not looking for a function or a way to do this with a foreach
Just asking if there's a native php function that does that, i am looking on array functions at: http://www.php.net/manual/en/ref.array.php and either i am missing it or it doesn't exist.
Thanks
A:
array_map(function($x, $y) { return $x + $y }, $array1, $array2) should do, if you like that kind of thing.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP class private property and method
Noticed something about PHP's classes and I don't know if it's a bug or why it works, this is the code:
<?php
class A {
private $prop = 'value';
public function fun()
{
$obj = new A;
$obj->echoProp();
}
private function echoProp()
{
echo 'Prop has value: '.$this->prop;
}
}
$obj = new A;
$obj->fun();
And the result isn't an error as I was expecting since I'm calling a private method (tested on PHP 5.3.10-1ubuntu3.7 with Suhosin-Patch). The result is "Prop has value: value"
A:
At the php documentation http://www.php.net/manual/en/language.oop5.visibility.php#language.oop5.visibility-other-objects it says:
Visibility from other objects
Objects of the same type will have access to each others private and
protected members even though they are not the same instances. This is
because the implementation specific details are already known when
inside those objects.
So this isn't a bug but a wanted feature of php.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove $ C = \{ x \mid x < a \} \cup \{a\} \cup \underline{ab} \cup \{b \} \cup \{ x \mid b < x \}. $
If $\underline{ab}$ is a region in $C$, then:
$
C = \{ x \mid x < a \} \cup \{a\} \cup \underline{ab} \cup \{b \} \cup \{ x \mid b < x \}.
$
Where C is a continuum that is nonempty, has no first or last point, and is ordered $<$.
Regions can be defined as all the points between $a$ and $b$ (such that $a<b$) denoted by $\underline{ab}$.
This seems a bit obvious to me, but perhaps the proof is more clear. I thought of trying to prove each possible point would end up being some point on $C$ and that $\underline{ab}$ is also a continuum, but I'm not sure this is the way to go.
A:
Let $X$ be $\{x|x<a\}\cup \dots \cup \{x|b<x\}$.
Clearly $X \subset C$.
Let's take a point $y\in C$. Then either $y<a, y = a, y> a$.
If $y<a$, then $y \in X$.
If $y = a$ then $y \in X$.
If $y > a$, then either $y<b, y = b, b<y$.
If $y <b $ then $a<y<b$ and so $y \in \underline{ab}$, so $y \in X$.
If $y = b$ then $y \in X$.
If $y > b$, then $y \in X$.
So no matter what point you take from C, it is in X. Therefore $C \subset X$, $C=X$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Register Navigation Service to Frame Element and NOT the page - WinRt Prism 2.0
Can anyone help.
We are working on an app which has a consistent header and footer and therefore ideally we'll use one viewmodel for the "home page" but we want the header and footer to remain.
Before we switched to starting using Prism, this was easy enough to navigate as we could control that in the Pages event and set the page.contentFrame.Navigate method to go where we wanted.
Now we're using the MVVM structure (which is superb and wish I'd done it ages ago) the NavigationService class only navigates the entire page (the VisualStateAware page).
How can I set this up so that when calling the Navigate method on the interface in the viewmodel that only the main content frame is ever navigated? or is there a better approach to this?
Any help would be greatly appreciated.
thank you
A:
The question title seems to, pre-empt the details of the question slightly as a solution. But to share a common view model and visual parts across all pages, within a frame, using the navigation service to navigate between pages here is an overview..
Create a shared ViewModel, say "HeaderViewModel" of type say IHeaderViewModel to be shared between the different pages' view models. Inject this into the constructor of each page's ViewModel.
Then expose this as a property of each page's ViewModel. This property could also be called HeaderViewModel too. You can then reference the properties of this common HeaderViewModel in the bindings in the View, using binding '.' notation.
If you are using Unity with Prism, you can create this shared instance HeaderViewModel in the OnInitialize override of the App.
Create a shared part for each Page/View as a UserControl, which can be positioned on each page in the same place. This enables you to bind to the same properties on your HeaderViewModel.
| {
"pile_set_name": "StackExchange"
} |
Q:
Tsung. contents_from_file attribute with variable value
I've got a problem using tsung:
I've got several files in one dir wich I have to send to the server. I
create file with list of this files (fullpath) and add an option to
tsung config:
<option name="file_server" id="xml_files" value="/home/ubuntu/.tsung/files"></option>
My goal is to pick a random filepath from this file and send to the
server. To do so I wrote this part of config:
<setdynvars sourcetype="file" fileid="xml_files" delimiter=";"
order="random">
<var name="file_name" />
</setdynvars>
<request subst="true">
<http url="/" version="1.1" method="POST"
contents_from_file="%%_file_name%%"></http>
</request>
But this do not work. When I set attr contents_from_file as constant
everything works fine.
Is there any way to do this with variable?
A:
I got the similar thing working, i am using tsung 1.5.0. you may want to try:
<request subst="true">
<http url="/" version="1.1" method="POST"
contents="%%readafile:readrnd%%"></http>
</request>
where readfafile is your own module that exports readrnd function.
readrnd should return contents of random file.
Note : filename would be a binary when read from file source, you may have to serialize.
instead of:
<request subst="true">
<http url="/" version="1.1" method="POST"
contents_from_file="%%_file_name%%"></http>
</request>
| {
"pile_set_name": "StackExchange"
} |
Q:
Sencha Cmd - Unknown command: include
Hi everybody,
The problem is sencha cmd give this error : Unknown command include
I working in Ext Js 4.2
ruby -v
-- ruby 2.0.0p353 (2013-11-22) [i386-mingw32]
compass -v -> Compass 0.12.5 (Alnilam)
sencha cmd version : 4.0.4.84
What is your solution ?
Thanks everyboy
command line code :
cd D:\Proje\SenchaExtJs\TaskList
sencha app refresh
Error output here :
> Sencha Cmd v4.0.4.84 [INF] [INF] init-plugin: [INF] [INF]
> cmd-root-plugin.init-properties: [INF] [INF] init-properties: [INF]
> [INF] init-sencha-command: [INF] [INF] init: [INF] [INF]
> app-refresh: [INF] [echo] Refreshing app at
> D:\Proje\SenchaExtJs\TaskList [INF] [INF] app-refresh-impl: [INF]
> [INF] -before-init-local: [INF] [INF] -init-local: [INF] [INF]
> -after-init-local: [INF] [INF] init-local: [INF] [INF] find-cmd-in-path: [INF] [INF] find-cmd-in-environment: [INF] [INF]
> find-cmd-in-shell: [INF] [INF] init-cmd: [INF] [echo] Using
> Sencha Cmd from C:\Users\SARGIN.A-SARGIN\bin\Sencha\Cmd\4.0.4.84 for
> D:\Proje\SenchaExtJs\TaskList\build.xml [INF] [INF] -before-init:
> [INF] [INF] -init: [INF] Initializing Sencha Cmd ant environment
> [INF] Adding antlib taskdef for
> com/sencha/command/compass/ant/antlib.xml [INF] [INF] -after-init:
> [INF] [INF] -before-init-defaults: [INF] [INF] -init-defaults: [INF]
> [INF] -after-init-defaults: [INF] [INF] -init-compiler: [INF] [INF]
> init: [INF] [INF] refresh: [INF] [INF] -before-refresh: [INF] [INF]
> -init: [INF] [INF] -init-compiler: [INF] [INF] -detect-app-build-properties: [INF] Loading app json manifest... [INF] Loading classpath entry D:\Proje\SenchaExtJs\TaskList\ext\src [INF]
> Loading classpath entry
> D:\Proje\SenchaExtJs\TaskList\ext\packages\ext-theme-base\src [INF]
> Loading classpath entry
> D:\Proje\SenchaExtJs\TaskList\ext\packages\ext-theme-base\overrides
> [INF] Loading classpath entry
> D:\Proje\SenchaExtJs\TaskList\ext\packages\ext-theme-neutral\src [INF]
> Loading classpath entry
> D:\Proje\SenchaExtJs\TaskList\ext\packages\ext-theme-neutral\overrides
> [INF] Loading classpath entry
> D:\Proje\SenchaExtJs\TaskList\ext\packages\ext-theme-neptune\src [INF]
> Loading classpath entry
> D:\Proje\SenchaExtJs\TaskList\ext\packages\ext-theme-neptune\overrides
> [INF] Loading classpath entry D:\Proje\SenchaExtJs\TaskList\app [INF]
> Loading classpath entry D:\Proje\SenchaExtJs\TaskList\app.js [INF]
> Loading classpath entry
> D:\Proje\SenchaExtJs\TaskList\build\temp\production\Exp\sencha-compiler\app
> [INF] Loading classpath entry
> D:\Proje\SenchaExtJs\TaskList\build\temp\production\Exp\sencha-compiler\app
> [WRN] unable to locate files for external reference :
> D:\Proje\SenchaExtJs\TaskList\ext\ext-theme-neptune.js [WRN] scope is
> D:\Proje\SenchaExtJs\TaskList\build\temp\production\Exp\sencha-compiler\app
> [INF] Concatenating output to file
> D:\Proje\SenchaExtJs\TaskList/build/temp/production/Exp/sencha-compiler/cmd-packages.js
> [INF] Adding external reference : @full-page => @overrides [INF]
> Loading classpath entry
> D:\Proje\SenchaExtJs\TaskList\build\temp\production\Exp\sencha-compiler\cmd-packages.js
> [INF] Adding external reference : Ext.util.Observable =>
> D:\Proje\SenchaExtJs\TaskList/build/temp/production/Exp/sencha-compiler/cmd-packages.js
> [INF] [INF] -refresh-app: [INF] Appending concatenated output to file
> D:\Proje\SenchaExtJs\TaskList/bootstrap.js [ERR] [ERR] BUILD FAILED
> [ERR] com.sencha.exceptions.ExArg: Unknown command: "include" [ERR]
> [ERR] Total time: 5 seconds [ERR] The following error occurred while
> executing this line:
> C:\Users\SARGIN.A-SARGIN\bin\Sencha\Cmd\4.0.4.84\plugins\ext\4.2\plugin.xml:386:
> The following error occurred while executing this line:
> D:\Proje\SenchaExtJs\TaskList\.sencha\app\build-impl.xml:367: The
> following error occurred while executing this line:
> D:\Proje\SenchaExtJs\TaskList\.sencha\app\refresh-impl.xml:100: The
> following error occurred while executing this line:
> D:\Proje\SenchaExtJs\TaskList\.sencha\app\refresh-impl.xml:44:
> com.sencha.exceptions.ExArg: Unknown command: "include"
A:
the problem is OS Language.
I use Windows 8.1 Turkish. I installed United States English and change my operating system language US ENG after restart the computer.
the error going to hell :)
reference page :
http://www.sencha.com/forum/showthread.php?261919-Sencha-Cmd-3.1.1-Error-while-building-new-theme/page2
| {
"pile_set_name": "StackExchange"
} |
Q:
Literal Meta Stack Overflow Questions
I saw this question pop up in my feed, and it made me think, how many questions on Stack Overflow pertain to the actual stack overflow errors?
A:
2,540 questions.
At least that's the number of questions tagged with the stack-overflow tag. But as you can see from your example, not all questions about stack overflow errors have that tag.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there some wrapper for running GUI applications under a fake screen resolution?
Some applications behave differently at a different screen resolution. Is there any way to get the system to report a different, user-specified, resolution to a GUI application when starting it?
By behave differently I mean for example their unresizable window is smaller (not necessarily physically, for obvious reasons, but fewer pixels) if I first switched the monitor to a lower resolution.
Something like:
~$ sudolution 800x600 unresizableapp
Or is there any method to force-resize unresizable windows?
A:
I doubt a fake resolution can be provided somehow. The resolution can be received from X extension RANDR, e.g. with the tool xrandr.
What you can do instead:
For resolutions smaller than current screen:
Use a nested X server like Xephyr with a custom resolution:
Xephyr :5 -retro -screen 400x300x24
Run desired application with DISPLAY=:5 application. It makes sense to run a window manager on :5, too. (400x300 is the resolution, x24 is color depth.)
For resolution bigger than current screen:
Change current screen to have a virtual bigger display:
xrandr --output VGA-1 --panning 3000x2000
Replace example VGA-1 with an output name given in output of xrandr. To turn panning of, run with --panning 0x0.
| {
"pile_set_name": "StackExchange"
} |
Q:
getting error to deploy era file in jboss
i am want to deploy the ear file that contains the 4 project 3 war and one .jar the jar project is common for war projects in this the jar project is using the spring and hibernate. and the war project is using the struts when deploy on the jboss 7 getting these error
15:11:51,929 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-6) MSC00001: Failed to start service jboss.persistenceunit."EyewatchEar.ear#EW": org.jboss.msc.service.StartException in service jboss.persistenceunit."EyewatchEar.ear#EW": Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1767) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_45]
at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_45]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: EW] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:889)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:73)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.createContainerEntityManagerFactory(PersistenceUnitServiceImpl.java:162)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.start(PersistenceUnitServiceImpl.java:85)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
... 3 more
Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.collection.OneToManyPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:248)
at org.hibernate.persister.internal.PersisterFactoryImpl.createCollectionPersister(PersisterFactoryImpl.java:196)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:375)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1737)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:84)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:904)
... 9 more
Caused by: org.hibernate.HibernateException: Unable to parse order-by fragment
at org.hibernate.sql.ordering.antlr.OrderByFragmentTranslator.render(OrderByFragmentTranslator.java:66)
at org.hibernate.sql.Template.renderOrderByStringTemplate(Template.java:696)
at org.hibernate.persister.collection.AbstractCollectionPersister.<init>(AbstractCollectionPersister.java:558)
at org.hibernate.persister.collection.OneToManyPersister.<init>(OneToManyPersister.java:85)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [rt.jar:1.7.0_45]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) [rt.jar:1.7.0_45]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) [rt.jar:1.7.0_45]
at java.lang.reflect.Constructor.newInstance(Constructor.java:526) [rt.jar:1.7.0_45]
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:226)
... 14 more
Caused by: java.lang.ClassCastException: antlr.CommonToken cannot be cast to antlr.Token
at antlr.CharScanner.makeToken(CharScanner.java:173)
at org.hibernate.sql.ordering.antlr.GeneratedOrderByLexer.mIDENT(GeneratedOrderByLexer.java:238)
at org.hibernate.sql.ordering.antlr.GeneratedOrderByLexer.nextToken(GeneratedOrderByLexer.java:138)
at antlr.TokenBuffer.fill(TokenBuffer.java:69)
at antlr.TokenBuffer.LA(TokenBuffer.java:80)
at antlr.LLkParser.LA(LLkParser.java:52)
at org.hibernate.sql.ordering.antlr.GeneratedOrderByFragmentParser.expression(GeneratedOrderByFragmentParser.java:504)
at org.hibernate.sql.ordering.antlr.GeneratedOrderByFragmentParser.sortKey(GeneratedOrderByFragmentParser.java:325)
at org.hibernate.sql.ordering.antlr.GeneratedOrderByFragmentParser.sortSpecification(GeneratedOrderByFragmentParser.java:241)
at org.hibernate.sql.ordering.antlr.GeneratedOrderByFragmentParser.orderByFragment(GeneratedOrderByFragmentParser.java:190)
at org.hibernate.sql.ordering.antlr.OrderByFragmentTranslator.render(OrderByFragmentTranslator.java:60)
... 22 more
i am using JTA but not able to find what is going wrong, so if some one have the solution please help.
thanks in Adv.
A:
You probably found a solution but for future reference, here's a working solution using Maven :
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-version}</version>
<exclusions>
<exclusion>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
</exclusion>
</exclusions>
</dependency>
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL Update Multiple Columns Issue
This seems to be a really simple query, but somehow I keep getting errors...
Basically, I just got a bunch of information from a user, and now I'm going to update their record in the users table in one query:
UPDATE users SET timezone = 'America/New_York', SET updates = 'NO', SET verified = 'YES' WHERE id = '1'
However, after running that, I get the following error:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET updates = 'NO', SET verified = 'YES' WHERE id = '1'' at line 1".
Any help is much appreciated.
A:
UPDATE users SET timezone = 'America/New_York', updates = 'NO', verified = 'YES' WHERE id = '1'
A:
Your update syntax is wrong, you have to write syntax SET just once.
UPDATE users SET col1= value1, col2= value2, col3= value3 WHERE condition;
More information about update
UPDATE MANUAL
| {
"pile_set_name": "StackExchange"
} |
Q:
I can file.addToFolder but cant file.removeFromFolder
I have a script that reads files from a folder and catalogs the contents to a spreadsheet. To avoid duplicates I want to move the files to a different folder (file.addToFolder(newFolder)) which works, however when I try to file.removeFromFolder(formerFolder) I get "cannot find method" which would suggest I am not giving it the right class of object even though removeFromFolder is listed as a member of the File class.
function moveFileToFolder(fileId, targetFolderId,formerFolderId) {
var targetFolder = DocsList.getFolderById(targetFolderId);
var file = DocsList.getFileById(fileId);
file.addToFolder(targetFolder);
file.removeFromFolder(formerFolderId);
};
What am I doing wrong?
A:
You should get the formerFolder like you get the targetfolder and pass it to the method instead of the formerFolderId.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sharepoint-hosted app: Access site columns belonging to host site
I have a sharepoint-hosted app containing a custom list. On the host site collection where I am deploying this app, there are several custom site columns.
In my app, I want to access these site columns and include as columns in my custom list.
Is this possible?
A:
Yes, it is possible. I created a site column called Test in the Host Web and then I used this code to add it to a list in the App Web.
$(document).ready(function () {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var fields = web.get_availableFields();
var testField = fields.getByTitle("Test");
var lci = new SP.ListCreationInformation();
lci.set_title("Test");
lci.set_templateType(SP.ListTemplateType.genericList);
var list = web.get_lists().add(lci);
list.get_fields().add(testField);
context.executeQueryAsync(success, fail);
function success() {
var message = jQuery("#message");
message.text("List added");
}
function fail(sender, args) {
alert('Error:' + args.get_message());
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Conversion to Binary - long long and NSUInteger
We need to convert the below datatypes to binary:
Long long to Binary
NSUInteger to Binary
Any help on this would be highly appreciated.
The code i have is :
As per the above link, we have
- (NSString *) longlongToBinary:(long long) val {
long long num = val;
NSString *res = [NSString string];
for (long long i=63; i>=0; i--)
{
long long div = 1l<<i;
if ((num&div)==div) res = [res stringByAppendingString:@"1"];
else res = [res stringByAppendingString:@"0"];
}
return res;
}
If the val is 20, then the output i am getting is:
0000000000000000000000000001010000000000000000000000000000010100
and this is wrong when i see it in the online convertors.
A:
long is only 32 bits. Since the method is named longlongToBinary, change all of the long variables to long long. That will give you the 64 bits you are using.
Now that you have changed most variables to long long, change the loop variable i back to an int and change the 1l constant to 1ll.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change button color from other thread
In my c# program I create a bunch of buttons in the main (UI) thread. Then I start a timer that runs a method Timeline(). Now I want the appearance of the buttons to change when the Timeline() method runs. But I'm not allowed to access the objects because they are owned by the main thread. How do I solve this?
Error: The calling thread cannot access this object because a different thread owns it.
I have found Dispatcher disp = Dispatcher.CurrentDispatcher; which has an Invoke() method but I'm not sure if that is the right way, and I couldn't get it to work.
Here is part of my code:
private static SurfaceButton[,] buttons = new SurfaceButton[dimensionBeats, dimensionsNotes];
public SurfaceWindow1()
{
try
{
InitializeComponent();
}
catch (Exception ex)
{
}
LoadAudioContent();
// Add handlers for Application activation events
AddActivationHandlers();
InitializeButtons();
try
{
t = new Timer(Timeline, null, 1, dimensionBeats*500);
}
catch (Exception e)
{
}
}
private void InitializeButtons()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 6; j++)
{
SurfaceButton btn = new SurfaceButton();
//btn.Content = files[j].Substring(0,1);
btn.Name = "a" +i + j;
btn.Width = 120;
btn.Height = 120;
btn.ContactEnter+=StartSound;
btn.ContactLeave+=StopSound;
btn.Opacity = 0.01;
btn.ClickMode = ClickMode.Release;
buttons[i,j] = btn;
// add the newly generated button to the correct column (left to right one panel per column)
switch (i)
{
case 0:
rowPanel0.Children.Add(btn);
break;
case 1:
rowPanel1.Children.Add(btn);
break;
case 2:
rowPanel2.Children.Add(btn);
break;
case 3:
rowPanel3.Children.Add(btn);
break;
case 4:
rowPanel4.Children.Add(btn);
break;
case 5:
rowPanel5.Children.Add(btn);
break;
case 6:
rowPanel6.Children.Add(btn);
break;
case 7:
rowPanel7.Children.Add(btn);
break;
}
}
}
}
private void Timeline(Object state)
{
for (int i = 0; i < pressed.GetLength(0); i++)
{
sendRequest(url, postMethod, tabelId, buttsToString(butts));
for (int j = 0; j < pressed.GetLength(1); j++)
{
if (pressed[i,j])
{
buttons[i, j].Background = Brushes.Red;
}
}
Thread.Sleep(500);
for (int j = 0; j < pressed.GetLength(1); j++)
{
buttons[i, j].Background = Brushes.White;
}
}
A:
You need to use Invoke/BeginInvoke to forward updates to the GUI thread:
int i1 = i; // local copies to avoid closure bugs
int j1 = j;
buttons[i1, j1].Dispatcher.BeginInvoke(
((Action)(() => buttons[i1, j1].Background = Brushes.Red)));
| {
"pile_set_name": "StackExchange"
} |
Q:
AWS Cognito for Angular website authentication.. Attributes did not conform to the schema: email: The attribute is require
I am trying to register user with AWS Cognito by passing email and password, But i receive the below error
{code: "InvalidParameterException", name: "InvalidParameterException", message: "Attributes did not conform to the schema: email: The attribute is required↵"}
code: "InvalidParameterException"
message: "Attributes did not conform to the schema: email: The attribute is required↵"
name: "InvalidParameterException"
proto: Object
Code for sign up:
register(email, password) {
const attributeList = [];
return Observable.create(observer => {
userPool.signUp(email, password, attributeList, null, (err, result) => {
if (err) {
console.log("signUp error", err);
observer.error(err);
}
this.cognitoUser = result.user;
console.log("signUp success", result);
observer.next(result);
observer.complete();
});
});
}
Please help me
A:
Issue was resolved by adding the attributes as below.
This is my method for registration this works fine with Cognito in angular 8
register(email, password) {
const attributeList = [];
attributes: {
email
};
return Observable.create(observer => {
userPool.signUp(email, password, attributeList, null, (err, result) => {
if (err) {
console.log("signUp error", err);
observer.error(err);
}
this.cognitoUser = result.user;
console.log("signUp success", result);
observer.next(result);
observer.complete();
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Hosting WCF Service that accesses SQL database onto IIS
I have a WCF service that accesses a SQL database to fetch data . I would like to deploy this service onto IIS . However , when i do this , my service is not able to access the database .
This is how my service accesses the DB
SqlConnection thisConnection = new SqlConnection(@"user id=SAIESH\Saiesh Natarajan;" +
"password=;server=SAIESH\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"database=master; " +
"connection timeout=30");
I need to know what i should do to be able to access this DB from my WCF service hosted on IIS
A:
Under IIS your service usually will be executed under NETWORK SERVICE account. In your connection string you use trusted_connection=yes. So, you need grant access to NETWORK SERVICE account. But better solution is to change authentication scheme and use USERNAME/PASSWORD to connect to SQL server.
Actually here is similar question WCF Impersonation and SQL trusted connections?
| {
"pile_set_name": "StackExchange"
} |
Q:
Is logging in as a shared user a bad habit?
I've worked in organizations where instead of creating a new Ubuntu user per person that wants to log into a machine, the sysadmins simply add the ssh key of each user to .ssh/authorized_keys, and everyone sshs to the machine as (e.g.) ubuntu@host or ec2-user@host. (Incidentally, I've also seen this practiced on shared Mac minis in a lab setting.) Is this accepted practice, or an anti-pattern?
The hosts in question are mainly used for testing, but there are also actions taken that typically require per-user configuration and are tracked as being done by a specific user, such as creating and pushing git commits, which are currently done using a generic git user.
A:
Yes it is a bad habit. It relies on the basic assumption that nobody malicious is (or will be) around and that nobody makes mistakes. Having a shared account makes it trivial for things to happen without accountability and without any limit - a user breaking something breaks it for everyone.
If the reason for this uid-sharing scheme is simply to reduce the administrative cost of creating new accounts and sharing configuration, then perhaps the administrators should invest some time in an automation system like Ansible, Chef, Puppet or Salt that makes stuff like creating user accounts on multiple machines extremely simple.
A:
To start with this doesn't shock me, and I work in an extremely secured environment. Everyone has his own user and machine and ssh key, and for working on a server we ssh in, as root or as another user, through a logging relay if necessary. Everything we do is logged as having been done by the owner of the ssh key, so accountability is OK.
What would the alternative be? Lots of things must be done as a certain user, not to mention root. Sudo? That's OK for certain very restricted tasks, but not for sysadminning the machine.
However I'm not sure about your last paragraph, do you mean that someone could push a git commit a a generic user? That would break accountability, and breaking accountability is bad. We do git from the machine where we are logged in and we authenticate to git with our ssh key...
Authentication, authorization, and accounting (AAA) is the classic expression: you are authenticated with your ssh key, you are authorized to do anything the generic user can do because your key is in the authorized_keys, and you need accounting so that what you do can be reviewed after the fact.
A:
It clearly depends on the use case of the system. If it is system for testing from time to time it is fine for me. We have also such systems. If the company does not have any kind of identity management (LDAP, IPA), then creating new user without any remote control on random system is quite burden.
But for every-day work when someones mistake makes whole company unable to operate is not a good idea.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex for OSX resolution
I'm using this command to get the screen resolution:
system_profiler SPDisplaysDataType | grep Resolution
This returns your screen resolution of the form:
Resolution: 1366 x 768
The problem that I'm being faced with, is finding a way to get the values: 1366 and 768 separately by possibly using a regex in Ruby. The reason why I need to get these two values is so that I can use them here:
image = Image.new(x, y)
where x and y would be 1366 and 768 respectively. My question is how can I those two values by themselves?
A:
matches = str.match(/(\d+) x (\d+)/)
hor = matches[1]
ver = matches[2]
| {
"pile_set_name": "StackExchange"
} |
Q:
Backing up MongoDB mup deploy
I have successfully deployed my meteor application using mup deploy. As stated in documentation to access database we need to run this command:
docker exec -it mongodb mongo <appName>
How can I use mongodump command with this setup? I have tried running
docker exec -it mongodb mongodump --db appName --archive=baza.gz --gzip
Command runs successfully, but I can not find baza.gz archive
A:
As I found dump gets saved in docker container. To access backup from local filesystem we need to copy it from docker container.
To dump:
docker exec -it mongodb mongodump --db appName --archive=/root/baza.gz --gzip
To copy from docker container to local filesystem:
docker cp mongodb:/root/backup.gz /home/local_user
| {
"pile_set_name": "StackExchange"
} |
Q:
Weierstrass Approximation Theorem for continuous functions on open interval
I am studying for my introductory real analysis final exam, and here is a problem I am somewhat stuck on. It is Question 2, in page 3 of the following past exam (no answer key unfortunately!):
http://www.math.ubc.ca/Ugrad/pastExams/Math_321_April_2006.pdf
Give an example of each of the following, together with a brief
explanation of your example. If an example does not exist, explain why
not.
(c) A continuous function $f : (−1,1) → \mathbb{R}$ that cannot be uniformly approximated by a polynomial.
By Weierstrass Approximation Theorem, every continuous real-valued function on closed interval can be uniformly approximated by a sequence of polynomials. Since in this question the domain of the function is an open interval $(-1, 1)$, I have a feeling that such example must exist.
My attempts: The proof of Weierstrass approximation theory uses the fact that a continuous function a compact set (a closed interval by Heine-Borel Theorem) achieves a maximum, so we can guess that the example we are looking after will not achieve a maximum on $(-1, 1)$. Such example of continuous function is
$$ f(x)=\frac{1}{x+1} $$
So now my question: is it true $f$ cannot be uniformly approximated by a sequence of polynomials? And if so, how do proceed to prove such a statement?
Thanks!
A:
Based on Alex Ravsky's hint, I have found the solution. I will type it up for the sake of reference.
We claim that the function
$$ f(x)=\frac{1}{x+1} $$
is a continuous function on $(-1, 1)$ that cannot be approximated by a polynomial. Assume not. Then, for $\epsilon=1$ in the definition of uniform convergence, there exists a polynomial $p(x)$ such that
$$
|f(x)-p(x)|\le 1
$$
for $all$ $x\in (-1, 1)$. Since the polynomial $p(x)$ is bounded on $(-1, 1)$, it follows that, there exists a constant $M$ such that $|p(x)|\le M$ for all $x\in (-1, 1)$. But then,
$$
|f(x)|\le |p(x)| + |f(x)-p(x)| \le M+1
$$
for all $x\in (-1,1)$ which contradicts the fact that $f(x)$ is unbounded on $(-1, 1)$.
A:
Your feeling seems to be right. :-D Hint: each polynomial should be bounded on $(0,1)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Embedding arbitrary objects in Clojure code
I want to embed a Java object (in this case a BufferedImage) in Clojure code that can be evald later.
Creating the code works fine:
(defn f [image]
`(.getRGB ~image 0 0))
=> #'user/f
(f some-buffered-image)
=> (.getRGB #<BufferedImage BufferedImage@5527f4f9: type = 2 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=ff000000 IntegerInterleavedRaster: width = 256 height = 256 #Bands = 4 xOff = 0 yOff = 0 dataOffset[0] 0> 0 0)
However you get an exception when trying to eval it:
(eval (f some-buffered-image))
=> CompilerException java.lang.RuntimeException: Can't embed object in code, maybe print-dup not defined: BufferedImage@612dcb8c: type = 2 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=ff000000 IntegerInterleavedRaster: width = 256 height = 256 #Bands = 4 xOff = 0 yOff = 0 dataOffset[0] 0, compiling:(NO_SOURCE_PATH:1)
Is there any way to make something like this work?
EDIT:
The reason I am trying to do this is that I want to be able to generate code that takes samples from an image. The image is passed to the function that does the code generation (equivalent to f above), but (for various reasons) can't be passed as a parameter to the compiled code later.
I need to generate quoted code because this is part of a much larger code generation library that will apply further transforms to the generated code, hence I can't just do something like:
(defn f [image]
(fn [] (.getRGB image 0 0)))
A:
I guess you would need to write a macro that takes the object (or a way to create the required object) at compile time, serialize that object in binary format (byte array) and the output of the macro should be - a symbol that refer to the byte array and a function that can be used to get the object from the serialized data by de-serializing it.
A:
Not sure what you need it for, but you can create code that evals to an arbitrary object using the following cheat:
(def objs (atom []))
(defn make-code-that-evals-to [x]
(let [
nobjs (swap! objs #(conj % x))
i (dec (count nobjs))]
`(nth ~i @objs)))
Then you can:
> (eval (make-code-that-evals-to *out*))
#<PrintWriter java.io.PrintWriter@14aed2c>
This is just a proof of concept and it leaks the objects being produced - you could produce code that removes the reference on eval but then you could eval it only once.
Edit: The leaks can be prevented by the following (evil!) hack:
The above code bypasses eval's compiler by storing the object reference externally at the time the code is generated. This can be deferred. The object reference can be stored in the generated code with the compiler being bypassed by a macro. Storing the reference in the code means the garbage collector works normally.
The key is the macro that wraps the object. It does what the original solution did (i.e. store the object externally to bypass the compiler), but just before compilation. The generated expression retrieves the external reference, then deletes to prevent leaks.
Note: This is evil. Expansion-time of macros is the least desirable place for global side-effects to occur and this is exactly what this solution does.
Now for the code:
(def objs (atom {}))
Here's where will temporarily store the objects, keyed by unique keys (dictionary).
(defmacro objwrap [x sym]
(do
(swap! objs #(assoc % sym x) ) ; Global side-effect in macro expansion
`(let [o# (@objs ~sym)]
(do
(swap! objs #(dissoc % ~sym))
o#))))
This is the evil macro that sits in the generated code, keeping the object reference in x and a unique key in sym. Before compilation it stores the object in the external dictionary under the key sym and generates code that retrieves it, deletes the external reference and returns the retrieved object.
(defn make-code-that-evals-to [x]
(let [s 17] ; please replace 17 with a generated unique key. I was lazy here.
`(objwrap ~x ~s)))
Nothing fancy, just wrap the object in the evil macro, together with a unique key.
Of course if you only expand the macro without evaluating its result, you'll still get a leak.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which parts of the URL are encrypted by SSL?
Lets say we have the following URL request in the address bar of the Browser:
https://www.mydomain.com/herecomessomepathorauniqueidlike?=45345678654
My question is: Which part of this URL is protected by SSL, what part can be read by a man in the middle like an administrator in a company?
Thanks in advance.
A:
The administrator can likely tell the hostname of the site you're visiting but not the path. The hostname is transmitted in the initial ClientHello handshake if you're using TLS SNI, which approximately translates to "not on Windows XP or an OS of that vintage." Even without that, though, your administrator can
likely sniff your DNS requests
correlate those requests and their responses to the IPs you're contacting.
Everything else, including the path, is transmitted in the HTTP request once the encrypted link is established. In theory, there's no way for this to be man-in-the-middled; in practice, entities as diverse as SSL-stripping hackers and the NSA have demonstrated occasional capability to perform these attacks, but the likelihood of one happening inside a company network is relatively rare.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add / Remove specific number of elements from an Array on Click event
I'm trying to make seat booking system that allows a maximum of 4 seats to be selected. Each seat can be selected then deselected on click implementing toggleClass to change status from 'free' 'booked' on seats up to the maxSeats value of 4. It works fine up until the 4th seat is clicked. On a second click to the 4th seat, it does not pop from the tempArray and the class stays as 'booked'. The 1st, 2nd and 3rd seats all add and remove on click I have tried all manner of things to the point where I'm totally devoid of ideas where to go with it. I can see the items being added and removed from tempArray in the console so its not far away.
// Create an empty array to store the seat ids for click event
window.tempArray = [];
//Handle the click event
$('#plan').on('click', 'td.n', function() {
var maxSeats = d.numSeats; //grabbed from JSON
if ($('.booked').length < maxSeats) { // Use .length to check how many '.booked' DOM elements present
if ($(this).hasClass('taken')) {
alert('This Seat Is already booked!');
} else {
// Set the class to booked
$(this).toggleClass('booked');
// Iterate the .booked elements
$(this).each(function() {
// Getting the id of each seat
var seatLocation = $(this).attr('id');
// If seatLocation is not inArray - add it - else - pop it off
//$.inArray take (value , name of array)
var index = $.inArray(seatLocation, window.tempArray);
if (index == -1) { // -1 is returned if value is not found in array
window.tempArray.push(seatLocation);
} else {
window.tempArray.pop(seatLocation);
}
console.log(window.tempArray);
// output added seats to the page...
// join() convert array to a string, putting the argument between each element.
$('#seatLocation').html(window.tempArray.join('- -')).css({
backgroundColor: '#F6511D',
color: '#fff',
padding: '0.2em',
borderRadius: '2px',
margin: '0 10px 0 0'
});
});
A:
Check this fiddle (maxSeats:4 in fiddle).
// Create an empty array to store the seat ids for click event
window.tempArray = [];
//A function to update the location div
function updateLocation(){
$('#seatLocation').html(window.tempArray.join('- -')).css({
backgroundColor: '#F6511D',
color: '#fff',
padding: '0.2em',
borderRadius: '2px',
margin: '0 10px 0 0'
});
}
//Handle the click event
$('#plan').on('click', 'td.n', function() {
var maxSeats = d.numSeats; //grabbed from JSON
var seat=$(this);
var seatLocation = seat.attr('id');
if (seat.hasClass('booked')){ // Check if the user changed his mind
seat.removeClass('booked')
// Delete element in array.
// Function from http://stackoverflow.com/a/5767357/1076753
window.tempArray.splice(window.tempArray.indexOf(seatLocation), 1);
updateLocation();
console.log(window.tempArray);
} else if ($('.booked').length < maxSeats) { // Use .length to check how many '.booked' DOM elements present
if (seat.hasClass('taken')){
alert('This Seat Is already booked!');
} else {
seat.addClass('booked')
window.tempArray.push(seatLocation);
updateLocation();
console.log(window.tempArray);
}
}
});
PS: think always about the user experience! It's easy, imagine that you are an user and not a developer ;)
| {
"pile_set_name": "StackExchange"
} |
Q:
Access Typescript Class properties after construction
Let's say I have a class model Person
export class Person {
name:string;
lastname:string;
}
And in a controller I set a variable to this type of class.
Object.keys(person)
Returns only the defined Properties. Is there a way to access all the class properties without having to define each one of them? Or do I have to make a constructor in the class in order to initialize the object?
A:
You can iterate instance members using:
const person = new Person();
Object.getOwnPropertyNames(person).forEach((val, idx, array) => {
console.log(val);
});
But there is an extra gotcha in TypeScript... if a property is never set, it doesn't appear in the output, so your example class:
class Person {
name:string;
lastname:string;
}
Actually has no properties if you just create a new instance without setting then setting the values, i.e.:
var Person = /** @class */ (function () {
function Person() {
}
return Person;
}());
If you want to see them, make them constructor parameters, or set a default value.
Constructor Parameters:
class Person {
constructor(public name: string, public lastname: string) { }
}
Default Values:
class Person {
name: string = '';
lastname: string = '';
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Sum of two dates in PHP
how I can sum two dates?
I have two date in this format j h:i:s and I will like to sum them
I found this script but no reference about days and I'm new to this, here is the script, maybe somebody can make the necessary changes.
<?php
/**
* @author Masino Sinaga, http://www.openscriptsolution.com
* @copyright October 13, 2009
*/
echo sum_the_time('01:45:22', '17:27:03'); // this will give you a result: 19:12:25
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
return "{$hours}:{$minutes}:{$seconds}";
}
?>
Usage:
All that I need is to sum two dates from two task like:
Task 1 will take 1 day 10 hour 20 mins 10 sec
Task 2 will take 3 days 17 hours 35 mins 40 sec
so the result will be the total time between task 1 and two
A:
just convert the dates using strtotime and sum the timestamps, than convert to the date again using date function:
$tmstamp = strtotime($date1) + strtotime($date2);
echo date("Y m d", $tmstamp) ;
but why would you add two dates in the first place?
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I find out how much memory is used by a specific component or class?
Is it possible to retrieve the amount of memory that is used by a single component in delphi?
I'm downloading simple strings from the internet and I see that the memory usage is up to a gigabyte at by the end of the downloading process, but when I look at the saved file which contains everything I downloaded the file is only in the kilobyte range, clearly there is something going on with the components, even though I destroy them.
Example:
Edit:
procedure TForm1.OnCreate(Sender: TObject);
var list: TStringList;
begin
list:=TStringList.Create;
list.LoadFromFile('10MB_of_Data.txt');
list.destroy;
end;
How can I know that "list" as a TStringList is using 10 MB worth of space in memory?
Thank you.
A:
I think comparing the memory usage before and after is the way to go with this as there is no simple way of seeing what memory was allocated by a block of code after the fact... For example, with the string list above, the class itself will only take up a small amount of memory as it is made up of pointers to other allocations (i.e. the array of strings) and that itself is an array of pointers to to the actual strings... and this is a comparatively simple case.
Anyway, this can be done with FastMM with a function like follows...
uses
FastMM4;
function CheckAllocationBy(const AProc: TProc): NativeUInt;
var
lOriginalAllocated: NativeUInt;
lFinalAllocated: NativeUInt;
lUsage: TMemoryManagerUsageSummary;
begin
GetMemoryManagerUsageSummary(lUsage);
lOriginalAllocated := lUsage.AllocatedBytes;
try
AProc;
finally
GetMemoryManagerUsageSummary(lUsage);
lFinalAllocated := lUsage.AllocatedBytes;
end;
Result := lFinalAllocated - lOriginalAllocated;
end;
And can be used like so...
lAllocatedBytes := CheckAllocationBy(
procedure
begin
list:=TStringList.Create;
list.LoadFromFile('10MB_of_Data.txt');
list.Free;
end);
This will tell you how much your string list left behind (which interestingly I get 40 bytes for on the first run of repeated calls and 0 after which after consulting the usage logs before and after the call is two encoding classes created on the first call). If you want to check where leaked memory was allocated, it's simple to use FastMM to do that also (although I agree with the above that if it's 3rd party, it shouldn't be your problem).
| {
"pile_set_name": "StackExchange"
} |
Q:
When a remote notification is received, how to know whether the app is active at that time?
When I receive a notification, I want to play a sound so I set the json message to "sound":"mysound.mp3" and it works fine when the app is inactive. When the app becomes active, I also want to play a sound when I receive a message, but I found it not easy.
if I add the play code to - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo, then if the app is inactive, the sound will be played twice: 1. receive a remote message; 2. user clicks the message and call the play sound code.
Is there any way to distinguish these two situations or any workaround?
A:
Try this:
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
// Play sound when the app is active
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Eclipse Disable Warnings inside Java Editor
Usually, Eclipse shows the warning light bulbs on the left side of the Java editor.
That is fine.
Now, suddenly I see the light bulb and the warning also INSIDE THE CODE of text editor, what is sort of annoying. I must have changed some configuration, but I can remember which one.
Any idea of how to remove the warning from the editor?
A:
The following Eclipse forum thread talks about this: https://www.eclipse.org/forums/index.php/t/1102047/ .
If you follow the link to the page to https://www.eclipse.org/eclipse/news/4.14/platform.php#show-markers-as-code-minings , it shows how to turn it off.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's a decent lighting kit for getting started with portraits?
I've done mostly nature photography up to this point but later this month a friend is having a birthday and she just had a daughter so I wanted to take some father/daughter portraits.
So now I'm looking for a lighting kit I can use with my D80 which doesn't break the bank.
A:
I'm going to recommend slightly less than half of what @cmason suggested: One light, one umbrella, one light stand. See also the Strobist starving student kit. You can get an SB-600 and then have wireless control over your camera for not much more.
The reason I recommend one light over two is that it works just fine for a lot of portraiture. (Check out the excellent Q&As tagged with lighting basics; most of the techniques are based around only one light). Make no mistakes, having two (or more) lights gives you more flexibility than just one. However, you are looking to "not break the bank", and so starting out simple seems advisable. You might also want to get somewhat different components as you upgrade over time: a different make of flash, a soft box vs an umbrella, a different stand, a different triggering system, etc.
Also, I don't think a super clamp is strictly necessary. I definitely wouldn't get one instead of a light stand. Again, it's worth having once you're ready to spend more for more flexibility. (Don't forget though that you'll need an umbrella/hot shoe adapter for your light stand.)
A:
To start out I would recommend you get a single unit like a SB600 with light stand, clamp and either an umbrella or a soft box or both. What I would definitely also add is a reflector which will give you a lot of possibilities over just using a single light. A reflector is a lot cheaper than a second light but can be set up to provide fill light. A good reflector is also very useful when shooting in ambient light. Overall I would advise you get kit that gives you the most possibilities with minimum outlay at first, you can get the more specialised pieces later on. A single light and a reflector will give you the most possibilities for the minimum outlay.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make mouseover function break mouseleave?
I have this code:
$(".box").mouseover(function() {
$(this).find(".desc").animate({ "color": "#fff", "backgroundColor": "#1d2a63" }, 200);
});
$(".box").mouseleave(function() {
$(this).find(".desc").animate({ "color": "#747474", "backgroundColor": "#fff" }, 800 );
});
It's working but I want to stop animation within mouseleave when the user goes back to an element.
Here's a scenario: mouse is over box, it's changing OK, you're leaving and the 800 ms animation is being played, but when you go back over the box during this time, you have to wait until the animation finishes and then the mouseover is displayed. It's not looking good.
A:
Tony's comment is right. But as stated before, you don't actually need JS to do it, CSS could help, like that (vendor-prefixes not included for brevity):
.box {
color: #747474;
background-color: #fff;
transition: all .2s;
}
.box:hover {
color: #fff;
background-color: #1d2a63;
transition: all .8s;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Jetson TK1 / OpenCV4Tegra Linker errors
I've got a program that compiles / runs fine on my machine. I just picked up a Nvidia Jetson TK1 to try running it on that. I flashed to the latest version of linux4tegra, installed cuda and opencv per the instruction here and here. I'm getting linker errors whenever I try to run my make file:
(.text+0x94): undefined reference to `cv::VideoCapture::VideoCapture(std::string const&)'
(.text+0xb2): undefined reference to `cv::VideoCapture::isOpened() const'
(.text+0xcc): undefined reference to `cv::VideoCapture::~VideoCapture()'
(.text+0x108): undefined reference to `cv::namedWindow(std::string const&, int)'
(.text+0x146): undefined reference to `vtable for cv::VideoCapture'
(.text+0x14a): undefined reference to `vtable for cv::VideoCapture'
I already symlinked a few cuda SO's, but I can't figure out where these are coming from.
My makefile looks like:
g++ `pkg-config --libs opencv` ...
Package config returns:
$ pkg-config --libs opencv
/usr/lib/libopencv_calib3d.so /usr/lib/libopencv_contrib.so /usr/lib/libopencv_core.so /usr/lib/libopencv_features2d.so /usr/lib/libopencv_flann.so /usr/lib/libopencv_gpu.so /usr/lib/libopencv_highgui.so /usr/lib/libopencv_imgproc.so /usr/lib/libopencv_legacy.so /usr/lib/libopencv_ml.so /usr/lib/libopencv_objdetect.so /usr/lib/libopencv_photo.so /usr/lib/libopencv_stitching.so /usr/lib/libopencv_superres.so /usr/lib/libopencv_ts.a /usr/lib/libopencv_video.so /usr/lib/libopencv_videostab.so /usr/lib/libopencv_esm_panorama.so /usr/lib/libopencv_facedetect.so /usr/lib/libopencv_imuvstab.so /usr/lib/libopencv_tegra.so /usr/lib/libopencv_vstab.so -lcufft -lnpps -lnppi -lnppc -lcudart -lrt -lpthread -lm -ldl
Any ideas? My initial though was header / SO mismatch but since these all came from nvidia in the same package I think that's unlikely.
A:
Turns out I needed pkg-config --libs opencv after my files in the make file.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add handler to ListBoxItem in code?
I'm trying to solve my problem using addHandler method, but I have no idea how to set its parameters correctly.
My approach is:
lbi.AddHandler(OnMouseLeftButtonUp, GoToEditDraft, true);
public static void GoToEditDraft()
{
}
I want to have the method GoToEditDraft triggered when user clicks on ListBoxItem (lbi). I understand that my mistakes in data types, that I didn't set. How to set it correctly?
Thank you!
A:
"I want to have the method GoToEditDraft triggered when user clicks on ListBoxItem (lbi)". So how about this way :
lbi.MouseLeftButtonUp += GoToEditDraft;
private void GoToEditDraft(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
//TODO: put some logic here
}
| {
"pile_set_name": "StackExchange"
} |
Q:
TypeError: 'undefined' is not a function (evaluating '$(document)')
I'm using a WordPress site.
I'm including this script in the header.
When the script loads, I get this error:
TypeError: 'undefined' is not a function (evaluating '$(document)')
I have no idea what is causing it or what it even means.
In firebug, I get this:
$ is not a function
A:
Wordpress uses jQuery in noConflict mode by default. You need to reference it using jQuery as the variable name, not $, e.g. use
jQuery(document);
instead of
$(document);
You can easily wrap this up in a self executing function so that $ refers to jQuery again (and avoids polluting the global namespace as well), e.g.
(function ($) {
$(document);
}(jQuery));
A:
Use jQuery's noConflict. It did wonders for me
var example=jQuery.noConflict();
example(function(){
example('div#rift_connect').click(function(){
example('span#resultado').text("Hello, dude!");
});
});
That is, assuming you included jQuery on your HTML
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
A:
Use this:
var $ =jQuery.noConflict();
| {
"pile_set_name": "StackExchange"
} |
Q:
Links between Geometric Group Theory and Number Theory
Do You know any successful applications of the geometric group theory in the number theory? GTG is my main field of interest and I would love to use it to prove new facts in the number theory.
A:
It is hard to answer this question as both of these subjects are very broad. So I'll just quote something from the introduction of Lubotzky and Segal's Subgroup Growth:
"There have also been applications outside subgroup growth: a group-theoretic characterisation of arithmetic groups with the congruence subgroup property, estimates for the number of hyperbolic manifolds with given volume, and the results mentioned above on the enumeration and classification of finite p-groups."
It might be relevant to point out that representation theory and homological stability has some surprising connections with number theory. Here is a link to a paper by Tom Church and Benson Farb (also see the references given within) "Representation theory and homological stability": http://arxiv.org/abs/1008.1368
A:
Very broad question.
An example I like is the following: the classical Minkowski reduction theory for quadratic forms can be rephrased and generalized in terms of the action of the mapping class group $\textrm{Mod}_g$ on the Teichmuller space $\mathcal{T}_g$.
Roughly speaking, one can more generally interpret reduction theories of forms in terms of fundamental domains for group actions (Siegel, Borel, Harish-Chandra and others).
A:
Another reference showing the connections between geometric group theory and number theory is the book of
A. Lubotzky on "Discrete Groups, Expanding Graphs and Invariant Measures."
There are many special topics where a connection between number theory and geometric group theory arises. As an example see http://arxiv.org/abs/0901.1458.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a Perl statistics package that doesn't make me load the entire dataset at once?
I'm looking for a statistics package for Perl (CPAN is fine) that allows me to add data incrementally instead of having to pass in an entire array of data.
Just the mean, median, stddev, max, and min is necessary, nothing too complicated.
The reason for this is because my dataset is entirely too large to fit into memory. The data source is in a MySQL database, so right now I'm just querying a subset of the data and computing the statistics for them, then combining all the manageable subsets later.
If you have other ideas on how to overcome this issue, I'd be much obliged!
A:
You can not do an exact stddev and a median unless you either keep the whole thing in memory or run through the data twice.
UPDATE While you can not do an exact stddev IN ONE PASS, there's an approximation one-pass algorithm, the link is in a comment to this answer.
The rest are completely trivial (no need for a module) to do in 3-5 lines of Perl.
STDDEV/Median can be done in 2 passes fairly trivially as well (I just rolled out a script that did exactly what you described, but for IP reasons I'm pretty sure I'm not allowed to post it as example for you, sorry)
Sample code:
my ($min, $max)
my $sum = 0;
my $count = 0;
while (<>) {
chomp;
my $current_value = $_; #assume input is 1 value/line for simplicity sake
$sum += $current_value;
$count++;
$min = $current_value if (!defined $min || $min > $current_value);
$max = $current_value if (!defined $max || $max < $current_value);
}
my $mean = $sum * 1.0 / $count;
my $sum_mean_diffs_2 = 0;
while (<>) { # Second pass to compute stddev (use for median too)
chomp;
my $current_value = $_;
$sum_mean_diffs += ($current_value - $mean) * ($current_value - $mean);
}
my $std_dev = sqrt($sum_mean_diffs / $count);
# Median is left as excercise for the reader.
A:
Statistics::Descriptive::Discrete allows you to do this in a manner similar to Statistics::Descriptive, but has been optimized for use with large data sets. (The documentation reports an improvement by two orders of magnitude (100x) in memory usage, for example).
A:
Why don't you simply ask the database for the values you are trying to compute?
Amongst others, MySQL features GROUP BY (Aggregate) functions. For missing functions, all you need is a little SQL.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reference Request: Elliptic differential operators in the Fréchet setting
Normally the theory of (elliptic) differential operators between vector bundles (or $\mathbb{R}^n$) is presented in the language of Sobolev spaces. I'm searching for a book (or something similar) which exposes the theory completely in the setting of smooth sections, that is using Fréchet space techniques.
In particular, I'm interested in how the Fredholm theory translates into Fréchet spaces. The basic results should transfer without big modifications, however some results are not so straightforward (like "Fredholm operators are open in the space of all continuous linear maps" since the theory of dual spaces is more complicated).
A:
The book Locally Convex Spaces by Osborne has a statement on p152 of the Fredholm alternative for Hausdorff locally convex spaces. Also consider the exercises from 26 onwards of the same chapter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Alternative to Microsoft XNA Game Studio?
For some reason the XNA Game Studio doesn't work on my PC. :( . It says something about pixel shaders and my hardware doesn't support something or the other. I just need to make some decent 2D games and demos. Neither do I think it will work on the PCs of my intended audience ( people from developing south-asian countries).
So is there any alternative for XNA that gives me equal performance and has a mature enough API?
A:
You could check out Allegro (a game programming library)
Edit to provide more information:
Allegro 4 and Allegro 5 are cross-platform, libraries mainly aimed at video game and multimedia programming. They handle common, low-level tasks such as creating windows, accepting user input, loading data, drawing images, playing sounds, etc. and generally abstracting away the underlying platform. However, Allegro is not a game engine: you are free to design and structure your program as you like.
Allegro 4 and 5 support the major OSs (Unix/Linux, Windows (MSVC, MinGW) and MacOS X). The engine supports 2D graphics primitives natively (you will need a separate API, like OpenGL or DirectX for 3D rendering, but you said that is not your target).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass connection string to a class library?
I have a project structure like
MySolution
-FrontEnd
-webforms
-console
-Mvc
-Repositories
-Dapper (Class library)
-Tests
How do I reference the connection string in my repository class library? I tried adding App.Config in my class library project but it is not available in Add New Items. I am using Visual Studio 2013 express for web. Thanks, Damien.
A:
The .Config that applies to libraries is the one of the executing assembly using those libraries, so you don't have to add an App.Config to your project, it will use the App or Web.Config of your startup project.
In order to get access to the ConfigurationManager you need to add a reference to System.Configuration in your library project.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nhibernate QueryOver - Performing a Has All for a Many-to-Many relationship
To explain my problem more easily I will create the following fictional example, illustrating a very basic many-to-many relationship. A Car can have many Parts, and a Part can belong to many Cars.
DB SCHEMA:
CAR_TABLE
---------
CarId
ModelName
CAR_PARTS_TABLE
---------------
CarId
PartId
PARTS_TABLE
-----------
PartId
PartName
CLASSES:
public class Car
{
public int CarId {get;set;}
public string Name {get;set;}
public IEnumerable<Part> Parts {get;set;}
}
public class Part
{
public int PartId {get;set;}
public string Name {get;set}
}
Using this very simple model I would like to get any cars that have all the parts assigned to them from a list of parts I am searching on.
So say I have an array of PartIds:
var partIds = new [] { 1, 3, 10};
I want to mimic the following c# code in terms of a database call:
var allCars = /* code to retrieve all cars */
var results = new List<Car>();
foreach (var car in allCars)
{
var containsAllParts = true;
foreach (var carPart in car.Parts)
{
if (false == partIds.Contains(carPart.PartId))
{
containsAllParts = false;
break;
}
}
if (containsAllParts)
{
results.Add(car);
}
}
return results;
To be clear: I want to get the Cars that have ALL of the Parts specified from the partIds array.
I have the following query, which is REALLY inefficient as it creates a subquery for each id within the partIds array and then does an IsIn query on each of their results. I am desperate to find a much more efficient manner to execute this query.
Car carAlias = null;
Part partAlias = null;
var searchCriteria = session.QueryOver<Car>(() => carAlias);
foreach (var partId in partIds)
{
var carsWithPartCriteria = QueryOver.Of<Car>(() => carAlias)
.JoinAlias(() => carAlias.Parts, () => partAlias)
.Where(() => partAlias.PartId == partId)
.Select(Projections.Distinct(Projections.Id()));
searchCriteria = searchCriteria
.And(Subqueries.WhereProperty(() => carAlias.Id).In(carsWithPartCriteria));
}
var results = searchCriteria.List<Car>();
Is there a decent way to execute this sort of query using NHibernate?
A:
This should be exactly what you want...
Part part = null;
Car car = null;
var qoParts = QueryOver.Of<Part>(() => part)
.WhereRestrictionOn(x => x.PartId).IsIn(partIds)
.JoinQueryOver(x => x.Cars, () => car)
.Where(Restrictions.Eq(Projections.Count(() => car.CarId), partIds.Length))
.Select(Projections.Group(() => car.CarId));
A:
Part partAlias=null;
Session.QueryOver<Car>().JoinQueryOver(x=>x.Parts,()=>partAlias)
.WhereRestrictionOn(()=>partAlias.Id).IsIn(partIds) //partIds should be implement an ICollection
.List<Car>();
Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wildfly configuration - weird error on startup
Hey I am trying to configure a Wildfly server but when I try to start the server I get the following errors. What am I doing wrong?
I had to reinstall the server after trying several times yesterday.
2014-03-31 23:18:41,102 DEBUG [org.jboss.as.config] (MSC service thread 1-6) VM Arguments: -XX:+UseCompressedOops -Dprogram.name=standalone.bat -Xms64M -Xmx512M -XX:MaxPermSize=256M -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Dorg.jboss.boot.log.file=C:\Users\Ilhami\wildfly-8.0.0.Final\standalone\log\server.log -Dlogging.configuration=file:C:\Users\Ilhami\wildfly-8.0.0.Final\standalone\configuration/logging.properties
2014-03-31 23:18:41,915 ERROR [org.jboss.as.server] (Controller Boot Thread) JBAS015956: Caught exception during boot: org.jboss.as.controller.persistence.ConfigurationPersistenceException: JBAS014676: Failed to parse configuration
at org.jboss.as.controller.persistence.XmlConfigurationPersister.load(XmlConfigurationPersister.java:112) [wildfly-controller-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.as.server.ServerService.boot(ServerService.java:331) [wildfly-server-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.as.controller.AbstractControllerService$1.run(AbstractControllerService.java:256) [wildfly-controller-8.0.0.Final.jar:8.0.0.Final]
at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_51]
Caused by: javax.xml.stream.XMLStreamException: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[148,21]
Message: "JBAS014746: driver may not be null"
at org.jboss.as.connector.subsystems.datasources.DataSourcesExtension$DataSourceSubsystemParser.readElement(DataSourcesExtension.java:637)
at org.jboss.as.connector.subsystems.datasources.DataSourcesExtension$DataSourceSubsystemParser.readElement(DataSourcesExtension.java:193)
at org.jboss.staxmapper.XMLMapperImpl.processNested(XMLMapperImpl.java:110) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
at org.jboss.staxmapper.XMLExtendedStreamReaderImpl.handleAny(XMLExtendedStreamReaderImpl.java:69) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
at org.jboss.as.server.parsing.StandaloneXml.parseServerProfile(StandaloneXml.java:1131) [wildfly-server-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.as.server.parsing.StandaloneXml.readServerElement_1_4(StandaloneXml.java:458) [wildfly-server-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.as.server.parsing.StandaloneXml.readElement(StandaloneXml.java:145) [wildfly-server-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.as.server.parsing.StandaloneXml.readElement(StandaloneXml.java:107) [wildfly-server-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.staxmapper.XMLMapperImpl.processNested(XMLMapperImpl.java:110) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
at org.jboss.staxmapper.XMLMapperImpl.parseDocument(XMLMapperImpl.java:69) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
at org.jboss.as.controller.persistence.XmlConfigurationPersister.load(XmlConfigurationPersister.java:104) [wildfly-controller-8.0.0.Final.jar:8.0.0.Final]
... 3 more
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[148,21]
Message: "JBAS014746: driver may not be null"
at org.jboss.as.controller.SimpleAttributeDefinition.parse(SimpleAttributeDefinition.java:189) [wildfly-controller-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.as.controller.SimpleAttributeDefinition.parseAndSetParameter(SimpleAttributeDefinition.java:214) [wildfly-controller-8.0.0.Final.jar:8.0.0.Final]
at org.jboss.as.connector.subsystems.datasources.DsParser.parseDataSource(DsParser.java:653)
at org.jboss.as.connector.subsystems.datasources.DsParser.parseDataSources(DsParser.java:202)
at org.jboss.as.connector.subsystems.datasources.DsParser.parse(DsParser.java:173)
at org.jboss.as.connector.subsystems.datasources.DataSourcesExtension$DataSourceSubsystemParser.readElement(DataSourcesExtension.java:628)
... 13 more
2014-03-31 23:18:41,930 FATAL [org.jboss.as.server] (Controller Boot Thread) JBAS015957: Server boot has failed in an unrecoverable manner; exiting. See previous messages for details.
2014-03-31 23:18:41,946 INFO [org.jboss.as] (MSC service thread 1-2) JBAS015950: WildFly 8.0.0.Final "WildFly" stopped in 7ms
Here is my standalone.xml:
<?xml version='1.0' encoding='UTF-8'?>
<server xmlns="urn:jboss:domain:2.0">
<extensions>
<extension module="org.jboss.as.clustering.infinispan"/>
<extension module="org.jboss.as.connector"/>
<extension module="org.jboss.as.deployment-scanner"/>
<extension module="org.jboss.as.ee"/>
<extension module="org.jboss.as.ejb3"/>
<extension module="org.jboss.as.jaxrs"/>
<extension module="org.jboss.as.jdr"/>
<extension module="org.jboss.as.jmx"/>
<extension module="org.jboss.as.jpa"/>
<extension module="org.jboss.as.jsf"/>
<extension module="org.jboss.as.logging"/>
<extension module="org.jboss.as.mail"/>
<extension module="org.jboss.as.naming"/>
<extension module="org.jboss.as.pojo"/>
<extension module="org.jboss.as.remoting"/>
<extension module="org.jboss.as.sar"/>
<extension module="org.jboss.as.security"/>
<extension module="org.jboss.as.threads"/>
<extension module="org.jboss.as.transactions"/>
<extension module="org.jboss.as.webservices"/>
<extension module="org.jboss.as.weld"/>
<extension module="org.wildfly.extension.batch"/>
<extension module="org.wildfly.extension.io"/>
<extension module="org.wildfly.extension.undertow"/>
</extensions>
<management>
<security-realms>
<security-realm name="ManagementRealm">
<authentication>
<local default-user="$local"/>
<properties path="mgmt-users.properties" relative-to="jboss.server.config.dir"/>
</authentication>
<authorization map-groups-to-roles="false">
<properties path="mgmt-groups.properties" relative-to="jboss.server.config.dir"/>
</authorization>
</security-realm>
<security-realm name="ApplicationRealm">
<authentication>
<local default-user="$local" allowed-users="*"/>
<properties path="application-users.properties" relative-to="jboss.server.config.dir"/>
</authentication>
<authorization>
<properties path="application-roles.properties" relative-to="jboss.server.config.dir"/>
</authorization>
</security-realm>
</security-realms>
<audit-log>
<formatters>
<json-formatter name="json-formatter"/>
</formatters>
<handlers>
<file-handler name="file" formatter="json-formatter" relative-to="jboss.server.data.dir" path="audit-log.log"/>
</handlers>
<logger log-boot="true" log-read-only="false" enabled="false">
<handlers>
<handler name="file"/>
</handlers>
</logger>
</audit-log>
<management-interfaces>
<http-interface security-realm="ManagementRealm" http-upgrade-enabled="true">
<socket-binding http="management-http"/>
</http-interface>
</management-interfaces>
<access-control provider="simple">
<role-mapping>
<role name="SuperUser">
<include>
<user name="$local"/>
</include>
</role>
</role-mapping>
</access-control>
</management>
<profile>
<subsystem xmlns="urn:jboss:domain:logging:2.0">
<console-handler name="CONSOLE">
<level name="INFO"/>
<formatter>
<named-formatter name="COLOR-PATTERN"/>
</formatter>
</console-handler>
<periodic-rotating-file-handler name="FILE" autoflush="true">
<formatter>
<named-formatter name="PATTERN"/>
</formatter>
<file relative-to="jboss.server.log.dir" path="server.log"/>
<suffix value=".yyyy-MM-dd"/>
<append value="true"/>
</periodic-rotating-file-handler>
<logger category="com.arjuna">
<level name="WARN"/>
</logger>
<logger category="org.apache.tomcat.util.modeler">
<level name="WARN"/>
</logger>
<logger category="org.jboss.as.config">
<level name="DEBUG"/>
</logger>
<logger category="sun.rmi">
<level name="WARN"/>
</logger>
<logger category="jacorb">
<level name="WARN"/>
</logger>
<logger category="jacorb.config">
<level name="ERROR"/>
</logger>
<root-logger>
<level name="INFO"/>
<handlers>
<handler name="CONSOLE"/>
<handler name="FILE"/>
</handlers>
</root-logger>
<formatter name="PATTERN">
<pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
</formatter>
<formatter name="COLOR-PATTERN">
<pattern-formatter pattern="%K{level}%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
</formatter>
</subsystem>
<subsystem xmlns="urn:jboss:domain:batch:1.0">
<job-repository>
<in-memory/>
</job-repository>
<thread-pool>
<max-threads count="10"/>
<keepalive-time time="100" unit="milliseconds"/>
</thread-pool>
</subsystem>
<subsystem xmlns="urn:jboss:domain:datasources:2.0">
<datasources>
<datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
<driver>h2</driver>
<security>
<user-name>sa</user-name>
<password>sa</password>
</security>
</datasource>
<datasource jndi-name="java:jboss/datasources/DBTest" pool-name="DBTest" enabled="true" use-java-context="true">
<connection-url>jdbc:mysql27.unoeuro.com?autoReconnect=true</connection-url>
<driver name="mysql-connector-java-5.1.29.bin" module="com.mysql"/>
<security>
<user-name>****</user-name>
<password>****</password>
</security>
</datasource>
<drivers>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
<driver name="com.mysql.Driver" module="com.mysql">
<xa-datasource-class>mysql-connector-java-5.1.29.bin</xa-datasource-class>
</driver>
</drivers>
</datasources>
</subsystem>
<subsystem xmlns="urn:jboss:domain:deployment-scanner:2.0">
<deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000" runtime-failure-causes-rollback="${jboss.deployment.scanner.rollback.on.failure:false}"/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:ee:2.0">
<spec-descriptor-property-replacement>false</spec-descriptor-property-replacement>
<jboss-descriptor-property-replacement>true</jboss-descriptor-property-replacement>
<annotation-property-replacement>false</annotation-property-replacement>
<concurrent>
<context-services>
<context-service name="default" jndi-name="java:jboss/ee/concurrency/context/default" use-transaction-setup-provider="true"/>
</context-services>
<managed-executor-services>
<managed-executor-service name="default" jndi-name="java:jboss/ee/concurrency/executor/default" context-service="default" hung-task-threshold="60000" core-threads="5" max-threads="25" keepalive-time="5000"/>
</managed-executor-services>
<managed-scheduled-executor-services>
<managed-scheduled-executor-service name="default" jndi-name="java:jboss/ee/concurrency/scheduler/default" context-service="default" hung-task-threshold="60000" core-threads="2" keepalive-time="3000"/>
</managed-scheduled-executor-services>
<managed-thread-factories>
<managed-thread-factory name="default" jndi-name="java:jboss/ee/concurrency/factory/default" context-service="default"/>
</managed-thread-factories>
</concurrent>
<default-bindings context-service="java:jboss/ee/concurrency/context/default" datasource="java:jboss/datasources/DBTest" jms-connection-factory="java:jboss/DefaultJMSConnectionFactory" managed-executor-service="java:jboss/ee/concurrency/executor/default" managed-scheduled-executor-service="java:jboss/ee/concurrency/scheduler/default" managed-thread-factory="java:jboss/ee/concurrency/factory/default"/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:ejb3:2.0">
<session-bean>
<stateful default-access-timeout="5000" cache-ref="simple" passivation-disabled-cache-ref="simple"/>
<singleton default-access-timeout="5000"/>
</session-bean>
<pools>
<bean-instance-pools>
<!-- A sample strict max pool configuration -->
<strict-max-pool name="slsb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/>
<strict-max-pool name="mdb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/>
</bean-instance-pools>
</pools>
<caches>
<cache name="simple"/>
<cache name="distributable" aliases="passivating clustered" passivation-store-ref="infinispan"/>
</caches>
<passivation-stores>
<passivation-store name="infinispan" cache-container="ejb" max-size="10000"/>
</passivation-stores>
<async thread-pool-name="default"/>
<timer-service thread-pool-name="default" default-data-store="default-file-store">
<data-stores>
<file-data-store name="default-file-store" path="timer-service-data" relative-to="jboss.server.data.dir"/>
</data-stores>
</timer-service>
<remote connector-ref="http-remoting-connector" thread-pool-name="default"/>
<thread-pools>
<thread-pool name="default">
<max-threads count="10"/>
<keepalive-time time="100" unit="milliseconds"/>
</thread-pool>
</thread-pools>
<default-security-domain value="other"/>
<default-missing-method-permissions-deny-access value="true"/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:io:1.0">
<worker name="default" io-threads="3"/>
<buffer-pool name="default" buffer-size="16384" buffers-per-slice="128"/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:infinispan:2.0">
<cache-container name="web" default-cache="passivation" module="org.wildfly.clustering.web.infinispan">
<local-cache name="passivation" batching="true">
<file-store passivation="true" purge="false"/>
</local-cache>
<local-cache name="persistent" batching="true">
<file-store passivation="false" purge="false"/>
</local-cache>
</cache-container>
<cache-container name="ejb" aliases="sfsb" default-cache="passivation" module="org.wildfly.clustering.ejb.infinispan">
<local-cache name="passivation" batching="true">
<file-store passivation="true" purge="false"/>
</local-cache>
<local-cache name="persistent" batching="true">
<file-store passivation="false" purge="false"/>
</local-cache>
</cache-container>
<cache-container name="hibernate" default-cache="local-query" module="org.hibernate">
<local-cache name="entity">
<transaction mode="NON_XA"/>
<eviction strategy="LRU" max-entries="10000"/>
<expiration max-idle="100000"/>
</local-cache>
<local-cache name="local-query">
<transaction mode="NONE"/>
<eviction strategy="LRU" max-entries="10000"/>
<expiration max-idle="100000"/>
</local-cache>
<local-cache name="timestamps">
<transaction mode="NONE"/>
<eviction strategy="NONE"/>
</local-cache>
</cache-container>
</subsystem>
<subsystem xmlns="urn:jboss:domain:jaxrs:1.0"/>
<subsystem xmlns="urn:jboss:domain:jca:2.0">
<archive-validation enabled="true" fail-on-error="true" fail-on-warn="false"/>
<bean-validation enabled="true"/>
<default-workmanager>
<short-running-threads>
<core-threads count="50"/>
<queue-length count="50"/>
<max-threads count="50"/>
<keepalive-time time="10" unit="seconds"/>
</short-running-threads>
<long-running-threads>
<core-threads count="50"/>
<queue-length count="50"/>
<max-threads count="50"/>
<keepalive-time time="10" unit="seconds"/>
</long-running-threads>
</default-workmanager>
<cached-connection-manager/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:jdr:1.0"/>
<subsystem xmlns="urn:jboss:domain:jmx:1.3">
<expose-resolved-model/>
<expose-expression-model/>
<remoting-connector/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:jpa:1.1">
<jpa default-datasource="" default-extended-persistence-inheritance="DEEP"/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:jsf:1.0"/>
<subsystem xmlns="urn:jboss:domain:mail:2.0">
<mail-session name="default" jndi-name="java:jboss/mail/Default">
<smtp-server outbound-socket-binding-ref="mail-smtp"/>
</mail-session>
</subsystem>
<subsystem xmlns="urn:jboss:domain:naming:2.0">
<remote-naming/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:pojo:1.0"/>
<subsystem xmlns="urn:jboss:domain:remoting:2.0">
<endpoint worker="default"/>
<http-connector name="http-remoting-connector" connector-ref="default" security-realm="ApplicationRealm"/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:resource-adapters:2.0"/>
<subsystem xmlns="urn:jboss:domain:sar:1.0"/>
<subsystem xmlns="urn:jboss:domain:security:1.2">
<security-domains>
<security-domain name="other" cache-type="default">
<authentication>
<login-module code="Remoting" flag="optional">
<module-option name="password-stacking" value="useFirstPass"/>
</login-module>
<login-module code="RealmDirect" flag="required">
<module-option name="password-stacking" value="useFirstPass"/>
</login-module>
</authentication>
</security-domain>
<security-domain name="jboss-web-policy" cache-type="default">
<authorization>
<policy-module code="Delegating" flag="required"/>
</authorization>
</security-domain>
<security-domain name="jboss-ejb-policy" cache-type="default">
<authorization>
<policy-module code="Delegating" flag="required"/>
</authorization>
</security-domain>
</security-domains>
</subsystem>
<subsystem xmlns="urn:jboss:domain:threads:1.1"/>
<subsystem xmlns="urn:jboss:domain:transactions:2.0">
<core-environment>
<process-id>
<uuid/>
</process-id>
</core-environment>
<recovery-environment socket-binding="txn-recovery-environment" status-socket-binding="txn-status-manager"/>
<coordinator-environment default-timeout="300"/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:undertow:1.0">
<buffer-caches>
<buffer-cache name="default" buffer-size="1024" buffers-per-region="1024" max-regions="10"/>
</buffer-caches>
<server name="default-server">
<http-listener name="default" socket-binding="http"/>
<host name="default-host" alias="localhost">
<location name="/" handler="welcome-content"/>
<filter-ref name="server-header"/>
<filter-ref name="x-powered-by-header"/>
</host>
</server>
<servlet-container name="default" default-buffer-cache="default" stack-trace-on-error="local-only">
<jsp-config/>
</servlet-container>
<handlers>
<file name="welcome-content" path="${jboss.home.dir}/welcome-content" directory-listing="true"/>
</handlers>
<filters>
<response-header name="server-header" header-name="Server" header-value="Wildfly 8"/>
<response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow 1"/>
</filters>
</subsystem>
<subsystem xmlns="urn:jboss:domain:webservices:1.2">
<modify-wsdl-address>true</modify-wsdl-address>
<wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>
<endpoint-config name="Standard-Endpoint-Config"/>
<endpoint-config name="Recording-Endpoint-Config">
<pre-handler-chain name="recording-handlers" protocol-bindings="##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM">
<handler name="RecordingHandler" class="org.jboss.ws.common.invocation.RecordingServerHandler"/>
</pre-handler-chain>
</endpoint-config>
<client-config name="Standard-Client-Config"/>
</subsystem>
<subsystem xmlns="urn:jboss:domain:weld:2.0"/>
</profile>
<interfaces>
<interface name="management">
<inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
</interface>
<interface name="public">
<inet-address value="${jboss.bind.address:127.0.0.1}"/>
</interface>
<!-- TODO - only show this if the jacorb subsystem is added -->
<interface name="unsecure">
<!--
~ Used for IIOP sockets in the standard configuration.
~ To secure JacORB you need to setup SSL
-->
<inet-address value="${jboss.bind.address.unsecure:127.0.0.1}"/>
</interface>
</interfaces>
<socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">
<socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
<socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9993}"/>
<socket-binding name="ajp" port="${jboss.ajp.port:8009}"/>
<socket-binding name="http" port="${jboss.http.port:8080}"/>
<socket-binding name="https" port="${jboss.https.port:8443}"/>
<socket-binding name="txn-recovery-environment" port="4712"/>
<socket-binding name="txn-status-manager" port="4713"/>
<outbound-socket-binding name="mail-smtp">
<remote-destination host="localhost" port="25"/>
</outbound-socket-binding>
</socket-binding-group>
</server>
A:
the driver configuration for your datasource is wrong (line 148).
You have to reference a driver defined in the drivers section. Please have a look at line 140 in your standalone.xml for the driver reference.
| {
"pile_set_name": "StackExchange"
} |
Q:
Searching Range Sheet1 Against Range in Sheet2 Copy to Sheet3 depending on value in lateral cell
I have searched and found a number of posts that are similar for instance
Look for values from sheet A in sheet B, and then do function in corresponding sheet B cell
and
For each Loop Will Not Work Search for Value On one Sheet and Change Value on another Sheet
While each of these address some aspect of my goal they are not quite it.
I have 3 sheets, sheet1 - 3, I want to search and match in sheets1 - 2 on columns A and B, if a match is found or not found in column B check value in column A to copy to sheet3 or not.
This is what I have so far using Office 2016.
Public Sub SeekFindCopyTo()
Dim lastRow1 As Long
Dim lastRow2 As Long
Dim tempVal As String
lastRow1 = Sheets("Sheet1").Range("B" & Rows.Count).End(xlUp).Row
lastRow2 = Sheets("Sheet2").Range("B" & Rows.Count).End(xlUp).Row
For sRow = 4 To lastRow1
Debug.Print ("sRow is " & sRow)
tempVal = Sheets("Sheet1").Cells(sRow, "B").Text
For tRow = 4 To lastRow2
Debug.Print ("tRow is " & tRow)
TestVal = Sheets("Sheet2").Cells(tRow, "B")
Operations = Sheets("Sheet2").Cells(tRow, "A")
If Sheets("SAP_XMATTERS").Cells(tRow, "B") = tempVal Then
Operations = Sheets("Sheet2").Cells(tRow, "A")
Debug.Print ("If = True tempVal is " & tempVal)
Debug.Print ("If = True TestVal is " & TestVal)
Debug.Print ("If = True Operaitons is " & Operations)
If Operations = "REMOVE" Then
Sheets("Sheet2").Range("A" & tRow).EntireRow.Copy
Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Insert xlcutcell
'Sheets("Sheet2").Rows(tRow).Delete
Else
'Sheets("Sheet2").Rows(tRow).Delete
End If
End If
Next tRow
Next sRow
End Sub
The code works well enough but the catch is that I am looking for a match in B:B between Sheets 1&2 if match I want to check the adjacent cell in A:A for the string REMOVE if it is REMOVE then copy entire row to sheet3. Here's the problem I also want to know if there is not a match in B:B between Sheets 2 & 1 with the string PROCESS in adjacent cell if so copy entire row to sheet3. I can do either option in separate subs but cannot make it work in one pass.
Your help would be appreciated even if it is along the lines of "you can't do that" ;-)
TIA
Bob
A:
A total re-write using .Find did the trick.
Sub SeekFindCopy()
Dim sourceValue As Variant
Dim resultOfSeek As Range
Dim targetRange As Range
LastRow = Sheets("Sheet1").Range("B" & Rows.Count).End(xlUp).Row
Set targetRange = Sheets("Sheet2").Range("B:B")
For sourceRow = 4 To LastRow
Debug.Print ("sRow is " & sRow)
sourceValue = Sheets("Sheet1").Range("B" & sRow).Value
Set resultOfSeek = targetRange.Find(what:=sourceValue, After:=targetRange(1))
'Debug.Print (sourceValue)
Operations = Sheets("Sheet1").Cells(sRow, "A")
If resultOfSeek Is Nothing Then
'Debug.Print ("Operations is " & Operations)
If Operations = "PROCESS" Then
Sheets("Sheet1").Range("A" & sRow).EntireRow.Copy
Sheets("UpLoad").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Insert xlcutcell
'Sheets("Sheet1").Rows(tRow).Delete
End If
Else
'Debug.Print ("Operations is " & Operations)
If Operations = "REMOVE" Then
Sheets("Sheet1").Range("A" & sRow).EntireRow.Copy
Sheets("UpLoad").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Insert xlcutcell
'Sheets("Sheet1").Rows(tRow).Delete
End If
End If
Next sourceRow
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Community VFP Mobile Responsiveness issue
So I have built out a custom VFP that we are using for our Community. Now, when I 'decrease' the browser to a mobile size, it resizes and goes into our Mobile-friendly mode. However, when I open it on my phone it is NOT doing that Mobile-friendly responsiveness. Is this an issue that others have come across, is this community related? Or is there something I'm missing?
A:
I don't know of any issues with responsive design with Visualforce in Communities. There are a number of developerforce articles and blogs that provide guidance on how to design a page to support different frameworks. Here are two:
https://developer.salesforce.com/blogs/developer-relations/2015/01/responsive-design-javascript-html5-css-visualforce.html
https://developer.salesforce.com/page/Responsive_Design_with_Twitter_Bootstrap_and_Visualforce
Some things in particular you could check would be:
Have you set the viewport metatag in the <head>:
<meta name="viewport” content="width=device-width, initial-scale=1.0”></meta>
Have you set the doctype to html5 and removed the various salesforce added styles in the <apex:page> tag?
<apex:page showheader="false" sidebar="false" standardstylesheets="false" doctype="html-5.0">
| {
"pile_set_name": "StackExchange"
} |
Q:
Installing Ruby on Rails on windows
I am in the process of installing Ruby on Rails on windows 7. I installed ruby-1.9.2 (in c:\ruby) and I've installed rails using the gem install rails command (doing this from c:\ruby\bin since this is the only place i can call the command). I've then run rails new my_app command.
The problem that I have is trying to run the rails server command from inside the apps folder (c:\ruby\bin\my_app) I get the message: 'rails' is not recognized....
What have I done wrong?
A:
On Windows you need to set your system PATH variable (My Computer -> Properties -> Advanced -> Environment Variables -> System variables)
Append the PATH Variable value:: c:\ruby\bin;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to extract Python object from JSON object?
I'm able to get a JSON string from a Python object as is :
def myserialize(obj):
return obj.__dict__
class A:
def __init__(self):
self._filename = AString()
self._size = AnInt()
self.objectString = ObjectContainingAString()
self.arrayOfObject = ....
def get_json_string(self):
return json.dumps(self.__dict__,default=myserialize,indent=4,sort_keys=True)
The JSON output looks like this
{
"_filename" : "value_of_string"
"_size" : value_of_int
"objectString": {
"string" : "value_of_string"
}
"arrayOfObject" : [
{
"obj1" : {
...
}
},
{
"obj2"...
}
]
}
This is exactly what I want ! A simple way to convert Python "complex" object to JSON string.
Problem :
But now, I'd like to convert this string to the same "complex" Python object !
Scenario:
The scenario is that I have a few more (different) "complex" objects that I want to convert back and forth from a JSON string.
It's okay if the solution you give must include an ID in the string somehow stating "this is a JSON string for an object of type XYZ only" since I only have a few "complex" objects (5/6).
EDIT 1
Complete scenario : I have 6 binary files containing configuration for an embedded software. This is clearly not human-readable.
I'm currently using Python to parse the binary file and extract its content to get a human-readable version. (JSON or something else !) JSON at least has the advantage of converting the Python object containg all the info about one config file in one line.
People should now be able to edit a few values in the (JSON or whatever) text configuration file.
I want to be able to convert the text file back to the corresponding Python object, and serialize it to get a modified binary file !
END OF EDIT
A:
The simplest re-usable solution I see involves two steps:
parse the json back into a python dictionary (this handles type conversions), and can be done outside of your class's constructor
optionally feed a python dictionary into your class's constructor and, when specified, use it to populate your class's fields with setattr
Here are the same thoughts expressed as python code:
class A:
def __init__(self, input_dict=None):
if input_dict is not None:
for k, v in input_dict.items():
setattr(self, k, v)
else:
self._filename = AString()
self._size = AnInt()
self.objectString = ObjectContainingAString()
self.arrayOfObject = ....
...
# Assume we have a list of json strings created by your json export
# Now parse json strings and turn them into objects of class A
for json_str in json_strs:
new_object = A(input_dict=json.loads(json_str))
# Do something with new_object...
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL Trigger, vague syntax error
Using MySQL 5.5, the following trigger is getting rejected with an error:
create trigger nodups
before insert on `category-category`
for each row
begin
if(catid >= relatedid) then
signal 'catid must be less than relatedid';
end if
end;
I'm getting the following error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use
near '-category for each row begin if(catid >= relatedid) then signal 'catid
must be l' at line 1
What is wrong with the syntax for this trigger?
For what it's worth, I'm just trying to prevent inserts with catid >= relatedid. I am open to other methods of achieving this goal.
Edit:
The query above is being entered on a single line, semi-colons and all.
I tried it again using a delimiter. Here is the result:
mysql> delimiter ###
mysql> create trigger nodups
-> before insert on `category-category`
-> for each row
-> begin
-> if(catid >= relatedid) then
-> signal 'catid must be less than relatedid';
-> end if
-> end;
-> ###
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''catid must be less than relatedid';
end if
end' at line 6
A:
- is a special character. You need to escape a table containg special characters with backticks
delimiter |
create trigger nodups
before insert on `category-category`
for each row
begin
if(catid >= relatedid) then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'catid must be less than relatedid';
end if;
end;
|
delimiter
You also need to change the delimiter. Otherwise the DB thinks your trigger definition ends at the first ; which would be incomplete.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.