text:
Q: Using one Repository Inside Another I am new to DDD, I have a Partner aggregate which has an User reference.
The User object itself is another Aggregate.
Since not all users has to be referenced in the Partner object, the User object is an aggregate root.
The Partner is an aggregate root as well.
First:
Would my design be wrong with one aggregate root inside another?
Second:
If the design is right, would it be a bad practice to use one Repository inside another to persiste the Partner? (UserRepository inside PartnerRepository)
Obs: I am not using any ORM framework.

A:
I am new to DDD...

I'll be answering this from a DDD standpoint, not OOP (Object Oriented Programming).

First: Would my design be wrong with one aggregate root inside
  another?

It wouldn't follow the general guidelines of Domain-Driven Design.  If you want to reference one aggregate root from another, you would reference it by id.

Second: If the design is right, would it be a bad practice to use one
  Repository inside another to persiste the Partner? (UserRepository
  inside PartnerRepository)

Again if following the guidelines of DDD, you wouldn't do this, you would persist each aggregate separately using separate repositories.
Here's a link to an article by Vaughn Vernon, possibly the second greatest figure in the field of DDD to explain better.

A:
First: Would my design be wrong with one aggregate root inside another?

Yes.

AGGREGATE
  A cluster of associated objects that are treated as a unit for the purpose of data changes.  External references are restricted to one member of the aggregate, designated as the root.  A set of consistency rules applies within the aggregate's boundaries.

Eric Evans, Domain Driven Design
The problem your design faces is this: the Partner aggregate cannot protect its own invariant if the User aggregate is allowed to modify the same state independently.
When, in your design, you assert that X is an aggregate, you are making two claims

*

*The validity of any change to X can be determined without consulting any external state.

*The validity of any external change can be determined without consulting the state of X.

That's the aggregate boundary -- changes on the outside don't need to look inside, changes inside don't need to look outside.
Therefore, nesting aggregates is a contradiction.
Another way of expressing the same idea: if one aggregate root is inside another, then you have an aggregate (the Partner aggregate) which has two roots (the Partner entity, and the User entity), which is precisely the situation that the aggregate pattern is intended to avoid.
Possible remedies:
One is that the User entity really is part of the Partner aggregate.  Every change to the user is supposed to be managed by the Partner.  You move the User back into the partner aggregate, and prevent your implementation from accessing it except by issuing commands to the aggregate root.
Another is that the User entity isn't part of the Partner aggregate.  Then you eliminate the direct reference in the Partner; that might mean eliminating the reference completely (if the business rules of Partner don't depend upon user at all), or having a reference to the User identifier, and business rules that check the identifier without following it (in other words, your rules might check that an id reference is null/not null, or is/is not a member of a collection).  If you think about it, the Partner aggregate can't even tell if the User it is referencing exists.
A third is the discovery of a new entity in your model, that includes the part of User that the Partner aggregate actually uses for validation.  This might be a snapshot of User state, or it might be a refactoring of User into multiple pieces.

A:
First: Would my design be wrong with one aggregate root inside
  another?

I doubt it. For example, User can be the aggregate root of some domain called user management and UserProfile the aggregate root of some other domain called user profiles, and probably there should be a 1:1 association between both domain objects.

Second: If the design is right, would it be a bad practice to use one
  Repository inside another to persiste the Partner? (UserRepository
  inside PartnerRepository)

You should ensure that there's a clear separation of concerns and you follow the single responsibility principle. That is, a repository can handle a single domain object and injecting a repository inside of other one opens the door to handle related or unrelated domain objects.
My advise is you should represent transactions in your domain services, and there you can inject as many repositories as you need.


text:
Q: Wrong RTTI Visibility Information and missing attributes I have in essence the following class in my application
TCategory = class(TAbstractionTreeItem)
  private
    fName: String;
    fParent: Integer;
    fComment: String;
  public
    procedure Default; override;
  protected
    procedure Validate(Validation: TValidation); override;
  published
    [AbstractionField]
    property Name: string read fName write fName;
    [AbstractionField]
    property Parent: Integer read fParent write fParent;
    [AbstractionField]
    property Comment: String read fComment write fComment;
  end;

When I now try to get information about through advanced RTTI in Delphi XE, I get as visibility information for the published properties a result that tells me they are only public and the attributes that I added are not showing up at all.
What is going on there? I already tried to validate that it is the right class that I try to analyse and that the unit that belongs to it is recompiled, when changes occur. That does not seem to be the problem.

A: In order to get your code provided to compile, i changed the following:
AbstractionField = class(TCustomAttribute)
end;

TCategory = class(TObject)
  private
    fName: String;
    fParent: Integer;
    fComment: String;
  public
    procedure Default;
  protected
    procedure Validate(Validation: Integer);
  published
    [AbstractionField]
    property Name: string read fName write fName;
    [AbstractionField]
    property Parent: Integer read fParent write fParent;
    [AbstractionField]
    property Comment: String read fComment write fComment;
  end;

Then I wrote the following code to query the visibility of the properties:
var
 C : TRttiContext;
 T : TRttiType;
 P : TRttiProperty;

begin
  T := C.GetType(TCategory.ClassInfo);
  for P in T.GetProperties do
  begin
     Memo1.Lines.Add(P.Name + ' ' +
                     GetEnumName(TypeInfo(TMemberVisibility),ord(P.Visibility)) );
  end;
end;

My Results where (As Expected):
Name mvPublished
Parent mvPublished
Comment mvPublished

I am using Delphi XE as well, your going to have to provide more code so we can duplicate the problem.
Also make sure you check your warnings for:
[DCC Warning] UnitName.pas(LineNum): W1025 Unsupported language feature: 'custom attribute'
This is the only way to identify if an attribute is incorrectly entered and unable to be found by the compiler.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When building WebTRC XCFramework for iOS I get "A library with the identifier 'ios-arm64' already exists." I'm trying to build an XCFramework for our use of WebRTC and am using an Apple Silicon Mac (Mac Studio). I've downloaded the WebRTC stuff from Google and installed all their tools and used their tools to generate an Xcode project version. I can run Xcode and build a framework library. I've set the "arch" in Xcode to be the $ARCHS_STANDARD plus x86_64 (for simulator use by our developers still using Intel based Macs)
Using the documentation at https://developer.apple.com/documentation/xcode/creating-a-multi-platform-binary-framework-bundle I create an archive for iOS and one for iOS Simulator
% xcodebuild archive -project all.xcodeproj -scheme framework_objc_signed_bundle -destination "generic/platform=iOS" -archivePath "archives/WebRTC"
% xcodebuild archive -project all.xcodeproj -scheme framework_objc_signed_bundle -destination "generic/platform=iOS Simulator" -archivePath "archives/WebRTC_simulator" ONLY_ACTIVE_ARCH=NO SKIP_INSTALL=NO BUILD_LIBRARY_FOR_DISTRIBUTION=YES
First issue is it doesn't seem to create an X86 version for simulator based on running "% lipo -archs" on the actual binary library in the WebRT_simulator.framework, which only shows "arm64", though I don't know if that is valid.
My question is really this one:
Then when I try and create the XCFramework using
% xcodebuild -create-xcframework -archive archives/WebRTC.xcarchive -framework WebRTC.framework -archive archives/WebRTC_simulator.xcarchive -framework WebRTC.framework -output WebRTC.xcframework
I end up with this: A library with the identifier 'ios-arm64' already exists.
I found a post asking about this result (on the Apple Developer Forums) but unfortunately it linked to another post for an answer and that post no longer exists.
What am I doing wrong and how can I go about creating the WebRTC XCFramework that runs on device, and both architectures simulators?
Following the Apple docs ends up with an error that I don't understand.  I've tried various searched on SO and in my search engine of choice but have not gotten anywhere.


text:
Q: How can I create code blocks in my own language after Lexing In Python? I'm creating a new language in Python and have run into a problem.
Let's say I have this code.
if (1=1){
    print('Hi')
};

Note: The above is the language I'm creating
So, I Lex it into:
[{type:"IF" , value:"if"} , {type:"{" , value:"{"} , {type:"PRINT" , value:"print"} , {type:"(" , value:"("} , {type:"'" , value:"'"} , {type:"ID" , value:"HI"}, {type:"'" , value:"'"} , {type:";" , value:";"} {type:"}" , value:"}"} , {type:";" , value:";"}]

The way I transpile it into Python takes it one statement at a time into a function. I get the statement by using the ';' tokens as a full stop.
size = len(lexer) #TheTokens
idx_list = [idx + 1 for idx, val in
   enumerate(lexer) if val.type == ';']
res = [lexer[i: j] for i, j in
   zip([0] + idx_list, idx_list +
   ([size] if idx_list[-1] != size else []))]

I then use a for loop to run through every statement and transpile them one by one.
Here's where the problem starts. The Loops and Conditions have codeblock and my code separates all the statements inside the code block as well. I want the whole for loop, or the whole if condition to be taken as one statement.
I got a pretty basic fix by making all the semicolons inside a code block comas, separating the statements and turning the code block commas into semicolons again. But that doesn't work for nested code blocks.
What should I do?

A: Once you have a list of tokens, the next step is to parse them and build a nested version of the tokens in some form.
Parsing works according to a 'grammar' that describes how tokens combine to form bigger structures.
One way of writing down a grammar is EBNF:
https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form
For your example above, a grammar like this might work:
statement = if_statement | print_statement
print_statement = PRINT ( ' ID ' ) ;
if_statement = IF ( condition ) block ;
condition = ... define if condition syntax
block = { statement_list }
statement_list = statement | statement statement_list

This is just a notation for the grammar, not code to parse with, but the important thing is the statement_list definition, that allows a statement_list to be a single statement, or a statement followed by another statement_list.
To write a parser from scratch to implement this grammar, the simplest way is to use a recursive descent parser:
https://en.wikipedia.org/wiki/Recursive_descent_parser
That wiki page has an example of C code to parse a mini language.
This looks at the tokens one at a time, and based on what the next token is (or next several tokens are), it starts parsing and remembers partly constructed pieces as it goes along. So for your example program, if a valid program is made of a list of statements, we know the next token has to be 'IF' or 'PRINT'. The parser sees the 'IF' token first, and knows it must be parsing an if statement.
Then it keeps going, expecting to find brackets and a condition. Once it goes past the first '{' it knows any statement can come next, so it looks to see if the next token is a 'PRINT' or an 'IF' and parses the print statement next. Then it sees the last '}' and completes the earlier IF statement, which now knows it has the PRINT statement inside its block.
This method of parsing means that your first IF statement can contain another IF statement, which can contain yet another IF statement, with a PRINT inside that.
You can then extend the language with more statements like FOR, WHILE etc.
If the grammar gets big and complex, there are tools to build parsers directly from grammars. For python I have used one called PLY, which you can get here:
https://github.com/dabeaz/ply
This means you put chunks of python comments into special functions that describe the grammar in a form very similar to EBNF. Ply then works out what order to call the functions in automatically, and in each function you write python that does something when a complete if statement is seen, or a complete print statement etc.

A: What I am doing with my language is to create the abstract syntax tree from my parsed code. I do not even bother with real lexing or anything too complicated.
For code blocks I use simple stacks to enter and exit them. I use collections.deque() for that.
You write the equivalent Python code, get the AST from them and examine the resulting tree. In this way you quickly learn how Python is interpreted. Then you know how to write Python using abstract Syntax trees. My compiler walks through my code in a tree fashion, therefore it is pretty easy to create the AST while simultaneously parsing the code.
After the AST is completed you can compile it into Python byte code and execute using exec or you can even save it as *.pyc and start it as a regular Python or import it.
This guarantees you maximal possible speed. Your language does not translate to Python but compiles to it and it goes directly to the Python Virtual Machine.
From the AST you can then write Python code if you really want, although this is a step in a decompilation, and although not difficult, it can get complicated.
So, I advise you to use a while loop with stacks for entering and exiting blocks and subblocks. How you tokenize the code is up to you. If you want you can build the AST during the traversal using the ast module, and then compile() it. If you need interpreting you exec it at the line or, in case you are in the block,  after block is closed, i.e. after block stack is empty again. Writing Python while walking your code would be easier, I admit, but you will be losing speed.
To simplify things I created my own classes to represent blocks, subblocks and conditions. E.g. a condition can have if, elif and else subblocks. A function or a loop is considered a block, and anything nested is a subblock. The objects in questions contain methods that translate them to AST chunks. One line has its own object, I call it a Command(), and comments have their class too, but they are just ignored during the AST creation. So I fill-in my objects with my code according to the code's context, inside my loop, and then ask them to parse it further and get me the AST chunk to add it to the tree. And bang. Python byte code is a result.
Ow, yes, in block classes I keep track of the line being interpreted and a token inside it. So if I detect a syntax error inside my code I can report it.


text:
Q: Group coordinator lookup failed: The coordinator is not available i use zipkin with kafka
zipkin.collector.kafka.bootstrap-servers: 172.16.5.147:9092,172.16.5.146:9092,172.16.5.145:9092

and work log:
2018-10-12 11:32:27.005 DEBUG 20073 --- [pool-5-thread-1] o.a.k.c.c.i.AbstractCoordinator          : [Consumer clientId=consumer-1, groupId=zipkin] Sending FindCoordinator request to broker 172.16.5.146:9092 (id: 999 rack: null)
2018-10-12 11:32:27.005 DEBUG 20073 --- [pool-5-thread-1] o.a.k.c.NetworkClient                    : [Consumer clientId=consumer-1, groupId=zipkin] Recorded API versions for node 998: (Produce(0): 0 to 3 [usable: 3], Fetch(1): 0 to 5 [usable: 5], ListOffsets(2): 0 to 2 [usable: 2], Metadata(3): 0 to 4 [usable: 4], LeaderAndIsr(4): 0 [usable: 0], StopReplica(5): 0 [usable: 0], UpdateMetadata(6): 0 to 3 [usable: 3], ControlledShutdown(7): 1 [usable: 1], OffsetCommit(8): 0 to 3 [usable: 3], OffsetFetch(9): 0 to 3 [usable: 3], FindCoordinator(10): 0 to 1 [usable: 1], JoinGroup(11): 0 to 2 [usable: 2], Heartbeat(12): 0 to 1 [usable: 1], LeaveGroup(13): 0 to 1 [usable: 1], SyncGroup(14): 0 to 1 [usable: 1], DescribeGroups(15): 0 to 1 [usable: 1], ListGroups(16): 0 to 1 [usable: 1], SaslHandshake(17): 0 [usable: 0], ApiVersions(18): 0 to 1 [usable: 1], CreateTopics(19): 0 to 2 [usable: 2], DeleteTopics(20): 0 to 1 [usable: 1], DeleteRecords(21): 0 [usable: 0], InitProducerId(22): 0 [usable: 0], OffsetForLeaderEpoch(23): 0 [usable: 0], AddPartitionsToTxn(24): 0 [usable: 0], AddOffsetsToTxn(25): 0 [usable: 0], EndTxn(26): 0 [usable: 0], WriteTxnMarkers(27): 0 [usable: 0], TxnOffsetCommit(28): 0 [usable: 0], DescribeAcls(29): 0 [usable: 0], CreateAcls(30): 0 [usable: 0], DeleteAcls(31): 0 [usable: 0], DescribeConfigs(32): 0 [usable: 0], AlterConfigs(33): 0 [usable: 0], AlterReplicaLogDirs(34): UNSUPPORTED, DescribeLogDirs(35): UNSUPPORTED, SaslAuthenticate(36): UNSUPPORTED, CreatePartitions(37): UNSUPPORTED)
2018-10-12 11:32:27.006 DEBUG 20073 --- [pool-5-thread-1] o.a.k.c.c.i.AbstractCoordinator          : [Consumer clientId=consumer-1, groupId=zipkin] Received FindCoordinator response ClientResponse(receivedTimeMs=1539315147006, latencyMs=1, disconnected=false, requestHeader=RequestHeader(apiKey=FIND_COORDINATOR, apiVersion=1, clientId=consumer-1, correlationId=9), responseBody=FindCoordinatorResponse(throttleTimeMs=0, errorMessage='null', error=COORDINATOR_NOT_AVAILABLE, node=:-1 (id: -1 rack: null)))
2018-10-12 11:32:27.006 DEBUG 20073 --- [pool-5-thread-1] o.a.k.c.c.i.AbstractCoordinator          : [Consumer clientId=consumer-1, groupId=zipkin] Group coordinator lookup failed: The coordinator is not available.
2018-10-12 11:32:27.006 DEBUG 20073 --- [pool-5-thread-1] o.a.k.c.c.i.AbstractCoordinator          : [Consumer clientId=consumer-1, groupId=zipkin] Coordinator discovery failed, refreshing metadata
2018-10-12 11:32:27.104 DEBUG 20073 --- [pool-5-thread-1] o.a.k.c.NetworkClient                    : [Consumer clientId=consumer-1, groupId=zipkin] Sending metadata request (type=MetadataRequest, topics=zipkin) to node 172.16.5.146:9092 (id: 999 rack: null)
2018-10-12 11:32:27.104 DEBUG 20073 --- [pool-5-thread-1] o.a.k.c.NetworkClient                    : [Consumer clientId=consumer-1, groupId=zipkin] Using older server API v4 to send METADATA {topics=[zipkin],allow_auto_topic_creation=true} with correlation id 10 to node 999
2018-10-12 11:32:27.106 DEBUG 20073 --- [pool-5-thread-1] o.a.k.c.Metadata                         : Updated cluster metadata version 4 to Cluster(id = ywLcZa2hRTCECJAdzcgMKg, nodes = [172.16.5.146:9092 (id: 999 rack: null), 172.16.5.145:9092 (id: 998 rack: null), 172.16.5.147:9092 (id: 1000 rack: null)], partitions = [Partition(topic = zipkin, partition = 5, leader = 999, replicas = [999,998,1000], isr = [999,998,1000], offlineReplicas = []), Partition(topic = zipkin, partition = 0, leader = none, replicas = [1000,998,999], isr = [], offlineReplicas = []), Partition(topic = zipkin, partition = 1, leader = 998, replicas = [998,999,1000], isr = [998,999,1000], offlineReplicas = []), Partition(topic = zipkin, partition = 2, leader = 999, replicas = [999,1000,998], isr = [999,1000,998], offlineReplicas = []), Partition(topic = zipkin, partition = 3, leader = 1000, replicas = [1000,999,998], isr = [1000,999,998], offlineReplicas = []), Partition(topic = zipkin, partition = 4, leader = 998, replicas = [998,1000,999], isr = [998,1000,999], offlineReplicas = [])])

and loop log...
Can anyone tell me what is the reason?
kafka-server: 0.11.0
kafka-client: 1.0.1
zipkin: 2.10.4

A: It is indeed a cluster problem. There is a problem with the __consumer_offsets topic data of kafka. It is good to restart kafka after deleting.


text:
Q: Android- developing applications, do you need license to buy? Do you need any license to buy for developing android applications?

A: Developing is free (apart from your time / tools etc).
Publishing will require you to have a developers account, which I believe is around $25.

A: Go there to create your Google Developers Account. It will cost you 25$ to be able to publish your softwares on the Android Market.


text:
Q: Hosting Service Stack at root I don't get this "If you want to host ServiceStack at root path (/), you should use this configuration:".
What do you mean by root, in terms of setup of the service.  What's the use case for example?

A: The ServiceStack's Hello World example explains when you want to do this. Basically it's whether you want to host ServiceStack services from the root path, e.g http://hostname/ or at a sub path instead, e.g: http://hostname/api/.


text:
Q: Sql query for differnt rows as a one row I have a query which is giving me the following output:
AcctName                 budget
Gross Salaries           232332
Basic Salaries           23123
Local Salaries           2312312
Local Travel             23424
country Travel           32242
Health care supplies     234234
Goods Supplies           3243242

You can see in this table I have three common names like Salaries, Travel, Supplies and their budget. I want query which can give me following result:
AcctNAme      Budget
Salaries       232323423
Travel         323232332
Supplies       232323232

The budget should be the sum of salaries, travel and supplies.
EDIT:
SELECT T1.[AcctName], T0.[DebLTotal]
FROM (VALUES('Salaries'),('Travel'),('Supplies')) TT1(AcctName)
LEFT JOIN(
SELECT CASE WHEN T1.[AcctName] LIKE '%Salaries%' THEN 'Salaries'
            WHEN T1.[AcctName] LIKE '%Travel%' THEN 'Travel'
            WHEN T1.[AcctName] LIKE '%Supplies%' THEN 'Supplies' END AS ActNAme,
       SUM(T0.[DebLTotal]) AS budget
FROM OBGT T0
   INNER JOIN OACT T1 ON T0.[AcctCode] = T1.[AcctCode]
   INNER JOIN OBGS T2 ON T0.[Instance] = T2.[AbsId]
GROUP BY CASE WHEN T1.[AcctName] LIKE '%Salaries%' THEN 'Salaries'
              WHEN T1.[AcctName] LIKE '%Travel%' THEN 'Travel'
              WHEN T1.[AcctName] LIKE '%Supplies%' THEN 'Supplies' END) TT2 ON TT1.[AcctName] = TT2.[AcctName]

A: This should work just fine.
select 'Salaries' as AcctName, (select sum(budget)
                                  from myTable
                                 where lower(AcctName) like '%salaries%') as Budget
union
select 'Travel', (select sum(budget)
                    from myTable
                   where lower(AcctName) like '%travel%')
union
select 'Supplies', (select sum(budget)
                      from myTable
                     where lower(AcctName) like '%supplies%')

You can test it here
I use lower() to make a case-insensitive comparison. Many times this is not necessary, depending on how you defined your database Collation.

A: You can use conditional grouping like:
DECLARE @t TABLE
    (
      AcctName VARCHAR(100) ,
      budget INT
    )

INSERT  INTO @t
VALUES  ( 'Gross Salaries', 232332 ),
        ( 'Basic Salaries', 23123 ),
        ( 'Local Salaries', 2312312 ),
        ( 'Local Travel', 23424 ),
        ( 'country Travel', 32242 ),
        ( 'Health care supplies', 234234 ),
        ( 'Goods Supplies', 3243242 )

SELECT CASE WHEN AcctName LIKE '%Salaries%' THEN 'Salaries'
            WHEN AcctName LIKE '%Travel%' THEN 'Travel'
            WHEN AcctName LIKE '%Supplies%' THEN 'Supplies'
            ELSE 'Other' END AS AcctNAme,
       SUM(budget) AS budget
FROM @t
GROUP BY CASE WHEN AcctName LIKE '%Salaries%' THEN 'Salaries'
              WHEN AcctName LIKE '%Travel%' THEN 'Travel'
              WHEN AcctName LIKE '%Supplies%' THEN 'Supplies'
              ELSE 'Other' END

EDIT:
SELECT t.AcctNAme, l.budget
FROM (VALUES('Salaries'),('Travel'),('Supplies')) t(AcctNAme)
LEFT JOIN(
SELECT CASE WHEN AcctName LIKE '%Salaries%' THEN 'Salaries'
            WHEN AcctName LIKE '%Travel%' THEN 'Travel'
            WHEN AcctName LIKE '%Supplies%' THEN 'Supplies' END AS AcctNAme,
       SUM(budget) AS budget
FROM @t
GROUP BY CASE WHEN AcctName LIKE '%Salaries%' THEN 'Salaries'
              WHEN AcctName LIKE '%Travel%' THEN 'Travel'
              WHEN AcctName LIKE '%Supplies%' THEN 'Supplies' END) l ON t.AcctNAme = l.AcctNAme

A: You use REVERSE AND RIGHT function to reverse ActName
Example:
SELECT RIGHT(S, CHARINDEX(' ', REVERSE(S)))FROM(
SELECT 'Health care supplies' AS S) AS A

-- Result

supplies

You can try this code:
SELECT DISTINCT *,
   SUM(Budget) OVER(PARTITION BY AcctName) AS Budget
FROM (
   SELECT
      RIGHT(AcctName, CHARINDEX(' ', REVERSE(AcctName))) AS AcctName,
      Budget
   FROM Your_Table) AS A


text:
Q: Is there a better method than using Map STL C++? I am creating a genetic algorithm that classifies set of data for which I need to generate random sequences of 1s,0s and 2s for defining a rule
2 represents it being in 2 states a 1 and 0. I am trying to use Map STL for mapping the random set of rules generated and the output for each rule. I need the Map key to be dynamic/ changing every iteration/generation to be filled by new population of rules.
I realise I have option of using pointers which complicates my code and will have readability issue.
The other option I know about is copying the key elements and value and deleting it so it can be replace by the new rule.
So, My question is:
1). Is it better to use vector and my own mapping algorithm? The only problem being is I want to be efficient and fast as I will be dealing with 2000 or more data.
2). Are there any other STL which I can use no libraries that I need to download pls.?
3). Shall I just use Map and keep reseting the elements in the map each time so I can initialise them again?
which method would be effective?
Open to any other suggestion or advice.

A: If you don't want data to be in sorted order you could consider std::unordered_map<>.
Have a look at this for some benchmarks.


text:
Q: Flask: How to filter and display different CRUD tables with pagination? In my Flask application, I have 10+ CRUD tables that I want to display one at a time using a Select dropdown. I have found and followed a lot of tutorials that helped me out in implementing one single CRUD table, but I haven't found a solution when it comes to the multiple tables.
In my current solution, I have managed to only make filtering and displaying tables work, but I am facing issues with the rest of the functionality like,

*

*Unable to work the pagination, for any table other than default.

*Setting up default table to be displayed

*Editing/Deleting for specific tables

*Rerouting back to the same table after editing/deleting

At this point, I had to hard code the table names in my code, but I want this all to be dynamic. How can I make it all work dynamically?

app.py
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from forms import Dropdown_Form

app = Flask(__name__)
app.secret_key = "Secret Key"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///site.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)

class Table_A(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.Integer)
    name = db.Column(db.String(300))

    def __init__(self, code, name):
        self.code = code
        self.name = name

class Table_B(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.Integer)
    name = db.Column(db.String(300))

    def __init__(self, code, name):
        self.code = code
        self.name = name

@app.route("/", methods=["GET", "POST"])
def index():
    form = Dropdown_Form()

    page = request.args.get("page", 1, type=int)
    table = Table_A.query.paginate(page=page, per_page=5)

    if request.method == "POST":
        table = globals()[request.form.get("table_name")]

        page = request.args.get("page", 1, type=int)
        table = table.query.paginate(page=page, per_page=5)
        return render_template("index.html", form=form, table=table)

    return render_template("index.html", form=form, table=table)

@app.route("/insert", methods=["GET", "POST"])
def insert():

    if request.method == "POST":

        code = request.form.get("code")
        name = request.form.get("name")
        my_data = Table_B(code, name)

        db.session.add(my_data)
        db.session.commit()

        flash("Data inserted successfully.")

        return redirect(url_for("index"))

@app.route("/update", methods=["GET", "POST"])
def update():

    if request.method == "POST":

        my_data = Table_B.query.get(request.form.get("id"))

        my_data.code = request.form.get("code")
        my_data.name = request.form.get("name")

        db.session.commit()
        flash("Data updated successfully.")

        return redirect(url_for("index"))

@app.route("/delete/<id>/", methods=["GET", "POST"])
def delete(id):

    my_data = Table_B.query.get(id)
    db.session.delete(my_data)
    db.session.commit()
    flash("Data deleted successfully.")

    return redirect(url_for("index"))

if __name__ == "__main__":
    db.create_all()
    app.run(port=5000, debug=True)

forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, SubmitField #, PasswordField, SubmitField, BooleanField

class Dropdown_Form(FlaskForm):
    table_name = SelectField("Table Name", choices=[("Table_A","Table A"), ("Table_B", "Table B")])
    submit = SubmitField("Submit")

templates\base.html
<!DOCTYPE html>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %}</title>

    {% block body %}
    {% endblock %}

templates\index.html
{% extends 'base.html' %}
{% block title %} Home {% endblock %}
{% block body %}

        <legend class="border-bottom mb-4">Manage Tables</legend>

        <form method="POST" action="">
            {{ form.hidden_tag() }}

                    {{ form.table_name(class="form-control form-select form-control-sm") }}

                    {{ form.submit(class="btn btn-primary btn-sm btn-block") }}

        </form>

                <button type="button" class="btn btn-sm btn-primary float-left" data-toggle="modal" data-target="#mymodal">Add Data</button>

                    Id
                    Code
                    Name
                    Action

          {% for row in table.items %}

                {{ row.id }}
                {{ row.code }}
                {{ row.name }}

                Edit
                Delete

Update Information

                    <form action="{{url_for('update')}}" method="POST">

                        Code:
                        <input type="hidden" name="id" value="{{row.id}}" />
                        <input type="text" class="form-control" name="code" value="{{row.code}}" />

                        Name:
                        <input type="text" class="form-control" name="name" value="{{row.name}}"/>

                        <button class="btn btn-primary" type="submit">
                            Update
                        </button>

                    </form>

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

          {% endfor %}

        {% for page in table.iter_pages() %}
            {% if page %}
                {% if table.page == page %}
                    {{ page }}
                {% else %}
                    {{ page }}
                {% endif %}
            {% endif %}
        {% endfor %}

Add Data

                <form method="POST" action="{{url_for('insert')}}">

                        Code:
                        <input type="text" class="form-control" name="code" required="1"/>

                        Name:
                        <input type="text" class="form-control" name="name" required="1"/>

                        <button class="btn btn-primary" type="submit">
                            Add Data
                        </button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                          Close
                        </button>

                </form>

{% endblock %}

A: Are you making a todo list app. if you want to implement things like searching for something in the table , pagination , or show these much entries then you can use datatables. it is a jquery library which will handle these functionalities.
Go and follow the instructions. It is super easy.


text:
Q: Triple integrals (Find volume): The solid bounded by the sphere $r = 2 cos$ $ \phi $ and the hemisphere $r = 1$, $z$ $\ge$ $0$ Here is the exact question:
https://imgur.com/a/cBQC8su!
My particular question regards the range of $\phi$; $\phi$ certainly lives between  $0$ $\le$ $\phi$ $\le$ $\frac {\pi}{2}$.
$\rho = 1$ intersects with $ \rho = 2cos\phi$ at $\frac {\pi}{3}$.
I thought that the range of $\phi$ would be  $0$ $\le$ $\phi$ $\le$ $\frac {\pi}{2}$, where $0$ $\le$ $\phi$ $\le$ $\frac {\pi}{3}$ to $\frac {\pi}{3}$ $\le$ $\phi$ $\le$ $\frac {\pi}{2}$. Any helpful tips?
The book lists the answer as $\frac {5\pi}{12}$.

A: The intersection $S$ of the two unit balls is a lens shaped object whose volume can easily be computed by the "washer method".  One obtains
$${\rm vol}(S)=2\cdot\int_{1/2}^1\pi(1-r^2)\>dr={5\pi\over12}\ .$$


text:
Q: Select value IN DataSet Is there any way to use a DataSet as an IN 'value'?
For instance, I have a query that loads a DataSet with options that the user can choose between when doing their work.  The problem is, the query that loads the DataSet is very long and arduous (selects and table joins inside of other selects and other table joins, etc. etc. etc.), so I want to be able to fill the DataSet exactly one time, and just reference the DataSet when running other queries.
Now, I've gotten it to work by calling each row, getting the value from the row, and appending it to the query.
//GetAvailableOptions is just the long and complicated query
//Code simplified just for example sake
DataSet ds = GetAvailableOptions();
string str_qry = "select from TestFile where (";
foreach(DataRow dr in ds.Tables[0].Rows)
{
    string str_test = dr[0].ToString();
    str_qry += dr[0].ToString() + " or ";
}

So the resulting query looks like this:
select from TestFile where (TestField = 'A' or TestField = 'B' or ... TestField = 'Z')

But I was wondering if I couldn't make it faster by doing the following:
DataSet ds = GetAvailableOptions();
string str_qry = "select from TestFile where TestField in " + ds.Tables[0].Columns[0];

But I can't get it to work.  Is this possible?  Is my logic sound?  The name of the Column I'm trying to reference from the DataSet is the same as the field I'm trying to load (in this example, TestField).
Another, I'm thinking more subjective question is, how much faster (if at all?) would it be if this would work?  Or even with the joins and multiple queries, would it be faster to pull from there instead of looping through and appending?  Or perhaps if there's another way I haven't thought of?  Can someone share their experience?

A: This sounds like something better done as a stored procedure.  I assume that the DataSet you are creating is populated from a stored procedure?
Also, the type of dynamic SQL you are generating is not a best practice for a number of reasons, chief among them security, you open yourself up to SQL injection.

A: One thing though you mention the data that returns the columns you are after is a complicated join, and if so can this actually all be done on the server?  So put together a new stored proc that retrives the inital complicated user data, and then in turn run the select you are constructing on the client on the server?


text:
Q: setFormula then get and set Value - is this the best way? I have a growing dataset on a google sheet with which I need to run some complex filters/queries/vlookups on. However I only need to do this daily as the new data arrives. The number of complex formulas is starting to slow the spreadsheet to a grinding halt, particularly with our woeful broadband connection.!
I therefore came up with a workaround of using GAS to set the formula in a cell, then to get the Value and then to set the Value, knowing that GAS doesn't run the spreadsheet functions natively (as per VBA). As I have already worked up the filters and vlookups on the sheets I need, I didn't go into scripting the formulas to achieve the same thing.
Here is a simplified version of the code:
function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName('Sheet1');
  var rng = sh.getRange('B11');
  rng.setFormula('=sum(filter(C2:E5,A2:A5="Bob"))');
  var val = rng.getValue();
  rng.setValue(val);
}

In my production spreadsheet I can have @ 300 formulas on each of 30 sheets, so if these are all pinging away at the dataset I get lengthy periods of the grey progress bar. (In essence the formulas are filtering/summing or counting daily data to weekly data) My example above shows everything happening on one sheet.
Wondered if there was a better/different way of doing this?
Thanks
Tim

A: Well, I have not come up with anything better so will post my solution. Two scripts. First one checks that the user actually want to update their values, if they say yes, then checks with the user again and shows them the date range it will update. Then runs the second script, which in simple terms just applies a formula to a cell then copies the value generated and pastes the value. On testing with full data load, spreadsheet does no "waiting/progress grey box" at all so solves my issue.
function runWriteBehavs() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sy = ss.getSheetByName("summary");
  //gets last row in column B - data is contigious
  var BVals = sy.getRange("B1:B").getValues();
  var BLast = BVals.filter(String).length;
  var rowBeh = BLast + 1;
  var lastDate = sy.getRange("A" + rowBeh).getValue();
  var lastEndDate = new Date(lastDate.getTime()+6*3600000*24);;
  //formats dates
  lastDate = Utilities.formatDate(new Date(lastDate), "GB", "dd/MM/yyyy");
  lastEndDate = Utilities.formatDate(new Date(lastEndDate), "GB", "dd/MM/yyyy");
  //message box for confirmation
  var output = Browser.msgBox("This script will run the summaries for the week:\\n" + lastDate + " - " + lastEndDate + "\\n Are you really sure you want to continue?",Browser.Buttons.YES_NO);

  if ( output == "yes" ) {
    //calls main update script
    writeBehavs();
  }

}

//Needs to be run once all data is entered
function writeBehavs() {
  //get variables
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var db = ss.getSheetByName("database");
  var sy = ss.getSheetByName("summary");
  var sL = ss.getSheetByName("lists");
  //gets number of behaviours, a counta() of list on sheet
  var bCount = sL.getRange("H1").getValue();
  //gets column listing hard coded on sheet
  var bCol = sL.getRange("H2:H30").getValues();
  //gets last row in column B - data is contigious
  var BVals = sy.getRange("B1:B").getValues();
  var BLast = BVals.filter(String).length;

  //for each number on behaviour count
  for (var i=0; i<bCount; ++i) {
  //set the column
  var colBeh = [bCol[i]];
  //set the correct row for data entry and start date check
  var rowBeh = BLast + 1;
  //sets correct row for end date check
  var rowBeh2 = rowBeh + 1;

  //gets first empty row in Column from iteration
  var rng = sy.getRange(colBeh+rowBeh);
  //enters the formula in the cell
  rng.setFormula('=iferror(sum(filter(database!$E$2:$E,database!$D$2:$D='+ colBeh + '$1,database!$A$2:$A=lists!$G$2,database!$B$2:$B>=$A' + rowBeh + ',database!$B$2:$B<$A' + rowBeh2 + ')),"0")');
  //captures the value generated by the formula
  var val = rng.getValue();
  //pastes the formula to the cell
  rng.setValue(val);
  //Job Done!
  }

}


text:
Q: On Category O in positive characteristic Let $G$ be a semisimple algebraic group over an algebraically closed field $k$. In the case that $k$ has characteristic 0, there has been intensive study of the BGG category O of representations of the enveloping algebra of the Lie algebra of $G$ (which is also, in this case, the hyperalgebra of $G$). When $k$ is a field of positive characteristic, though, the enveloping algebra and the hyperalgebra are different, and there has been a lot of study of representations of the enveloping algebra. On the other hand, it seems that there has been much less study of representations of the hyperalgebra, perhaps because it is more complicated (for example, it is not finitely generated).
So let's now assume that the characteristic of $k$ is positive. A seminal paper of Haboush, "Central Differential Operators of Split Semisimple Groups Over Fields of Positive Characteristic," set up the foundations of category O for hyperalgebras in this setting. More precisely, let $U$ denote the hyperalgebra of $G$. In that paper Haboush defined Verma modules for $U$ (which are defined analogously to the characteristic 0 case) and proved that many of the properties one would expect, including relationships with simple modules and certain "integrality" properties, hold. However, this is just the beginning; there are many questions one could ask about whether or not category O in positive characteristic behaves like category O in characteristic 0. E.g, what is the structure of the blocks in this category? What about the structure of projective generators? Are there translation functors? If so, how do they behave? I.e., how much of the (huge) characteristic 0 story carries over to positive characteristic? Haboush's paper is from 1980, and I haven't been able to find any papers that carry on the study started in the paper -- does anyone know of any?
(As a sidebar, I would note that the hyperalgebra/enveloping algebra dichotomy in positive characteristic is mirrored in the study of quantum groups at roots of 1: the De Concini-Kac algebra is the analog of the enveloping algebra, and the Lusztig algebra is the analog of the hyperalgebra).

A: I'm not sure if this is really an answer, or more a response to David's, since I've not thought about this before. The idea to look for a Beilinson-Bernstein type theorem seems right, but there is an elegant paper of Kashiwara and Lauritzen which shows that $D$-affinity fails for $SL_5$ in all positive characteristics by studying the Grassmannian $\text{Gr}(2,5)$, and considering the local cohomology of the subvariety of planes which intersect a given plane nontrivially. This variety has nontrivial local cohomology in dimension 3. Perhaps a derived Beilinson-Bernstein theorem is the thing to seek then?
On the other hand Lauritzen, Pedersen and Thomsen show that $D$-modules on the flag variety are more straight-forward than you expect from characteristic $0$: they show that the local cohomology sheaves $\mathcal H_Y^c(X)$ (where $Y$ is a Schubert variety in the flag variety $X$ and $c$ is the codimension of the $Y$ in $X$) are simple, and the corresponding local cohomology of Schubert cells (which are the Vermas in the characteristic zero theory) are multiplicity free. In other words "Kazhdan-Lusztig polynomials" in this theory would all be of the form $q^k$.

A: I don't know the answer to your question, but maybe one can venture to guess that
the Beilinson-Bernstein localization picture carries over to this setting? (for the enveloping algebra this is done by Bezrukavnikov-Mirkovic-Rumynin). I would expect that you have a derived equivalence (maybe even underived?) between reps of the hyperalgebra and
D-modules on the flag variety, where D means the full ring of diffops (ie diffops acting on functions, rather than the Weyl algebra, so have all possible divided powers - I think this is explained nicely in papers of Berthelot), or equivalently stratifications (rather than crystals) on the flag manifold.. is there a reason this is obviously naive?
my guess would be that this category behaves very much like D-modules in characteristic zero (unlike the BMR story which is very different in nature). Anyway once you have BB localization your questions should be fairly straightforward to approach (looking at N-equivariant sheaves). Does someone know if this story has been worked out?
The closest work I can think of is the work of Noot-Huyghe in the p-adic setting.. I would expect the story I'm suggesting to be much easier?

A: Maybe I can answer the original question more directly, leaving aside the interesting recent geometric work discussed further in later posts like the Feb 10 one by Chuck: analogues of Beilinson-Bernstein localization on flag varieties and consequences for algebraic groups (Bezrukavnikov, Mirkovic, Rumynin).
The 1979 conference paper by Haboush may be hard to access and also hard to read in detail, but it raises some interesting questions especially about centers of certain hyperalgebras.   I tried to give an overview in Math Reviews:   MR582073 (82a:20049) 20G05 (14L40 17B40)
Haboush,W. J.,
Central differential operators on split semisimple groups over fields of positive
characteristic.
Séminaire d'Algèbre Paul Dubreil et Marie-Paule Malliavin, 32ème
année (Paris, 1979), pp.
35–85, Lecture Notes in Math., 795, Springer, Berlin, 1980.
The hyperalgebra here is the Hopf algebra dual of the algebra of regular functions on a simply connected semisimple algebraic group $G$ over an algebraically closed field of characteristic $p$, later treated in considerable depth by Jantzen in his 1987 Academic Press book Representations of Algebraic Groups (revised edition, AMS, 2003).   After the paper by Haboush, for example, Donkin finished the determination of all blocks of the hyperalgebra.
While the irreducible (rational) representations are all finite dimensional and have dominant integral highest weights (Chevalley), the module category involves locally finite modules such as the infinite dimensional injective hulls (but no projective covers).    The role of the finite Weyl group is now played by an affine Weyl group relative to $p$ (of Langlands dual type) with translations by $p$ times the root lattice.    In fact, higher powers of $p$ make life even more complicated.
The older work of Curtis-Steinberg reduces the study of irreducibles to the finitely many "restricted" ones for the Lie algebra $\mathfrak{g}$.  For these and other small enough weights,  Lusztig's 1979-80 conjectures provide the best
hope for an analogue of Kazhdan-Lusztig conjectures when $p>h$ (the Coxeter number).   The recent work applies for $p$ big enough": Andersen-Jantzen-Soergel, BMR, Fiebig.
Anyway, the hyperalgebra involves rational representations of $G$ including restricted representations of $\mathfrak{g}$, while the usual enveloping algebra of the Lie algebra involves all its representations.   But the irreducible ones are finite dimensional. I surveyed what was known then in a 1998 AMS Bulletin paper.   Lusztig's 1997-1999 conjectures promised more insight into the non-restricted irreducibles and are now proved for large enough $p$ in a preprint by Bezrukavnikov-Mirkovic.   This and their earlier work with Rumynin use a version of "differential operators" on a flag variety starting with the usual rather than divided-power (hyperalgebra) version of the universal enveloping algebra of $\mathfrak{g}$.
To make a very long story shorter, Haboush was mainly looking for the center of the hyperalgebra (still an elusive beast unlike the classical enveloping algebra center, due to the influence of all powers of $p$).   His weaker version of Verma modules may or may not lead further.   But there is no likely analogue of the BGG category for the hyperalgebra in any case.    That category depended too strongly on finiteness conditions and well-behaved central characters.
ADDED: It is a long story, but my current viewpoint is that the characteristic $p$ theory for both $G$ and $\mathfrak{g}$ (intersecting in the crucial zone of restricted representations of $\mathfrak{g}$) is essentially finite dimensional and requires deep geometry to resolve.   True, the injective hulls of the simple $G$-modules with a highest weight are naturally defined and infinite dimensional (though locally finite), but the hope is that they will all be direct limits of finite dimensional
injective hulls for (the hyperalgebras of) Frobenius kernels relative to powers of $p$.   Shown so far for $p \geq 2h-2$ (Ballard, Jantzen, Donkin).   In particular, the universal highest weight property of Verma modules in the BGG category (and others) is mostly replaced in characteristic $p$ by Weyl modules (a simple consequence of Kempf vanishing observed by me and codified by Jantzen).    Then the problems begin, as Lusztig's conjectures have shown.   The
Lie algebra case gets into other interesting territory for non-restricted modules.


text:
Q: React : how to call a function as a state object value? I have a page which contains widgets, each widget contains data and settings used to display the data. When a widget's button is clicked, a sidebar opens (the sidebar component is a child of the page, sibling of the widgets). Within this sidebar, inputs allow to edit the clicked widget data and settings.
What I did to achieve this : I created a state in the parent to both the sidebar and the widgets, when a widget is clicked, this state is setted to contain both the data needed by the sidebar and a callback function to edit them.
What is wrong : The sidebar displays the data from the widget as it should but it does not call the callback function when data is modified.
Here's the code inside the widget component :
(...)
  const updatingInformations = (data, settings, config) => {
    console.log("updating informations : ", data, settings, config);
    data && setWidgetData(data);
    settings && setWidgetSettings(settings);
    config && setWidgetConfig(config);
  };
(...)
<button
          onClick={(e)=>{
            e.preventDefault();
            setSidebarContent({
              type: "widget",
              widget: widget,
              informations: {
                data: widgetData,
                config: widgetConfig,
                settings: widgetSettings,
              },
              callback: updatingInformations,
            });
          }}
          />
(...)

Inside the sidebar component :
(...)
const updatingWidget = (path, newValue) => {
    let stockInfo = { ...sidebarContent.informations };
    stockInfo[path[0]][path[1]][path[2]][path[3]] = newValue;
    console.log(
      "updating widget : ",
      sidebarContent,
      stockInfo[path[0]][path[1]][path[2]][path[3]],
    );
    sidebarContent.callback(null, stockInfo.settings, null);
  };

When the action is triggered (after editing an input), updatingWidget() is called as shown by its console.log() but updatingInformations() isn't called.
What is wrong with my code ?


text:
Q: c++ windows - Disable crash dialog box in a child process I have a program that launches a child process.
When the child process crashes I would like there not to be a debug message box. I would like to do this without writing anything in the child process.
I am running this on windows 7.
In the createProcess function, in the flags parameter I only put CREATE_NEW_CONSOLE.
During my attempts, I put SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX) in the child process and made it crash, there was no dialog box. Now I put the same function call in the parent program before I called create process, and made the child program crash, now the message box appeared.
What should I do differently?

A: have you set CREATE_DEFAULT_ERROR_MODE in process creation flags?


text:
Q: How are RS 485 transceivers implemented? I would like to know how transceivers (which are used to send and receive  differential signals) are implemented. AFAIK the receiver the transmitter (TX) could be something similar to an H bridge. I already took a look at datasheets of some popular transceivers but I could not find any details about the inner working.
EDIT : the term transceiver might be a little to large, by transceiver I mean the ones used for RS 485 (eg : for USB or DMX-512)

A: Assuming the receiver side of a transceiver is boring to you (just a comparator with some hysteresis):
TI's DS9638 (datasheet of the SNLS389D) actually has an equivalent circuit for a single transmitter circuit:

To illustrate what's happening a bit better:

In green, the identical output stages. Look at the left:

*

*Q15 has the job of pulling the output low as soon as the base of Q6 sees super-threshold voltage

*Q18+Q19+Q17 form a current amplifier

*rest of the combination of Q16's collector and Q18 base invert

The whole functionality of the center part is to make sure Q5 and Q6 see the inverse, but at very tightly controlled thresholds.

A: It looks like an Op Amp differential outputs, but it's more like buffered Schottky TTL logic with even higher current drive capability. The main difference is that TTL is asymmetric impedance for more current active low, which this driver is even higher current than TTL and CMOs buffers but more symmetrical low Z.  The  output impedance is ~ 8 Ohms rather >= 300 Ohms on Op Amps (without negative feedback which lowers Op Amps but they are still more current limited than RS485) and also much slower slew rates.
Note the output on the high signal has a series R of 8 Ohms driven by a very low Z Darlington on both outside circuits and the low side collector output has an equivalent Rce giving about the same low source impedance due to higher controlled base current.
The single ended logic Input is more like low power Schottky logic with the same thresholds as all TTL families and HCT CMOS logic, namely 0.8V & 2.0 V worst case with a midpoint threshold of 1.3V like a comparator with a 1.3V reference that may shift with temperature extremes.

*

*the theory and practice that makes RS-422/485 transceivers work better is balanced transmission lines with complementary drive making common-mode noise more rejected and the 100 Ohm differential load makes reflections that cause ringing, less likely to occur.

Looking at the VI characteristics we see;

*

*Vih=2V min and Vil=0.8V max , just like all TTL since day "1" and same for RS-232 inputs, except we use big bipolar drive signals for long cables to make noise look relatively small.

*The output swing is from 0 to 3V making the differential receiver without Tx series R's sometimes added to reduce source ringing to see +/-6V with no loss and +/- 3V differential with series R dividers to match the 100R differential load.

TI also makes a 3.3V logic chip for RS-422/485 work using special CMOS with very low RdsOn unlike 50R in 5V logic and 25R in advanced low voltage logic. Except they add 5R in series to match the performance of the bipolar chip discussed here.


text:
Q: How to spawn a gpg child process from a daemon in nodejs? I can spawn a gpg child process and decrypt a file normally if I just run the app normally.
/app.js
var spawn = require('child_process').spawn;

function decrypt() {
    var gpg = spawn('gpg', ['--no-use-agent', '--passphrase', 'My Passphrase', './test.pdf.asc']);

    gpg.on('close', function (code) {
        console.log(code); // code == 0
    });
}

decrypt();

run the app.js as regular process and can decrypt the file
node app.js

However, when I try to run the app.js as daemon using pm2, upstart, etc... I got the error code (2) and could not decrypt the file
run the app.js a a daemon
pm2 start app.js

A: This is not a Node.js issue. It is related to gnupg tool. In order to run gpg from calling it in your codes or as a cron job, you need a flag '--no-tty'.


text:
Q: File pointer in C# | How to access multiple segments of a large file I have a large file, want to keep 5-6 pointer which divides the file in chunks and gives faster access to any part. Is is possible to achieve in c#.

A: I think Memory-Mapped Files is the closest option to do what you want to do, without much hardwork on your side.
Edit : I assumed you are on .NET 4.0 since this is not available in earlier framework versions. Nice article talking about efficiency you are looking for


text:
Q: How to change commenter links to /user/user_id? I would like to change the commenter links as shown in this screenshot:

In my test plugin at GitHub I have first tried the following code:
define('PROFILE', '%s');

function get_comment_author_link($cid) {
   $uid = get_comment_author($cid);
   return sprintf(PROFILE, $uid->ID, $uid->name);
}

add_action('get_comment_author_link',  'get_comment_author_link');

But then by studying the file wp-includes/comment-template.php I have realized, that the argument to get_comment_author_link is not a comment ID, but a string containing ... and thus I can't use this hook for my purpose (because the user ID can't be found in the hook).
Please advise me a suitable hook or way to change the commenter links.

A: You can use the get_comment_author_link hook, which is part of the get_comment_author_link() template tag, like your question already suggests. Then you only have to get the according user_id, which can be done via the $comment global, and construct the link you want accordingly.
Exemplary usage like shown below:
add_filter( 'get_comment_author_link', 'wpse144835_custom_comment_author_link' );
function wpse144835_custom_comment_author_link( $link ) {
    global $comment;
    $comment_user_id = $comment->user_id;
    // code to create the new link
    return $new_link;
}

Edit:
Responding regarding your questions, the according comment is unfortunately deleted, so this is kind of a informational shortlist now. There is a lot in there, way too much to really answer them, but I give you some additional information:

*

*As we have the global available you can use $comment->comment_author

*As for functions, you can use get_comment_author() or comment_author() depending on your need to return or echo.

*At the Codex: Global Variables you can get an overview about them

*There is the WP_Comment_Query and the Walker_Comment class

*For example at the comment_author codex page is a list of comment related functions

*Additionally I'd suggest you look through the comment-template.php and the comment.php to learn more about all of that

A: Could you try:
 $id = get_comment( get_comment_ID() )->user_id;

I just found this solution while googling, but I don't have an environment to test it out.

A: The output of that function, is an a-tag containing a link to the author profile, its input is definitely an ID.
If you'd like to change the output of that function, you need a filter and you'd need to str_replace the a-tag (or similar method acting on the string). (see where to modify get_comment_author_link()?)
I think the more important question is: what exactly are you trying to achieve here?
In theory the commenters link could be implemented differently in every theme/plugin. It could be done with get_comment_author_url() or retrieved straight from the comment object with get_comment(), or any other way really.
However to alter the output of get_comment_author_link(), see the example above.


text:
Q: dired: M-x find-dired: disable history? I set (setq find-args "-iname ") so that M-x find-dired gives me ... "Run find (with args): -iname " as default. However, it seems to remember its history. Is there a way to disable the history and always start with the default argument "-iname"? I tried to modify find-args-history without success.

A: You have to use the function marius/find-dired each time instead of find-dired, as it is showed in answer. E.g. setup something like this (global-set-key (kbd "C-x g") 'marius/find-dired). It calls (setq find-args "-iname ...") each time before calling find-grep.
EDIT: without renaming:
(setq find-args '("-iname '**'" . 10))
(defadvice find-dired (after eab-find-dired activate)
  (setq find-args '("-iname '**'" . 10)))

for deactivate:
(ad-remove-advice 'find-dired 'after 'eab-find-dired)
(ad-deactivate 'find-dired)

EDIT2: We use after-advice here, see comments.


text:
Q: Why n-1 instead of n in pooled sample variance I am currently self-learning hypothesis testing and am looking at the independent samples t-test whose test statistic involves the pooled sample variance (https://libguides.library.kent.edu/spss/independentttest),
$$ S_p^2 = \frac{(n_1 - 1)S^2_1+(n_2-1)S_2^2}{n_1+n_2-2},$$
where $n_1, n_2$ are the sample sizes of the two samples and $S_1^2, S_2^2$ their respective sample variance. This test assumes that $S_1^2 = S_2^2$.
I understand that the pooled sampled variance is computed as a weighted average with weights $w_i = n_i -1$ for $i=1,2$. However I am unsure why $n_i-1$ is used as a weight instead of $n_i$. I understand that the $n-1$ is used instead of $n$ so that the usual sample variance is an unbiased estimator of the variance (Bessel's correction) but I cannot see why it is necessary for the pooled sample variance since the statistic
$$ \frac{n_1S^2_1+n_2S^2_2}{n_1+n_2} $$
is also an unbiased estimator.
Can anyone explain this to me? Thanks.

A: For a two-sample t test on samples from populations with
the same variance $\sigma^2,$ you have two proposed
variance estimates
$$ S_p^2 = \frac{(n_1 - 1)S^2_1+(n_2-1)S_2^2}{n_1+n_2-2},$$
and
$$ S_a^2 = \frac{(n_1S^2_1+n_2)S^2_2}{n_1+n_2}. $$
For $S_p^2,$ you have found $S_i^2; i=1,2,$ each of which requires computing a sample mean $\bar X_i, 1,2.$ So,
$$ \frac{\nu S_p^2}{\sigma^2} \sim
\mathsf{Chisq(\nu)}.$$ where $\nu = n_1+n_2 - 2.$
For $S_a^2,$ the distribution theory is not so clear.
You say something about $S_a^2$ being unbiased, but that
hardly specifies a distribution. Let's use The same
degrees of freedom $\nu$ as above for an experiment.
Simulation: Begin by looking at $m = 10\,000$ samples
x1 of size $n_1 = 2$ from
$\mathsf{Norm}(\mu_1 = 100, \sigma_1 = 15)$ and x2 of size $n_2=3$ from $\mathsf{Norm}(\mu_2 = 110, \sigma_2 = 15).$
We find the sample variances, the pooled variance estimat
and the average variance estimate. Then we look at the
corresponding chi-squared random variables.
set.seed(2022)
n1 = 2; m=10^5
M1 = matrix(rnorm(n1*m, 100, 15), nrow=m)
v1 = apply(M1, 1, var)
n2 = 3
M2 = matrix(rnorm(n2*m, 110, 15), nrow=m)

v2 = apply(M2, 1, var)

pool = (v1 + 2*v2)/(n1+n2-2)
q.p = (n1+n2-2)*pool/15^2
avg.v = (v1+v2)/(n1+n2) ####
q.a = (n1+n2)*avg.v/15^2

Then we compare the results with the density functions
of the corresponding chi-squared distribution.
For the pooled estimate $S_p^2$ we get a good match,
but for $S_a^2$ the fit is not good.

R code for graphs:
par(mfrow=c(1,2))
 hist(q.p, prob=T, ylim=c(0,.35), col="skyblue2", main="Pooled")
  curve(dchisq(x, n1+n2-2), add=T, lwd=2, col="orange")

 hist(q.a, prob=T, ylim=c(0,.35), col="skyblue2", main="Averaged")
  curve(dchisq(x, n1+n2-1), add=T, lwd=2, col="orange")
par(mfrow=c(1,1))


text:
Q: Cannot access data when tf.data with CSV def get_dataset_from_csv(csv, bs=BATCH_SIZE, val=False, debug=True):

    # Initialize dataset with TFRecords
    dataset = tf.data.Dataset.from_tensor_slices(dict(csv))

    # Decode mapping
    dataset = dataset.map(decode_image, num_parallel_calls=AUTO)

def decode_image(rows):
    image = cv2.imread(rows['file_path']) # cannot access rows['file_path']
    target = rows['target']

    return {"image": image}, target

When I run above code, the following error came out:

Can't convert object of type 'Tensor' to 'str' for 'filename

The type of rows['file_path'] is <class 'tensorflow.python.framework.ops.Tensor'>, so I can't get value during dataset.map. How can I get value of rows['file_path'] during map procedure?


text:
Q: PyQtGraph not working after move from 32 bit to 64 bit I've needed to move from 32bit to 64bit Python, and have run into a problem with pyqtgraph plotting.
Even the simplest examples are displaying the same behaviour (SimplePlot.py for instance, from the examples folder)
Running SimplePlot.py shows the window, but the window is empty except for a squiggle in the top left, which I  am guessing is the plot.. If I left click inside the window and pan it, the plot shows with a sensible size, though still with no axes or titles.
Right clicking brings up the menu as expected, but any changes are not visible until i close the menu and pan the plot again. The examples work fine when run within a 32bit environment...
I'm using an anaconda environment (Python 2.7.12) with the following packages installed:
pyqtgraph 0.910
PySide 1.2.4
numpy 1.11.1
scipy 0.18.0
cython 0.24.1
All packages (including pyqtgraph) were installed with pip.
No exceptions or errors are shown when I see these issues.
Has anyone seen this before?
Please note: I have seen this question, and tried the solution. It didn't alter the behaviour in my case
Thanks for any help!

A: The issue is also found in the conda packge for PySide. See the discussion at https://github.com/conda-forge/pyside-feedstock/issues/15.
It can be fixed with pip and should also be fixed on the conda forge channel soon.
Our quickfix for conda is a custom built package based on the offical (and working) binaries from the Qt Download website at https://download.qt.io/official_releases/pyside/


text:
Q: What values am I supposed to be getting from Apple's Core Data Utility tutorial? I'm following the Core Data Utility tutorial and I've implemented the custom managed object class. It builds and runs fine but the values don't seem to be correct. My CDCLI.cdcli file is full of objects like this one:
<object type="RUN" id="z114">
    <attribute name="processid" type="int64">1334</attribute>
    <attribute name="date" type="date">369155986.60885798931121826172</attribute>
</object>

That "date" attribute doesn't look like a date. The date and the processID attribute are being set like so:
// Attribute: Date
NSAttributeDescription *dateAttribute = [[NSAttributeDescription alloc] init];

[dateAttribute setName:@"date"];
[dateAttribute setAttributeType:NSDateAttributeType];
[dateAttribute setOptional:NO];

// Attribute: Process ID
NSAttributeDescription *idAttribute = [[NSAttributeDescription alloc] init];

[idAttribute setName:@"processID"];
[idAttribute setAttributeType:NSInteger64AttributeType];
[idAttribute setOptional:NO];
[idAttribute setDefaultValue:[NSNumber numberWithInteger:-1]];

Based on the following method, I was expecting to receive "0" as the processID attribute value, which I'm not.
- (void)setNilValueForKey:(NSString *)key {

    if ([key isEqualToString:@"processID"]) {
        self.processID = 0;
    } else {
        [super setNilValueForKey:key];
    }
}

In fact, adding a few NSLog statements to that method tells me it isn't even being called, which I'll have to figure out.
Does anyone know what the date and processID attributes are supposed to look like so I can be sure I'm getting the correct values?

A: The date value looks good to me.  The internal format is the number of seconds since the reference date (Jan 1, 2001, GMT).  That value would be approximately 11.7 years, which seems like a reasonable date.
Likewise, the process ID of 1334 seems to be an appropriate value for a PID.
Finally, in your code, you do this:
if ([key isEqualToString:@"ProcessID"]) {

but your usage if the attribute name seems inconsistent.  The log shows processid, your first set of code uses processID, and the second set of code uses ProcessID.


text:
Q: How to calculate a number of $x$ values such that $f(x)$ is a quadratic residue modulo $m$? Let $a, b$ be any fixed positive integers, $f(x) = (3x + 3a)^2 - b$
How to calculate a number of $x$ values such that $f(x)$ is a quadratic residue modulo $m$ without actually finding them?
Edit: I updated the question to make it more clear.

A: Step 1: You can ignore the $-b$ since for each residue of $(3x+3a)^2-b$ there is a corresponding residue of $(3x+3a)^2$ whichi s just $b$ more than the former.
Step 2: Similarly you can ignore the $a$ since for each value of $(3x+3a)$ there is a value $(3y)$ with $y=x+a \pmod m$.
So we want to find the number of quadratic residues of the form $(3x)^2 \pmod m$.
If $m$ is a prime greater than $3$, then there are $\frac{m+1}{2}$ quadratic residues $r$ mod $m$, and for each one of those $q$, since $3$ has an inverse mod $m$,
$x=3^{-1}q\pmod m$ is a number such that $(3x)^2 = r.$  So if $m$ is an odd prime greater than $3$, then the answer is $\frac{m+2}{2}$.
If $m$ is the product of distinct primes all greater than $3$ then again we can find $x=3^{-1}\pmod m$ and the number of quadratic residues matches the number of possble values of $(3x)^2$; and that is the product of the number of quadratic residues for each factor.  So for example, when $m = 5\cdot 11 \cdot 19$ there are
$3\cdot 6 \cdot 10$ possible values of $3x)^2\pmod m$.
If $m=3$ or $m=9$, then there of course is only one residue, namely $(3x)^2=0$.
Other cases can be solved as well, but counting the residues for an arbitrary prime power is a bit trickier.


text:
Q: Manual date entry check for jQuery UI Datepicker I have jQuery datepicker on a page that allows manual date entry.How to check the format and validation of date in the jQuery UI Datepicker.For example,input 20030230,and it will remind me of the incorrect date.
thanks for your help.


text:
Q: Deny direct access to PHP file When designing a website I created a top.php page to hold the essence of my page so I could just use include for each page. So top.php holds my head, with my CSS stylesheet and with it my background to the site and then the menu bar. I've used absolute positioning with my content so everything just sits on top of an image basically - the template. Impractical perhaps but it does look nice. Anyway if you were to access mywebpage.com/top.php you just see the template with no content obviously. Now it wouldn't really be a problem because nobody would go to that link except Google has decided to include it in it's search. Even though I've submitted a sitemap and hidden it on my Google Web Account.
Any solutions?
I'm not an experienced web designer obviously.

A: You should place all files that you only include in a directory, and block access to that directory using a .htaccess file.
This will prevent Google as well as users from accessing the file directly.
Your .htaccess file should contain
deny from all
You create a directory called 'fragments' and drop top.php in there. Then, within the directory create a new file called .htacess. The file should contain deny from all.
Creating a file without any name and only an extension can be done this way:

*

*Go to notepad and type deny from all

*Click on Save As

*Select 'Save as type' to be 'All files' and name ".htacess" (with the quotes)

A: Create a robots.txt file and put it in your root folder. Add this to it:
User-agent: *
Disallow: /top.php

Additionally you could modify the permissions or disallow it using .htaccess


text:
Q: matplotlib subplot in a 2 lines, 2 columns but only 3 graphs if I only have 2 plots, here is the code I use to plot subplots:
x = np.linspace(0,10,100)
y1 = np.sin(x)
y2 = np.cos(x)

fig, (ax1,ax2) = plt.subplots(2,1)  # deux lignes une colonne

ax1.plot(x,y1,color='C1')
ax2.plot(x,y2,color='C0')

fig.show()

now, I would like to plot the two same plots but in position 'A' and 'D' according to the organisation
A   B
C   D
where B and C are empty.
I tried this code, but it is not working:
fig, ((ax1,'empty'),('empty',ax2)) = plt.subplots(2,2)

ax1.plot(x,y1,color='C1')
ax2.plot(x,y2,color='C0')

fig.show()

The result I would like is this one, with the previous notation:
fig = plt.subplots()
ax1=plt.subplot(2,2,1)
ax1.plot(x,y1,color='C1')

ax2=plt.subplot(2,2,4)
ax2.plot(x,y2,color='C0')

I finnaly found the solution, close to a suggested topic.
fig, axs = plt.subplots(2,2)

axs[0,0].plot(x,y1)
axs[1,1].plot(x,y2)

axs[0,1].set_visible(False)
axs[1,0].set_visible(False)

fig.show()


text:
Q: Machine learning when there are two "answers" I have a problem that I am trying to use machine learning on.  At a very high level, I am looking to do a transformation where in the training data I have x and it can map to either 1 or 10.  I also have y and it can map to either 2 or 20.
When I use LSTMs or RNNs on the data is seems to be giving me the average of 1 and 10 or 2 and 20.  But what I want is for the network to choose one of the values and not average them.
Is this not a good problem for machine learning or should I use a different model like random forest?

A: Given the information in your comment, that the labels are about

[...] placing furniture in a room. So for example some times we want
  the couch placed on the left hand side of the room. Other times we
  want it placed on the right side of the room. We never want it placed
  in the center of the room.

then you can treat them as separate categories like "right side of the room", "center of the room", etc., but much better approach would be to map those categories to two-dimensional coordinates, for example $x \in \{-1, 0, +1\}$ for left, center, right, and $y \in \{-1, 0, +1\}$ for bottom, center, top.
If you want to make the predictions like "the piece of furniture can be either on right side of the room, or on the left side, then you want to be able to predict bi-modal distribution. One of the approaches to such problems would be to treat the outcome variable (or variables) as a mixture distribution. Mixture distribution can be multi-modal, and what your model would predict is the probability of the predicted variables to be in a particular region of the variable space. In your case, you could use mixture density network (Bishop, 1994), using model like
$$\begin{align}
\boldsymbol{h} &= \operatorname{LSTM}(\mathbf{Z}) \\
\boldsymbol{\mu} &= g_\mu(\boldsymbol{h}) \\
\boldsymbol{\Sigma} &= g_\sigma(\boldsymbol{h}) \\
\boldsymbol{\pi} &= g_\pi(\boldsymbol{h}) \\
(x, y) &\sim \sum_{i=1}^k \pi_i \,\mathcal{N}(\boldsymbol{\mu}_i, \boldsymbol{\Sigma}_i)
\end{align}$$
where $g_\mu$, $g_\sigma$, and $g_\pi$ are sub-networks (e.g. dense layer, followed by activation function) mapping the latent variables $\boldsymbol{h}$ to mean $\boldsymbol{\mu}$, covariance $\boldsymbol{\Sigma}$, and mixing proportions $\boldsymbol{\pi}$ of the mixture of bivariate normal distributions, and $\mathbf{Z}$ are the features. Notice that this model would enable us to assume correlation between the dimensions, so if something usually appears on "top left" corner, then the model would be able to learn such relation. This is a simplification of MDN-RNN network described by Ha and Schmidhuber (2018).

Bishop, C.M. (1994). Mixture Density Networks. Technical Report NCRG/4288, Aston University, Birmingham, UK.

Ha, D., and Schmidhuber, J. (2018). Recurrent world models facilitate policy evolution. In Advances in Neural Information Processing Systems (pp. 2450-2462).


text:
Q: How create a 2 columns SQL View? I need to create a SQL View (using MySQL Workbench) that should simply take all the values of a row and stack them with theirs respectives column names on the first column. Like this:
Original Table:
name              | email                | address            | country    | ...
------------------|----------------------|--------------------|------------|
Al Wade Avery     | wade@hotmail.com     | 1004 Court Street  | USA        |
Antone Clay       | aclay@gmail.com      | 6219 Devon Court   | UK         |
Issac Luigi       | issac@hotmail.com    | 43 Bridge Street   | USA        |
Lucio Andrea      | lucioandrea@me.com   | 2283 Laurel Lane   | Italy      |
...               | ...                  | ...                | ...        |

View:
field         | value             |
--------------|-------------------|
name          | Al Wade Avery     |
email         | wade@hotmail.com  |
address       | 1004 Court Street |
country       | USA               |
...           | ...               |
name          | Antone Clay       |
email         | aclay@gmail.com   |
address       | 6219 Devon Court  |
country       | UK                |
...           | ...               |
name          | Issac Luigi       |
email         | issac@hotmail.com |
address       | 43 Bridge Street  |
country       | USA               |
...           | ...               |

A: A simple way to do this is using union all:
create view v_table as
    select 'name' as field, name as value from t
    union all
    select 'email', email
    union all
    select 'address', address
    union all
    select 'country', country;

However, you don't really want to do this because you are losing information about which fields are tied to which row in the original data.  If you have an id field, you should include that in the view:
create view v_table as
    select id, 'name' as field, name as value from t
    union all
    select id, 'email', email
    union all
    select id, 'address', address
    union all
    select id, 'country', country;

Otherwise, another unique column -- perhaps name -- should be included.


text:
Q: Shell script and mv directory creates extra character but not when run on cmd line I need to rename a directory in a crontab job so created bash file to run the script that that will move the folder prior to running mongodump command.
When I run the command directory on the command line the directory is moved and renamed without any extra characters
When I run the move.sh that directory is moved but with an trailing ? at the end of the directory name.  Rm -R /change071105^M  also appear..
Any insight is appreciated
Checked move.sh for extra character.
Directory was renamed and all files appeared.
Created a move.sh  with:
Resume of mv in script renames directory as:
change071105?  not the expected change071115
Ran command at the command line to confirm
mv /mongo_backup/change /mongo_backup/change$(date --date='1 day ago' +'%m%d%y')

also checked move.sh for extra spaces ..
 #!/bin/bash
    dd=$(date --date='1 day ago' +'%m%d%y')
    mv -v "/mongo_backup/change" "/mongo_backup/change$dd"
    #mv /mongo_backup/change /mongo_backup/change$(date --date='1 day ago' +'%m%d%y')

A: Issue was created in notepad on a windows machine and extra characters when creating scripts:   added mv -v and when running script  >sh    the \r appeared in output
Refined search and below fixed this issue
sed -i 's/\r$//' scriptname.sh


text:
Q: Prove the implication "if $ac>bc$ and $c>0$, then $a>b$" using the contrapositive
Let $a,b,c\in \mathbb{Z}$. If $ac>bc$ and $c>0$, then $a>b$

I think I would use contrapositive to prove this. But I am not sure proper contrapositive statement.
Is it If $a<b$, then $ac<bc$, and $c<0$.? If so, contrapositive is not a good choice, isn't it?

A: The contrapositive of your statement would be
$$\text{If }\;a\leq b, \text{ then } \;ac\leq bc\;\text{ OR }\;c\leq 0$$
To be "not greater than" means to be "less than or equal to". And the negation of $P$ AND $Q$ is (NOT $P$) OR (NOT $Q$).

A: If $ac > bc$ and $c > 0$. It follows that $ac-bc = (a-b)c > 0$, because $c>0$ it follows that $a-b>0$, so $a>b$.

A: Hint:  $x>y$ if and only if $x-y>0$. Also $xy>0$ if and only if $x,y$ have the same sign.

A: I think I would use induction on $c$ -- assuming that you already know that if $a>b$ and $p>q$ then $a+p>c+q$.
(Though not after reading user112167's suggestion.)


text:
Q: Background substraction using OpenCV MOG from live camera feed I am studying OpenCV and I'm having a lot of fun, but now I'm stuck with a problem where I'm trying to use a background subtraction algorithm to detect any changes.
I followed this tutorial and I managed to get it working to detect changes in a video file (AVI).
The problem I'm having right now is that it tends to incorrectly subtract the background noise and other small changes and instead fill the whole screen pretty much with white.
Here is my implementation of the MOG algorithm on a live camera feed, but the relevant part is this:
    VideoCapture cap;
    if (argc > 1)
        cap.open(argv[1]);
    else
        cap.open(0);
    cap.set(CV_CAP_PROP_FOURCC ,CV_FOURCC('D', 'I', 'V', '3') );
........
    Mat frame, fgMaskMOG;

    Ptr<BackgroundSubtractor> pMOG = new BackgroundSubtractorMOG();
    for (;;)
    {
        if(!cap.read(frame)) {
            cerr << "Unable to read next frame." << endl;
            continue;
        }
        // process the image to obtain a mask image.
        pMOG->operator()(frame, fgMaskMOG);

        std::string time = getDateTime();
        cv::rectangle(frame,cv::Rect(0,cap.get(CV_CAP_PROP_FRAME_HEIGHT)-25,290,20),cv::Scalar(255,255,255),-1);
        cv::putText(frame,time,cv::Point(0,cap.get(CV_CAP_PROP_FRAME_HEIGHT)-5),1,1.5,cv::Scalar(0,0,0),2);
........
        // show image.
        imshow("Image", frame);
        imshow("Debug",fgMaskMOG);
        int c = waitKey(30);
        if (c == 'q' || c == 'Q' || (c & 255) == 27)
            break;
    }

This implementation works just fine for a video file as you can see:

(source: opencv.org)

(source: opencv.org)

But this is the result when I try to use MOG on a live camera feed:

(source: opencv.org)

(source: opencv.org)

(EDIT:

EXPECTED RESULT: My expectation was the same as the video file (see pictures one and two above).
ACTUAL RESULT: The actual result was far from my expected result, much noise was generated (i.e not filtered out), when one put something in front of the camera, it would be black instead of white (inverse from the result of the video file).

- - - - SYSTEM DETAILS - - - -
OS: Windows x64bit
MEMORY AVAILABLE: 3890 MB
WEBCAM: I'm using my built-in webcam on my Satellite C660 TOSHIBA laptop.
COMPILER:
Microsoft Visual Studio Express 2012 for Windows Desktop
Version 11.0.61030.00 Update 4
Microsoft .NET Framework
Version 4.5.50948
OpenCV Version: OpenCV V. 2.4.9, built for Windows, downloaded from SourceForge.
OUTPUT FROM cv::getBuildInformation(): OpenCV_BUILD.txt
Microsoft Visual Studio Project Property Sheet: OpenCV Project Property Sheet
)


text:
Q: CentOS won't present login menu after a new service was defined Yesterday I was trying to install Ganglia in my virtual machine. After I defined Ganglia as a service I reboot the machine, but after that CentOS won't present the log in menu anymore.
I think it's because Ganglia service is blocking the system from starting properly, because I was able to show the start commands that the OS presents as shown below.

How do I fix that ?

A: Boot into single user mode and disable the service in other runlevels, then switch to RL3 (or 5) or reboot normally.

A: From the look of it, Ganglia is started in the foreground and does not allow the boot process to continue. Boot single as SvenW suggested or (if the VM makes it difficult) you can enter interactive boot by pressing 'I' in the first stages of the boot process.


text:
Q: Error:"Unable to find the requested .Net Framework Data Provider. It may not be installed." i having an error said that "Unable to find the requested .Net Framework Data Provider. It may not be installed."
I'm using (visual studio 2010) with (Sqlserver 2008 R2) And (.net framework 4.0)
(ASP.net:C#)

A: I'm trying to use SubSonic for vb.net windows apps and mySql and had the same error as you,
I've just installed vb.net 2010 express
I read a stack overflow question here which suggested that the db connector had been installed before .net v4 (vs2010) hence they couldn't be found, I thought this sounded feasible so I downloaded the latest MySql connector, uninstalled the old one and installed the new one. The next time I ran my project the simpleRepository worked straight away!
I was blaming SubSonic! but it really is great!
Hope this might help


text:
Q: NFe - ERRO no AddProt (Para quem já utilizou o NfePHP) (Para quem já utilizou o NfePHP)
Já fiz praticamente todos passos para Gerar a Nfe:

*

*Criei o xml no MakeNfe

*Assinei o xml com AssinaNfe

*Validei com o ValidaXml

*Enviei o Lote para Sefaz com o EnviaLote.php

*Consultei o  Recibo com o código do recibo no ConsultaRecibo e ela foi aprovada para uso

Até aqui tudo bem, mas no AddProt está retornando o erro abaixo e no TestaDanfe.php não está encontrando o arquivo xml
no AddProt utilizando o Recibo e a Chave da v está acontecendo o seguinte erro:
Warning: DOMDocument::loadXML(): Start tag expected, '<' not found in Entity, line: 1 in /home/MEUSITE/public_html/nota-fiscal/nfephp-master/libs/Common/Dom/Dom.php on line 37

Fatal error: Uncaught exception 'NFePHP\Common\Exception\RuntimeException' with message 'O arquivo indicado não é um XML!' in /home/MEUSITE/public_html/nota-fiscal/nfephp-master/libs/Common/Dom/Dom.php:39 Stack trace: #0 /home/MEUSITE/public_html/nota-fiscal/nfephp-master/libs/NFe/ToolsNFe.php(349): NFePHP\Common\Dom\Dom->loadXMLString('/home/MEUSITE/...') #1 /home/MEUSITE/public_html/4.00testaAddProt.php(24): NFePHP\NFe\ToolsNFe->addProtocolo('/home/MEUSITE/...', '/home/MEUSITE/...', true) #2 {main} thrown in /home/MEUSITE/public_html/Sistema/nota-fiscal/nfephp-master/libs/Common/Dom/Dom.php on line 39

OBS.: Os caminhos estão corretos, não fiz nenhuma alteração nos XML só efetuei os procedimentos certos.
O que estou fazendo de errado? O que falta para gerar NFE e a DANFE em PDF?
Para que serve o arquivo AddProt.php do NFE-PHP?

A: Amigo, passei por isso, o erro era:
tem q ser no meu caso:
$indSinc = '0'; //0=asíncrono, 1=síncrono
para chegar o recibo pegando o arquivo gerado depois de enviar o lote


text:
Q: Ghost network adapters Get-NetAdapter returns a bunch of adapters (about 15) which are not visible anywhere else in the system.
Looks like this:
HP hs3210 HSPA+ Mobile Broadband Device      37 Not Present

What are these, and how to remove them ?

A: Net adapaters are physical or virtual network devices in your system (not WIFi devices in you area as suggested by @jdweng). Unless you know what your doing, or have a clear goal in mind i would just leave the devices as they are or you risk breaking Windows.
Items returned by get-NetAdapter were detected/installed at some point. Things like HyperV, VMWare, Docker, VPN's etc as well as physical hardware like network cards, or bluetooth can all install devices like this. If you have physically removed or disabled a device in the BIOS of your PC you will still see traces of them - but honestly theres little advantage to removing them, but there is a risk of seriously breaking your Windows installation in weird ways (you have been warned :-).
If you really want to peruse deleting these devices take a look in the registry - HKLM:\SYSTEM\CurrentControlSet and its subkeys - this is ultimately where those devices are stored. Again, deleting stuff from the registry can have unintended as well as catastrophic consequences. (so backup your data, have a boot USB to hand etc before you start). good luck!

A: If they are genuinely physical devices that have been removed, there are several powershell scripts available that will remove "ghost" devices on your system that were once installed but now no longer have associated hardware. Just Google "powershell remove ghost devices".
I've adapted this one for use in my particular environment:
https://github.com/istvans/scripts/blob/master/removeGhosts.ps1
Take care, understand what the script is doing and test thoroughly. Only remove what is definitely not required.


text:
Q: How do i select Tables name and Rows count and CHECKSUM_AGG for all tables? I can't figure out how to select TalbeName,Rows Count,Table Hash  for all tables
it is easy to select Rows count for all tables like this
SELECT sc.name +'.'+ ta.name TableName,SUM(pa.rows) RowCnt
FROM sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name

But how to select CHECKSUM_AGG(BINARY_CHECKSUM(*)) in addition,
to get
TALBENAME_____________ ROWS_________ CHECKSUM_AGG(BINARY_CHECKSUM(*))

Thanks in advance!.

A: After 3 days of searching, I Found the solution using Dynamic SQL.
DECLARE @table sysname
DECLARE @sqlCommand nvarchar(MAX)
DECLARE @sqlparam nvarchar(MAX)
DECLARE @COUNT INT
DECLARE @HASH INT

DECLARE TABLE_CURSOR CURSOR FOR
SELECT SC.NAME+'.'+TA.NAME FROM SYS.TABLES TA
INNER JOIN SYS.SCHEMAS SC ON SC.SCHEMA_ID=TA.SCHEMA_ID ORDER BY 1
OPEN TABLE_CURSOR

WHILE 1=1
BEGIN
   FETCH TABLE_CURSOR INTO @TABLE
   IF @@FETCH_STATUS<>0
      BREAK
   SET @sqlCommand = N'SELECT @CNT=COUNT(*),@HSH=CHECKSUM_AGG(BINARY_CHECKSUM(*)) from '+@table
   SET @sqlparam=N'@CNT INT OUTPUT, @HSH INT OUTPUT'
   EXECUTE sp_executesql @sqlCommand, @sqlparam,  @COUNT OUTPUT,  @HASH OUTPUT
   PRINT @TABLE+': '+CONVERT(NVARCHAR(50),@COUNT)+':'+CONVERT(NVARCHAR(50),@HASH)
END
CLOSE TABLE_CURSOR
DEALLOCATE TABLE_CURSOR


text:
Q: I have two different SharePoint picture libaries showing the same thing. How do I get them to show correctly? I have two different picture libaries showing the same thing. How do I get them to show correctly?

A: 1)Delete one.
2) back up and delete one
3) back up delete them all then restore one
4)leave them alone and never talk about again.
Hope this helps


text:
Q: What is the relationship between number of perfect squares and number of perfect cubes? If S is the "number" of perfect squares between 1 and a specific integer N and Q is the "number" of perfect cubes between 1 to N. How we can show the relationship between S and Q?
Please explain with mathematical proof.

A: You have
$$S = \lfloor \sqrt{N} \rfloor$$
Indeed, the square between 1 and N are :
$$1, 2^2, 3^2, \cdots, (S-1)^2, S^2$$
With $S$ an integer such that $\sqrt{N}-1 < S \leq \sqrt{N}$
Same idea with the cube :
$$Q =  \lfloor \sqrt[3]{N} \rfloor$$
Now, I'm not sure there is an explicit relation between the two. On average, $\frac{S}{Q} \sim N^{\frac{1}{6}}$


text:
Q: Sending email at the click of a text element I need to make a text element that would generate an email to the admin on click.
I was looking for various solutions and came up with the following code that I compiled from various bits found on stackoverflow.
I don't know php, javascript,  jquery, just html.
JQuery that I put before

PHP that I put in mail.php which is in public_html
 <?php
if($_POST)
{
    $to      = 'mail@mail.com';
    $subject = 'subject';
    $message = 'hello';
    $headers = 'From: webmaster@example.com' . "\r\n" .
        'Reply-To: webmaster@example.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);

    echo 'Email Sent.';
}
 ?>

HTML
TEST

Nothing happens.


text:
Q: Infragistics UltraTimeLineView allow scrolling when control is disabled I've an Infragistics UltraTimeLineView. I'm not showing the horizontal scrollbar because I don't need it, but I do need the vertical scrollbar.
In some cases I need to disable my control to avoid the user to add appointments or remove, resize, drag or edit the created ones. The problem is that I want that the user still be able to see all the created appointments, and that is not posible because I've too many Owners.
Increasing the shown-owners in the grid is not a possibility.
Thanks for your help! Diego

A: Not possible.
Question in Infragistics forum.


text:
Q: C++11 chrono create time_point from number I'm converting a std::chrono::time_point<std::chrono::high_resolution_clock> timestamp using
std::chrono::duration_cast<std::chrono::milliseconds>(
  getTimestamp().time_since_epoch()
).count()

to a 64 bit timestamp with millisecond precision. This is needed for some serialization in between of data. Later on I need to convert those timestamps back to a std::chrono::time_point<std::chrono::high_resolution_clock> for further processing. What is the proper way to do this in C++11?

A: Convert the number of milliseconds to a duration and add it to an epoch time_point:
auto epoch = std::chrono::time_point<std::chrono::high_resolution_clock>();
auto since_epoch = std::chrono::milliseconds(deserialised);
auto timestamp = epoch + since_epoch;


text:
Q: Non-semisimple symmetric subgroups of simply connected simple algebraic groups Let $G$ be a simply connected simple algebraic group over the field of complex numbers $\mathbb C$. Let $H$ be a symmetric subgroup of $G$. This means that there exists an automorphism of order 2 $\sigma\colon G\to G$ such that $H$ is the group of fixed points of $\sigma$ in $G$. It is known that $H$ is connected.
Let us assume that $H$ is not semisimple. It is known that then the center of $H$ is one-dimensional. Consider the derived subgroup $H^{\rm der}:=[H,H]$.

Question. Is it true that the semisimple group $H^{\rm der}$ is always simply connected?

It seems that this is true when $G$ is a classical group (say, when $G={\rm Sp}_{2n}$, $H=U_n$). What about $E_6$ and $E_7$? If the answer is always "yes", I would prefer a classification-free proof.

A: In your case, $H$ is a Levi subgroup and the derived subgroup of a Levi subgroup in a simply connected group is always simply connected (since all fundamental weights are characters).

A: The answer is YES. Such a subgroup $H$ is called a Hermitian symmetric subgroup (because then for suitable real forms of $G$ and $H$, the quotient $G/H$ is a Hermitian symmetric space). It follows from the theory of Victor Kac that any Hermitian symmetric subgroup of a simple group is a "diagrammatic" subgroup (Levi subgroup) corresponding to the Dynkin subdiagram obtained by removing one vertex corresponding to a simple root appearing with coefficient one in the expression of the highest root as a linear combination of simple roots. See e.g. Table 7, type II in the book by Onishchik and Vinberg, or  case (B) in the text after Lemma 5.17 on page 513 in Ch. X of the book by Helgason "Differential Geometry, Lie Groups, and Symmetric Spaces".  It is well known that the derived group of any Levi subgroup of a simply connected semisimple group is simply connected, see e.g. Proposition 12.14 in the book by G. Malle and D. Testerman "Linear Algebraic Groups and Finite Groups of Lie Type".


text:
Q: Scala : Read JSON file with Play I'm trying to extract the data from a JSON file that looks like that :
    val json: JsValue = Json.parse("""
    {
      "item": {
            "id" : "11111111",
            "name" : "box",
            "categories" : [{
                               "name" : "blue box",
                               "id" : "12345",
                           },
                           {
                               "name" : "fancy box",
                               "id" : "98765",
                           }]
              }
    }
    """)

I would like to do it using the play JSON library. I came up with this code :
    //I define my class and reader for one category
    case class ItemCategory(id: Option[String], name: String)
    implicit val categoryRead: Reads[ItemCategory] = (
        (JsPath \ "item" \ "categories" \ "id").readNullable[String] and
        (JsPath \ "item" \ "categories" \ "name").read[String]
    )(ItemCategory.apply _)

    //I define my class and reader for one item
    case class MyItem(categories : Option[List[ItemCategory]], id : Option[String], name : Option[String])
    implicit val myItemRead: Reads[MyItem] = (
        (JsPath \ "item" \ "categories").readNullable[List[ItemCategory]] and
        (JsPath \ "item" \ "id").readNullable[String] and
        (JsPath \ "item" \ "name").readNullable[String]
    )(MyItem.apply _)

    //I then try to read :
    var item: JsResult[MyItem] = json.validate[MyItem](myItemRead)
    println(item)

However this code gives a JsError :List(ValidationError(validate.error.missing-path,WrappedArray())).
Which to my understanding simply means that some path went missing. I tried to read just one category and it worked fine, I try to read an item without trying to get the categories and here again it went fine. Hence I think the problem is on reading a list of items. I would really appreciate if you could help me with this.

A: Path is relative. categoryRead js path should be relative. Such as _ \ xxx