text:
Q: how to optimize this query further more
I tried all i could do but could not get the least execution time.

SELECT e.code_assigned,
       Count(DISTINCT tcp.id) AS total_qa,
       Count(DISTINCT tcp.encounter_uid) AS total_records,
       Sum(IF(tcp.qa_disagree = '1', tcd.weight, 0)) AS error_points,
       Sum(IF(tcp.qa_disagree = '1',1,0)) AS total_disagree,
       Sum(tcd.weight) AS total_qa_weight,
       Count(DISTINCT CASE WHEN tcp.qa_disagree = '1' THEN tcp.encounter_uid end) AS total_disagree_record

FROM tbl_encounter_detail AS e
STRAIGHT_JOIN tbl_event_cpt_pro AS tcp ON tcp.encounter_uid = e.encounter_uid AND tcp.work_item_uid = e.work_item_uid
JOIN tbl_encounter as ed ON tcp.encounter_uid = ed.encounter_uid
LEFT JOIN tbl_code_weight AS tcd ON tcd.code = tcp.procedure_num

WHERE  e.qa_complete = 1
GROUP  BY code_assigned

UNION ALL

SELECT e.code_assigned,
       Count(DISTINCT tcf.id) AS total_qa,
       Count(DISTINCT tcf.encounter_uid) AS total_records,
       Sum(IF(tcf.qa_disagree = '1', tcd.weight, 0)) AS error_points,
       Sum(IF(tcf.qa_disagree = '1',1,0)) AS total_disagree,
       Sum(tcd.weight) AS total_qa_weight,
       Count(DISTINCT CASE WHEN tcf.qa_disagree = '1' THEN tcf.encounter_uid end) AS total_disagree_record

FROM tbl_encounter_detail AS e
STRAIGHT_JOIN  tbl_event_cpt_fac AS tcf ON tcf.encounter_uid = e.encounter_uid AND tcf.work_item_uid = e.work_item_uid
JOIN tbl_encounter as ed ON tcf.encounter_uid = ed.encounter_uid
LEFT JOIN tbl_code_weight AS tcd ON tcd.code = tcf.procedure_num

WHERE e.qa_complete = 1
GROUP BY code_assigned

This query is hampering performance (this is the least that i am able to do) I don't know why am i not able to optimize it more. what is really hampering it? Please help.

new explain plan

for tbl_event_cpt_pro and tbl_event_cpt_fac

CREATE TABLE `tbl_event_cpt_pro` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`encounter_uid` int(11) NOT NULL,
`procedure_num` varchar(10) NOT NULL,
`procedure_qty` int(11) NOT NULL DEFAULT '1',
`procedure_modifier1` varchar(10) DEFAULT NULL,
`procedure_modifier2` varchar(10) DEFAULT NULL,
`procedure_provider` varchar(75) DEFAULT NULL,
`mid_provider` varchar(75) DEFAULT NULL,
`userid` varchar(50) NOT NULL,
`user_time_entered` datetime NOT NULL,
`qa_disagree` tinyint(1) NOT NULL DEFAULT '0',
`qa_procedure_num` varchar(10) DEFAULT NULL,
`qa_procedure_qty` int(5) DEFAULT NULL,
`qa_procedure_modifier` varchar(10) DEFAULT NULL,
`qa_procedure_provider` varchar(75) DEFAULT NULL,
`qa_note` varchar(255) DEFAULT NULL,
`qa_userid` varchar(50) DEFAULT NULL,
`qa_user_time_entered` datetime DEFAULT NULL,
`qa_reason` varchar(75) DEFAULT NULL,
`work_item_uid` int(11) NOT NULL,
`user_time_entered_utc` datetime DEFAULT NULL,
`cosigning_physician` varchar(75) DEFAULT NULL,
`procedure_date` date DEFAULT NULL COMMENT 'Date procedure was
 performed. May not be date of service/admit date.',
`charge_code_select` varchar(20) DEFAULT NULL COMMENT 'If the
procedure CPT has multiple charge codes, this indicates the one chosen    by coder',
`specialist` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Indicates   Specialist outpatient procedure - ref IU and Sturdy',
`dos` date DEFAULT NULL,
 PRIMARY KEY (`id`),
 KEY `idx_enc_uid` (`encounter_uid`),
 KEY `procedure_provider` (`procedure_provider`),
 KEY `mid_provider` (`mid_provider`),
 KEY `qa_procedure_provider` (`qa_procedure_provider`),
 KEY `userid` (`userid`),
 KEY `qa_userid` (`qa_userid`),
 KEY `work_item_uid` (`work_item_uid`),
 KEY `work_item_uid_2` (`work_item_uid`,`encounter_uid`),
 KEY `cosigning_physician` (`cosigning_physician`),
 KEY `code_index` (`procedure_num`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_1` FOREIGN KEY (`encounter_uid`)   REFERENCES `tbl_encounter` (`encounter_uid`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_10` FOREIGN KEY (`work_item_uid`) REFERENCES `tbl_work_item` (`work_item_uid`) ON DELETE CASCADE,
 CONSTRAINT `tbl_event_cpt_pro_ibfk_11` FOREIGN KEY (`userid`) REFERENCES `tbl_user` (`user_email_address`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_12` FOREIGN KEY (`work_item_uid`,  `encounter_uid`) REFERENCES `tbl_encounter_detail` (`work_item_uid`, `encounter_uid`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_13` FOREIGN KEY (`cosigning_physician`) REFERENCES `tbl_provider` (`provider_lov`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_2` FOREIGN KEY (`procedure_provider`) REFERENCES `tbl_provider` (`provider_lov`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_3` FOREIGN KEY (`mid_provider`) REFERENCES `tbl_provider` (`provider_lov`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_4` FOREIGN KEY (`qa_procedure_provider`) REFERENCES `tbl_provider` (`provider_lov`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_5` FOREIGN KEY (`userid`) REFERENCES `tbl_user` (`user_email_address`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_6` FOREIGN KEY (`qa_userid`) REFERENCES `tbl_user` (`user_email_address`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_7` FOREIGN KEY (`work_item_uid`) REFERENCES `tbl_work_item` (`work_item_uid`),
 CONSTRAINT `tbl_event_cpt_pro_ibfk_9` FOREIGN KEY (`encounter_uid`) REFERENCES `tbl_encounter` (`encounter_uid`) ON DELETE CASCADE

)

for tbl_encounter_detail

 CREATE TABLE `tbl_encounter_detail` (
 `enc_detail_uid` int(11) NOT NULL AUTO_INCREMENT,
 `encounter_uid` int(11) NOT NULL,
 `work_item_uid` int(11) NOT NULL,
 `code_assigned` varchar(50) DEFAULT NULL,
 `coding_start_time` datetime DEFAULT NULL,
 `code_complete_ts` datetime DEFAULT NULL,
 `code_complete` int(1) NOT NULL DEFAULT '0',
 `suspend_active` int(1) DEFAULT NULL,
 `qa_flag` int(1) NOT NULL DEFAULT '0',
 `qa_complete` int(1) NOT NULL DEFAULT '0',
 `qa_start_time` datetime DEFAULT NULL,
 `qa_complete_ts` datetime DEFAULT NULL,
 `qa_assigned` varchar(50) DEFAULT NULL,
 `dataentry_complete` int(1) NOT NULL DEFAULT '0',
 `dataentry_start_time` datetime DEFAULT NULL,
 `dataentry_complete_ts` datetime DEFAULT NULL,
 `dataentry_assigned` varchar(50) DEFAULT NULL,
 `encounter_status` varchar(30) NOT NULL,
 `dataentry_assigned_tec` varchar(50) DEFAULT NULL COMMENT 'Data entry user for Technical component',
 `dataentry_complete_tec` int(1) NOT NULL DEFAULT '0' COMMENT 'Data Entry complete for Technical component; used only for split data entry clients',
 `dataentry_assigned_pf` varchar(50) DEFAULT NULL COMMENT 'Data entry user for Profee component',
 `dataentry_complete_pf` int(1) NOT NULL DEFAULT '0' COMMENT 'Data Entry complete for Profee component',
 `qa_feedback` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Set when the QA reviewer has feedback on disagreements',
 `qa_seen_by_coder_utc` datetime DEFAULT NULL COMMENT 'Set when the coder acknowledges QA feedback on this encounter',
 `qa_dataentry` tinyint(1) DEFAULT '0' COMMENT 'Set if data entry requested QA',
 `code_complete_pf` tinyint(1) DEFAULT '0' COMMENT 'When LiveCode and split data entry are active, this indicates Profee coding is done; otherwise ignored',
 `qa_requested` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Whether QA was requested by Coder or Data Entry (vs random sample)',
 PRIMARY KEY (`enc_detail_uid`),
 UNIQUE KEY `uniq_wi_enc` (`work_item_uid`,`encounter_uid`),
 KEY `idx_enc_uid` (`encounter_uid`),
 KEY `idx_code_assigned` (`code_assigned`),
 KEY `encounter_status` (`encounter_status`),
 KEY `qa_assigned` (`qa_assigned`),
 KEY `dataentry_assigned` (`dataentry_assigned`),
 KEY `dataentry_assigned_tec` (`dataentry_assigned_tec`),
 KEY `dataentry_assigned_pf` (`dataentry_assigned_pf`),
 KEY `idx_qa_complete` (`qa_complete`),
 KEY `idx_composite` (`qa_complete`,`code_assigned`,`encounter_uid`,`work_item_uid`),
 CONSTRAINT `tbl_encounter_detail_ibfk_1` FOREIGN KEY (`encounter_uid`) REFERENCES `tbl_encounter` (`encounter_uid`),
 CONSTRAINT `tbl_encounter_detail_ibfk_2` FOREIGN KEY (`work_item_uid`) REFERENCES `tbl_work_item` (`work_item_uid`),
 CONSTRAINT `tbl_encounter_detail_ibfk_3` FOREIGN KEY (`code_assigned`) REFERENCES `tbl_user` (`user_email_address`),
 CONSTRAINT `tbl_encounter_detail_ibfk_4` FOREIGN KEY (`qa_assigned`) REFERENCES `tbl_user` (`user_email_address`),
 CONSTRAINT `tbl_encounter_detail_ibfk_5` FOREIGN KEY (`dataentry_assigned`) REFERENCES `tbl_user` (`user_email_address`),
 CONSTRAINT `tbl_encounter_detail_ibfk_6` FOREIGN KEY (`dataentry_assigned_tec`) REFERENCES `tbl_user` (`user_email_address`),
 CONSTRAINT `tbl_encounter_detail_ibfk_7` FOREIGN KEY (`dataentry_assigned_pf`) REFERENCES `tbl_user` (`user_email_address`),
 CONSTRAINT `tbl_encounter_detail_ibfk_8` FOREIGN KEY (`encounter_status`) REFERENCES `tbl_encounter_status` (`id`)

)

for tbl_encounter

CREATE TABLE `tbl_encounter` (
`encounter_uid` int(11) NOT NULL AUTO_INCREMENT,
`patient_name` varchar(75) NOT NULL,
`patient_sex` varchar(1) NOT NULL,
`patient_dob` date NOT NULL,
`encounter_dos` date NOT NULL,
`batch_control` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_location` varchar(50) CHARACTER SET latin1 DEFAULT NULL,
`facility_id` varchar(75) NOT NULL,
`patient_mrn` varchar(20) NOT NULL,
`patient_fin` varchar(20) NOT NULL,
`encounter_lwbs` tinyint(1) DEFAULT NULL,
`encounter_ama` tinyint(1) DEFAULT NULL,
`encounter_reason_for_visit` varchar(300) DEFAULT NULL,
`encounter_chief_complaint` varchar(2048) DEFAULT NULL,
`encounter_ins_type` varchar(50) CHARACTER SET latin1 DEFAULT NULL,
`encounter_ins_1` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_ins_2` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_primary_type` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_primary_class` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_secondary_type` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_secondary_class` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_disch_diagnosis` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_disch_disp` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_type` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_assign_provider1` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_assign_provider2` varchar(75) DEFAULT NULL COMMENT 'Obsolete - should be dropped in future',
`encounter_admit_mode` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`load_time` datetime NOT NULL,
`enc_admit` datetime DEFAULT NULL COMMENT 'Datetime of inpatient admission.',
`import_loc` varchar(200) DEFAULT NULL COMMENT 'Source of record: typically file name and line number',
`import_line` bigint(20) unsigned DEFAULT NULL,
`attend_provider_uid` int(10) unsigned DEFAULT NULL,
`disch_time_utc` datetime DEFAULT NULL,
`last_adt_recorded_utc` datetime DEFAULT NULL COMMENT 'The EVN.2 recorded timestamp of the last ADT update applied. Used to ensure updates are applied in order.',
`loaded_disch_disp` varchar(75) DEFAULT NULL COMMENT 'The discharge disposition originally loaded from ED Log for this chart',
`admitted` tinyint(1) DEFAULT NULL,
`injury_real_date` date DEFAULT NULL,
`lmp_date` date DEFAULT NULL COMMENT 'Last Menstrual Period',
`transfer` tinyint(1) DEFAULT NULL COMMENT 'Coded in patient header when patient was transferred between facilities',
`transfer_dest` varchar(75) DEFAULT NULL COMMENT 'If chart is a transfer to another facility, the coder specifies the facility in this field',
`dos_end` date DEFAULT NULL,
`outpatient` tinyint(1) DEFAULT NULL,
`discharge` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`encounter_uid`),
KEY `idx_fac_id` (`facility_id`),
KEY `idx_name` (`patient_name`),
KEY `idx_dos` (`encounter_dos`),
KEY `attend_provider_uid` (`attend_provider_uid`),
KEY `idx_fin` (`patient_fin`),
KEY `idx_ins` (`encounter_primary_type`),
KEY `idx_prov` (`encounter_assign_provider1`),
KEY `idx_mrn_temp` (`patient_mrn`),
CONSTRAINT `tbl_encounter_ibfk_1` FOREIGN KEY (`attend_provider_uid`) REFERENCES `tbl_provider` (`provider_uid`)

)

for tbl_code_weight

Create Table: CREATE TABLE `tbl_code_weight` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(20) NOT NULL,
`weight` float NOT NULL,
KEY `idx_composite` (`code`,`weight`)
PRIMARY KEY (`id`)

)


text:
Q: merged pcap file from mergecap command I have created a merge script to merge all pcap files in a folder to a single file. Merge function works. But is there any way to test if the contents of the merged file and the input files are same? Because the application which I have to read through the file says, merged file is corrupt some how.

A: Try to load the merged file with wireshark or tcpdump which should tell you if it is corrupt. But maybe the file is not corrupt, but in a format your application does not understand. Try to merge with output format 'pcap', e.g. mergecap -F pcap, because some application do not work with pcapng (used by wireshark).

A: This happens sometimes with mergecap and tcpslice. They don't work well if the input pcap files aren't perfect.
This can be solved using joincap.
go get -u github.com/assafmo/joincap

To merge 1.pcap and 2.pcap:
joincap 1.pcap 2.pcap > merged.pcap

I wrote joincap to overcome what I believe is bad error handling by mergecap and tcpslice.
For more details go to https://github.com/assafmo/joincap.

redpajama_set_name: RedPajamaStackExchange


text:
Q: F# tail recursion and why not write a while loop? I'm learning F# (new to functional programming in general though used functional aspects of C# for years but let's face it, that's pretty different) and one of the things that I've read is that the F# compiler identifies tail recursion and compiles it into a while loop (see http://thevalerios.net/matt/2009/01/recursion-in-f-and-the-tail-recursion-police/).
What I don't understand is why you would write a recursive function instead of a while loop if that's what it's going to turn into anyway.  Especially considering that you need to do some extra work to make your function recursive.
I have a feeling someone might say that the while loop is not particularly functional and you want to act all functional and whatnot so you use recursion but then why is it sufficient for the compiler to turn it into a while loop?
Can someone explain this to me?

A: A recursive function is often the most natural way to work with certain data structures (such as trees and F# lists). If the compiler wants to transform my natural, intuitive code into an awkward while loop for performance reasons that's fine, but why would I want to write that myself?
Also, Brian's answer to a related question is relevant here. Higher-order functions can often replace both loops and recursive functions in your code.

A: The fact that F# performs tail optimization is just an implementation detail that allows you to use tail recursion with the same efficiency (and no fear of a stack overflow) as a while loop. But it is just that - an implementation detail - on the surface your algorithm is still recursive and is structured that way, which for many algorithms is the most logical, functional way to represent it.
The same applies to some of the list handling internals as well in F# - internally mutation is used for a more efficient implementation of list manipulation, but this fact is hidden from the programmer.
What it comes down to is how the language allows you to describe and implement your algorithm, not what mechanics are used under the hood to make it happen.

A: A while loop is imperative by its nature. Most of the time, when using while loops, you will find yourself writing code like this:
let mutable x = ...
...
while someCond do
    ...
    x <- ...

This pattern is common in imperative languages like C, C++ or C#, but not so common in functional languages.
As the other posters have said some data structures, more exactly recursive data structures, lend themselves to recursive processing. Since the most common data structure in functional languages is by far the singly linked list, solving problems by using lists and recursive functions is a common practice.
Another argument in favor of recursive solutions is the tight relation between recursion and induction. Using a recursive solution allows the programmer to think about the problem inductively, which arguably helps in solving it.
Again, as other posters said, the fact that the compiler optimizes tail-recursive functions (obviously, not all functions can benefit from tail-call optimization) is an implementation detail which lets your recursive algorithm run in constant space.

A: You could use the same argument for any transformation that the compiler performs.  For instance, when you're using C#, do you ever use lambda expressions or anonymous delegates?  If the compiler is just going to turn those into classes and (non-anonymous) delegates, then why not just use those constructions yourself?  Likewise, do you ever use iterator blocks?  If the compiler is just going to turn those into state machines which explicitly implement IEnumerable<T>, then why not just write that code yourself?  Or if the C# compiler is just going to emit IL anyway, why bother writing C# instead of IL in the first place?  And so on.
One obvious answer to all of these questions is that we want to write code which allows us to express ourselves clearly.  Likewise, there are many algorithms which are naturally recursive, and so writing recursive functions will often lead to a clear expression of those algorithms.  In particular, it is arguably easier to reason about the termination of a recursive algorithm than a while loop in many cases (e.g. is there a clear base case, and does each recursive call make the problem "smaller"?).
However, since we're writing code and not mathematics papers, it's also nice to have software which meets certain real-world performance criteria (such as the ability to handle large inputs without overflowing the stack).  Therefore, the fact that tail recursion is converted into the equivalent of while loops is critical for being able to use recursive formulations of algorithms.


text:
Q: Can I install a customized image of ubuntu with wubi? I have a customized image of ubuntu which I want to install with wubi, there are any procedure to install it without a standard installation or any VM?

A: Normally Wubi looks for an ISO image of an installation CD in the same directory as the executable wubi.exe. Therefore, most likely you can, but I'd first try it out.


text:
Q: Filter table by Selected month in dropdown box I have a dropdown that filters the table by its teamCode in my database
here is the html for dropdown :

        INSULATION

          GABLE
          HOLING
          OUTSIDE INSULATION
          INSIDE INSULATION

I will make a sample only for the  tag with id gableTeam
this is the ajax for gableTeam :
    $(document).on('click','#gableTeam',function(){
    var Fmonth = $('#Fmonth').val();
        $.ajax({
            type: 'post',
            url: 'read_gable.php',
            data: {
                'month' :Fmonth
            },

            success: function(data){
                $("#containerDiv").html(data)
                $("#containerDiv").hide().fadeIn(500)
                //alert(Fmonth);
            },
            error:function(data){
                alert('Failed');
            }
    })
});

I set to check the value of my dropdown #Fmonth to filter what month would show in the table when #gableTeam is click.
This is my html for dropdown box #Fmonth :
<select class="form-control" width="50px" name="Fmonth" id="Fmonth">
      <option value="1">January</option>
      <option value="2">February</option>
      <option value="3">March</option>
      <option value="4">April</option>
      <option value="5">May</option>
      <option value="6">June</option>
      <option value="7">July</option>
      <option value="8">August</option>
      <option value="9">September</option>
      <option value="10">October</option>
      <option value="11">November</option>
      <option value="12">December</option>
</select>

This is my php for read_gable.php (it will only show one row for just only a sample):
    <?php
$Fmonth = @$_REQUEST["month"];
try {
            $pdo = new PDO('mysql:host=localhost:3306;dbname=*****;', '*****', '***' );
            $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $stmt = $pdo->prepare(
                " SELECT * from mbwa WHERE month = :Fmonth AND teamCode = '313'"
        );
        $stmt->bindValue( ':Fmonth', $Fmonth, PDO::PARAM_STR );

        $flag = $stmt->execute();
        if ( !$flag ) {
            $info = $stmt->errorInfo();
            exit( $info[2] );
        }
        while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {

                @$tbody .='
';

                $tbody .=''.$row["DAY1"].'	';
                $tbody .=''.$row["DAY2"].'	';
                $tbody .=''.$row["DAY3"].'	';
                $tbody .=''.$row["DAY4"].'	';
                $tbody .=''.$row["DAY5"].'	';

                @$tbody .='
';
             }
        }
        catch ( PDOException $e ) {
        echo $e->getMessage();
        $pdo = null;
        }
?>

now how can i filter my table when the dropdown Fmonth is change? And it must only filter the selected team in
 which is gableTeam. (I only put one team for a sample but in my real code there's a 10 teams to filter).
I don't know what to put inside
    $(document).on('change','#Fmonth',function(){
    ////what should be in here

});

any help?

A: I assume that month will be the same for all your teams. So, you can use a tag and onclick of that you can get id i.e: teamname, then on change of dropdown, you can passed both month and teamname to your page where you are fetching the data depending on that.
Related Code:
var teamname = "";
// onclick of 'a' event
$(document).on('click', 'a', function() {
    //getting id value i.e: your teamname
    var teamname = $(this).attr('id');

    //getting fmonth value on change event
    $('#Fmonth').change(function() {
        var Fmonth = $('#Fmonth').val();
        alert(Fmonth);
        alert(teamname);
        if (teamname != '') {
            $.ajax({
                type: 'post',
                url: 'read_gable.php',
                data: {
                    'month': Fmonth,
                    'team': teamname //<-passing team value
                },

                success: function(data) {
                    $("#containerDiv").html(data)
                    $("#containerDiv").hide().fadeIn(500)
                    //alert(Fmonth);
                },
                error: function(data) {
                    alert('Failed');
                }
            });
        }
    });

});


text:
Q: MySQL if/else for tables Is there a way to if else tables in mysql?
Example:
select * from tableA A, if(tableA.find=1,TableBA B,TableBB B) where A.id = B.aid

Real Example:
tables are: location_order, order_contract, order_gm, order_gm_hh:
select *
from   location order lo, order_contract oc, if(lo.hh=0,order_gm,order_gm_hh) as og
where  lo.orderid = oc.orderid && oc.gmid = og.id

A: You can left outer join both tables, and then use the IF() function in the SELECT clause:
SELECT     a.*,
           IF(a.find = 1, b1.value, b2.value) b_value
FROM       tableA a
LEFT JOIN  tableBA b1 ON (b1.aid = a.id)
LEFT JOIN  tableBB b2 ON (b2.aid = a.id);

Test case:
CREATE TABLE tableA (id int, find int, value int);
CREATE TABLE tableBA (id int, aid int, value int);
CREATE TABLE tableBB (id int, aid int, value int);

INSERT INTO tableA VALUES (1, 1, 100);
INSERT INTO tableA VALUES (2, 0, 200);
INSERT INTO tableA VALUES (3, 1, 300);
INSERT INTO tableA VALUES (4, 0, 400);

INSERT INTO tableBA VALUES (1, 1, 10);
INSERT INTO tableBA VALUES (2, 3, 20);

INSERT INTO tableBB VALUES (1, 2, 30);
INSERT INTO tableBB VALUES (2, 4, 40);

Result:
+------+------+-------+---------+
| id   | find | value | b_value |
+------+------+-------+---------+
|    1 |    0 |   100 |      10 |
|    2 |    1 |   200 |      30 |
|    3 |    0 |   300 |      20 |
|    4 |    1 |   400 |      40 |
+------+------+-------+---------+
4 rows in set (0.00 sec)

A: You could have to separate this out into two select statements. For example:
select * from tableA A
inner join TableBA B on A.id = B.aid
where A.find = 1

UNION

select * from tableA A
inner join TableBB B on A.id = B.aid
where A.find <> 1

A: Do an outer join on both tables and use a case statement in the select to pull the value from whichever table meets the Find=1 criteria using a case statement.
SELECT     Case A.Find
              WHEN 1 THEN B1.SomeField
              ELSE B2.SomeField
           END as SomeField
FROM       tableA A
LEFT JOIN  tableBA b1 ON (b1.aid = A.id)
LEFT JOIN  tableBB b2 ON (b2.aid = A.id);


text:
Q: Find next Date/Time in JPA query I need to return the next meeting for a user. For example, to userId 1, the next meeting will be today (MeetingId 1), because today is 02-12-2019 13:12PM. If I search for the next meeting today at 15:00PM,  the next meeting will be at 09-12-2019 (MeetingiD 2). If I search for the next meeting tomorrow, the next meeting will be at 09-12-2019 (MeetingiD 2).

I'm using MYSQL database and the query (but I don't know how to search exactly):
@Query(select m from meeting m inner join m.group g inner join g.user u where u.id = :userId order by m.meetingDate desc)
Meeting getNextMeeting(@Param(userId) long userId)

public class Meeting {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id;
    @OneToMany()
    private Group group;
    private Date meetingDate;
    private Time meeting;
}

public class Group {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id;
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "userId",nullable = false)
    private User user;
}

public class User {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id;
}

A: To get only one next meeting, You need to filter out all the future event using the below condition and limit 1.
Below query works, if you are using Postgres
(date m.date + time m.time) > CURRENT_TIMESTAMP and limit 1

A: Mysql has now() function that returns current date.
Ref: https://www.w3schools.com/sql/func_mysql_now.asp
Try this query:
@Query("select m from meeting m inner join m.group g inner join g.user u where u.id = :userId and m.meetingDate > now() order by m.meetingDate asc")
List<Meeting> getNextMeetings(@Param(userId) long userId)

You sorting should be ascending(from the closest date to now to the farthest). Query will return list of entities. I would suggest you to check the order in result query and take the first entity from the list -> list.get(0). Otherwise, you can sort it by yourself and take the first.


text:
Q: Java Interface vs Class as return type Let's say we've got inner class (rest of the code isn't really important I guess, DataStructureIterator is just the interface extended by java.util.Iterator<Integer>):
private class EvenIterator implements DataStructureIterator.
Now we want to create a method returning new instance of EvenIterator. As I noticed we can do it in various ways:

*

*public EvenIterator getEvenIterator(){return new EvenIterator();}

*public DataStructureIterator getEvenIterator() {return new EvenIterator();}
I found out that both versions of the code compiles well, but I just can't get what's the difference (if there's any) between them and which version should be used.

A: It depends. If your method contract is such that you're saying that you're returning some kind of iterator (i.e., not a specific implementation), then return the interface. In other words, your contract is saying "don't assume any other behavior/functionality other than the ability to iterate over integers". The advantage here is that you can then swap out the underlying implementation for something else later. Callers don't and should not care.
On the other hand, if your method's contract is that you return an iterator that specifically provides the ability to iterate only over even integers, return EvenIterator. This necessarily means you cannot swap out the implementation (to something that doesn't iterate over even integers), and doing so implies breaking/changing the contract. You could abstract further and make EvenIterator an interface itself and provide different implementations for the iterator (perhaps one iterates over an internal linked-list, another over an internal array, or perhaps you provide the ability to iterate over specific kinds of even integers; e.g., powers of 2 vs. powers or 4).


text:
Q: SELECT JOIN two tables with multible rows in one row i got a CSV file from the post of swizerland with all addresses. For the usecase we only need about 10% of the includet data. I try now to merge and cut out not needet data.
Swizerland uses 3 different languages for some citys / street-names. The main-table includes always the spoken language from the city. In a second table there is one row for the second, and a second row for the third language.
At the end I want something like this as output:
PID | ZIP_CODE | DE_CITY | FR_CITY | IT_CITY
My query looks like that:
SELECT
   NEW_PLZ1.ONRP,
   case
       when NEW_PLZ1.SPRACHCODE = '1' then NEW_PLZ1.ORTBEZ18
       when NEW_PLZ2.SPRACHCODE = '1' then NEW_PLZ2.ORTBEZ18
   end as 'DE_CITY',
    case
        when NEW_PLZ1.SPRACHCODE = '2' then NEW_PLZ1.ORTBEZ18
        when NEW_PLZ2.SPRACHCODE = '2' then NEW_PLZ2.ORTBEZ18
    end as 'FR_CITY',
    case
        when NEW_PLZ1.SPRACHCODE = '3' then NEW_PLZ1.ORTBEZ18
        when NEW_PLZ2.SPRACHCODE = '3' then NEW_PLZ2.ORTBEZ18
    end as 'IT_CITY'
FROM
    NEW_PLZ1
LEFT JOIN NEW_PLZ2 ON NEW_PLZ1.ONRP = NEW_PLZ2.ONRP;

ONRP is the primary key and FK in both tables. SPRACHCODE is 1 for german, 2 for french, 3 for italian.
With the query above I get the result I wish - but one language is always a seperate row (because of the join table with 2 rows)
I tried then use GROUP BY ONRP but getting the following error:
[42000][1055] Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'adressen.NEW_PLZ2.SPRACHCODE' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
I found on stackoverflow following:
-disable strict mode:
this worked to execute the query. but the result is not good. (missing data, wrong data)
-add all used fields in GROUP BY
this worked also to execute query. But also with missing data or wrong data.
Atm my creativity is broken to try out how to solve that. I dont know what else keywords i can search here which would help me.
I'm happy for advice to:
resolve my brainbreaker for the group-by and why its not working or how to do the query for wished output in other way.
important: the query will not be in production env. It will be used only to create a new database/table with the needet data.
Thanks a lot for help

A: Use an Aggregation function
Of course you must test different functions till you get your result
SELECT
   NEW_PLZ1.ONRP,
   MAX(case
       when NEW_PLZ1.SPRACHCODE = '1' then NEW_PLZ1.ORTBEZ18
       when NEW_PLZ2.SPRACHCODE = '1' then NEW_PLZ2.ORTBEZ18
   end) as 'DE_CITY',
    MAX(case
        when NEW_PLZ1.SPRACHCODE = '2' then NEW_PLZ1.ORTBEZ18
        when NEW_PLZ2.SPRACHCODE = '2' then NEW_PLZ2.ORTBEZ18
    end) as 'FR_CITY',
    MAX(case
        when NEW_PLZ1.SPRACHCODE = '3' then NEW_PLZ1.ORTBEZ18
        when NEW_PLZ2.SPRACHCODE = '3' then NEW_PLZ2.ORTBEZ18
    end) as 'IT_CITY'
FROM
    NEW_PLZ1
LEFT JOIN NEW_PLZ2 ON NEW_PLZ1.ONRP = NEW_PLZ2.ONRP
GROUP BY NEW_PLZ1.ONRP;


text:
Q: Android: Trigger unhover on link If a link in android is clicked and has e.preventDefault() attached to it, it will still remain hovered after the click. Is it possible to trigger unhover?
Doesn't work:
$('testElement').on('touchend', function () {
  $(this).trigger('mouseout');
});


text:
Q: Should I consider parallelism in statistic callculations? we are going to implement software for various statistic analysis, in Java. The main concept is to get array of points on graph, then iterate thru it and find some results (like looking for longest rising sequence and various indicators).
Problem: lot of data
Problem2: must also work at client's PC, not only server (no specific server tuning possible)
Partial solution: do computation on background and let user stare at empty screen waiting for result :(
Question: Is there way how to increase performance of computation itself (lots of iterations) using parallelism? If so, please provide links to articles, samples, whatever usable here ...

A: The main point to use parallel processing is a presence of large amount of data or large computations that can be performed without each other. For example, you can count factorial of a 10000 with many threads by splitting it on parts 1..1000, 1001..2000, 2001..3000, etc., processing each part and then accumulating results with *. On the other hand, you cannot split the task of computing big Fibonacci number, since later ones depend on previous.
Same for large amounts of data. If you have collected array of points and want to find some concrete points (bigger then some constant, max of all) or just collect statistical information (sum of coordinates, number of occurrences), use parallel computations. If you need to collect "ongoing" information (longest rising sequence)... well, this is still possible, but much harder.
The difference between servers and client PCs is that client PCs doesn't have many cores, and parallel computations on single core will only decrease performance, not increase. So, do not create more threads than the number of user PC's cores is (same for computing clusters: do not split the task on more subtasks than the number of computers in cluster is).
Hadoop's MapReduce allows you to create parallel computations efficiently. You can also search for more specific Java libraries which allow evaluating in parallel. For example, Parallel Colt implements high performance concurrent algorithms for work with big matrices, and there're lots of such libraries for many data representations.

A: In addition to what Roman said, you should see whether the client's PC has multiple CPUs/CPU cores/hyperthreading. If there's just a single CPU with a single core and no hyperthreading, you won't benefit from parallelizing a computation. Otherwise, it depends on the nature of your computation.
If you are going to parallelize, make sure to use Java 1.5+ so that you can use the concurrency API. At runtime, determine the number of CPU cores like Runtime.getRuntime().availableProcessors(). For most tasks, you will want to create a thread pool with that many threads like Executors.newFixedThreadPool(numThreads) and submit tasks to the Executor. In order to get more specific, you will have to provide information about your particular computation, as Roman suggested.

A: If the problem you're going to solve is naturally parallelizable then there's a way to use multithreading to improve performance.
If there are many parts which should be computed serially (i.e. you can't compute the second part until the first part is computed) then multithreading isn't the way to go.
Describe the concrete problem and, maybe, we'll be able to provide you more help.


text:
Q: Why doesn't my opamp work? I need to display the voltage at the probe, varying the Vout1 from 0 to 67mV and I expect the voltage to be 0.1V to 0.5,  but my simulation stops way before 0.5V. I have checked the calculations and they are correct, also tried with an ideal opamp and it works.
How can I solve this, any ideas?

EDIT:

*

*It's supposed to display at the probe a voltage of 100mV when the Vout is 0 and a voltage of 0.2 mV when the vout is 67mV.

*It controls the gain of the Vout.
Actually it works when I use the ideal opamp, my question is what kind of opamp should I use to get my results..

A: This is not an answer - yet. This is just to tidy up the schematic and maybe help you see what you have done wrong.

simulate this circuit – Schematic created using CircuitLab
Figure 1. OP's schematic redrawn.
You need to edit your question to explain:

*

*What is the circuit supposed to do?

*What is R14 supposed to do?


text:
Q: Dual functor and homology of projective modules Let $$P_1\xrightarrow{f} P_2\xrightarrow{g} P_3$$ be a complex of projective modules over a ring $A$ (We assume that $gf=0$) and let $H=\frac{Ker g}{Im f}$ be a projective module. Let $-^*=Hom(-,A)$ stand for the dual functor and let $$P_3^*\xrightarrow{g^*} P_2^*\xrightarrow{f^*} P_1^*$$ be the dual complex.  Is it true that $\frac{Ker f^*}{Im g^*}=H^*$?

A: no. $\newcommand{\Z}{\mathbb Z}\newcommand{\im}{\mathrm{Im}\,}$
take $P_1=0,\,$  $P_2=P_3=\Z\,$  and $g:P_2\to P_3,x\mapsto2x.\,\,$
we have $H^*=H=0\,$ because $\ker g=0,\,$ but $\frac{\ker f^*}{\im g^*}=\Z/2\Z\,$  since $g^*(y)=2y$.
in fact, any projective resolution computing nontrivial ext gives a counterexample, this is a usual thing in homological algebra.


text:
Q: NodeJS Post request using a Button I don't know if this is possible or not. All the research I've done has shown that it is possible with a form and text input. But anyways, Using NodeJs & Express I want to be able to click a button on my webpage, and once it's clicked, it sends a post request to my Node.JS server.
Simpler way of saying it:
When button is clicked, send info to the server.
Goal I'm trying to achieve:
When button is clicked, it sends some sort of ID/code/anything to turn on a service from my database. (I have yet to learn how db's work so I am just trying to focus on front end.)
Code I have so far:
app.post("/send", function(req, res){
  var newID = req.body.ID;
  res.redirect("/action")
});

<form action="/send" method="POST">
    <input type="button" name="newID" placeholder="Button">
    <button>send</button>
</form>

A: You do not need to use jQuery or AJAX.
Simply add an input of type submit inside the form tag so that the POST request defined by your form tag is submitted.
Your newID input should be of type text, this allows entering a value in the input field.
The newID value can be retrieved server side with req.body.newID (be sure to use the body-parser middleware).
<form action="/send" method="POST">
    <input type="text" name="newID" placeholder="Enter your ID"/>
    <input type="submit" value="Click here to submit the form"/>
</form>

A: For this purposes you should use $.ajax,
example:
$('button').on('click', function() {
    $.ajax({
      type: 'POST',
      url: '/send',
      data: { ID: 'someid' },
      success: function(resultData) {
         alert(resultData);
      }
    });
});


text:
Q: My program doesn't excute even installed runtime package I published my program(.net core 3.1 winform program). but it doesnt excuted even installed .net core 3.1 run-time package. so i install .net core 3.1 sdk package, it works.
why i install sdk instead of run-time package?

A: The software development kit (SDK) includes everything you need to build and run . NET Core applications, using command line tools and any editor (including Visual Studio). The runtime includes just the resources required to run existing

A: There was a problem creating a single file by using app.config in the wrong way.
When app.config was used in the correct way, it was confirmed that it works normally only with the runtime sdk.
Previously, both *.dll.config and *.dll were required, but after correcting it, only *.dll.config worked normally.


text:
Q: How to understand "State of the application should be stored in a file"? I have been learning Java on my own for a while, and I finally received a recruitment task, where I'm supposed to create a program in which user can order a pizza, or a few pizzas, with option to customize its ingredients. Now, I believe I understand all but one requirement, that is "State of the application should be stored in a file". I'm not sure how to approach this, so far I came up with generating a .txt file after each order is submitted, containing:

*

*Name of the user that made the order (also a requirement listed in the task);

*List of pizzas, each with its own list of ingredients (one of the requirements is to be able to add/remove ingredients from pizzas).
And files would be named something along the lines "Pizza order" + user name + HH:MM of file creation.
I would ask for clarifications, but I'm worried that this may be something trivial, and subsequently disqualify me from the recruitment process.


text:
Q: How to detect changes for the inner elements of an ASP.NET AJAX control? Within a custom ASP.NET AJAX control, I'm trying to get all of the inner inputs of the element that represents the container, and detect their changes.
The following works only in IE 9 and FF:
if (this.get_watchChanges()) {
    $(this.get_element()).find(":input").change(function() {
         //mark dirty
    });
}

Looking for input elements with the type of text and checkbox is not working for me at all.
What's a good cross-browser way to detect a change for inner elements of a parent element?

A: I realize this is quite old, just stumbled on it and thought I'd through something up for the next guy.  Would something like this work?
<script type="text/javascript">
   var isDirty = false;
   $(document).ready(function() {
      isDirty = false;
      $("input, input[@type=checkbox]").change(function() {
         isDirty = true;
      });
   });
</script>

A: I ended up adding something targeting the various types of controls (since I was using Telerik).  I can't post the result, but I ended up doing something like:
$(".RadDatePicker").each(function() { /* attach to date change event */ });

And so on for each control (targeting them by their CSS class.  The complexity came because of the ASP.NET AJAX framework, and how the JavaScript APIs worked.


text:
Q: How to use the -a option to pass a parameter to scrapy? I read the doc and find the command line should be like this.
scrapy runspider getspecificimg.py -a ip='lizhe'
And my spider code is like this :
class GetImage(scrapy.Spider):
    name = 'ImageSpider'
    start_urls = ['https://www.pexels.com/']

# Get the input argument
    # NameNeedSearch = InputPara
    NameNeedSearch = ip

But the result I get means that the ip isn't defined why?
20161211162649.bmp
-- update --
I want to pass in a variable then use it to concatenate the full url and use it as the start_url
My code is like this :  and get the error self is not defined why is that ?
class GetImage(scrapy.Spider):
    name = 'ImageSpider'
# Get the input argument
    NameNeedSearch = self.ip
    # startUrl = 'https://www.pexels.com/' +
    start_urls = ['https://www.pexels.com/']

A: You need to write your code using self in one of your GetImage class methods, for example __init__ or start_requests that are called when starting the crawl.
When called by the framework, these methods will get as first argument the class instance itself, available as the conventional self variable used in the method signature (it's just a convention):
class GetImage(scrapy.Spider):
    name = 'ImageSpider'
    start_urls = ['https://www.pexels.com/']

    def start_requests(self):
        # self points to the spider instance
        # that was initialized by the scrapy framework when starting a crawl
        #
        # spider instances are "augmented" with crawl arguments
        # available as instance attributes,
        # self.ip has the (string) value passed on the command line
        # with `-a ip=somevalue`
        for url in self.start_urls:
            yield scrapy.Request(url+self.ip, dont_filter=True)


text:
Q: navigateToURL, how to make it open new tab in browser instead of window (pop-up)? I've got a flash game, which is sponsored, so I have several buttons in the game that lead to my sponsors website. I used the following code on each of them:
navigateToURL(new URLRequest("http://www.sponsorsite.com"), "_blank");

Now, the problem is that every one of these buttons open up a new window which is most of the time and for most of the people getting blocked by their browser (or popup-blockers). One button however (the one button I got from my sponsor and load as an swf at runtime) is different, and instead of opening a new window it opens up a new tab, which never gets blocked.
I'm now trying for hours to emulate that buttons behaviour, but there really seems to be not difference. It uses the very same line of code as stated above. The only difference is that it was created in the Flash IDE, exported as a swf, and then imported into my game.
Do you have any idea how I can make 'navigateToURL' open up a new tab instead of new window in the users browser?


text:
Q: Android - cannot find library, installing through the Play Store I distributed the app to Play Store.
If I manually install the apk, it works normally.
However, if I proceed with the installation on the Play Store, it doesn't work.
error is

"/data/app/ package-name  /lib/arm64/ mylib .so" no such file or directory

Here's how I tried to solve the problem.
extractNativeLibs="true" set on mainfest
include("x86", "x86_64", "armeabi-v7a", "arm64-v8a") set on build.gradle
Check if the library is saved normally.
jni/CPU_ABI inside an AAR
lib/CPU_ABI inside the final APK
It works normally in the installation except for the Play Store.
An error occurs only when installed through the Play Store.
I checked the existence of the library through the following instructions.
ls /data/app/<package-nam>/lib/<system-abi>/
If there's anything I forgot, the apk should not be installed manually. I don't know why an error occurs only when installing through the Play Store.


text:
Q: What's the best approach to allow 2 user's browsers to communicate to each other I want to make an browser based chess game. Where 2 users take turns making moves on the same board.
At the moment I've set in motion a tomcat server with spring that picks up rest calls made by the node server.
However I'm making a rest call every time any user makes a move. Although the response happens very quickly as there is very little to be done on the server side.
But I feel this may not be the best approach. Is there a better alternative or would rest calls be sufficient in this scenario?

A: You can use the websocket.io with nodejs for the real-time communication between users.

If you don't want to use the server at all then you can use the webrtc that uses peer to peer connection.

Here are few useful references:
https://dev.to/rynobax_7/creating-a-multiplayer-game-with-webrtc
https://rynobax.github.io/jump-game
https://github.com/jwagner/webrtc-pong
https://www.webrtc-experiment.com/#featured

For Nodejs and socket.io
https://github.com/fbaiodias/phaser-multiplayer-game

Thanks


text:
Q: CSS Bottom not working correctly I have this sidebar that i'm trying to move to the bottom for mobile view devices. However, this isn't working correctly and instead is putting the sidebar at the top of the page. Could anyone help?

*some stuff*

*some more stuff*

#rightMenu {
    @media#{$medium-up} {
        float: right;
        width: auto;
        height: 0px;
    }

    @media#{$small-only} {
        width: auto;
        position: absolute;
        bottom: 0;
        left: 0;
    }
}

#checkoutForm {
    position: relative;
    height: auto;

    *some stuff*
}

A: My guess is that your "some stuff" in #checkoutForm are floating elements causing #checkoutForm not to force a size and subsequently having height 0px and looking like its rendering your absolute positioned element on the top.
Make sure this is not the case, a tried and tested technique to address that problem would be to use clearfix.
.clearfix:before,
.clearfix:after {
  content: "";
  display: table;
}

.clearfix:after {
  clear: both;
}

.clearfix {
  zoom: 1; /* ie 6/7 */
}

*some stuff*

*some more stuff*


text:
Q: Updating UI Activity in Thread here is my problem.  I am programming an android app, which needs to display the time the activity it is running.  Therefor I created a new Thread which is called from the activity.  However when I start the app in the emulator, it seems the Activity is never loaded.  Maybe you guys can help me here.  Here is the relevant code:
public class ActivityStartTracker extends ActivityBasic {
    TimerThread timer;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start);
        timer = new TimerThread();
    }

    protected void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver, new IntentFilter(
                ServiceLocator.BROADCAST_ACTION));
        timer.run();
    }

    protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
        if (timer.isRunning()) {
            timer.interrupt();
        }
    }

    class TimerThread extends Thread {
        boolean isRunning = false;

        public TimerThread() {
        }

        @Override
        public void run() {
            int seconds = 0;
            isRunning = true;
            while (isRunning) {
                try {
                    Log.d(TAG, "Timer is running for : " + seconds);
                    seconds++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    isRunning = false;
                }
            }
        }

        public boolean isRunning() {
            return isRunning;
        }
    }
}

Like I said, these are the relevant code fragments.
The problem is, if I run this, the Activity stays black - I just get the header with the name of the app, thats all.  With the logging I can confirm that the thread is running, but nothing else is displayed.
Can you please help me out, I am rather new to android.
Thank you very much - already in advance.

A: Calling timer#run() will do just that, call the #run() method in the UI thread. You need to start your thread by calling #start() on it instead - the new thread will then do what you expect.
Further: Do not ever call Thread#start() twice, it won't actually restart the thread, just crash your application. If you intend to start the Thread from your onResume you need to allocate a new thread there.
Btw, consider using an AsyncTask instead.
Br,
Jens

A: keep on your mind that the only thread that can update the UI is the UIThread .
So if you want to modify the UI in another thread, you should the method : runOnUIThread()
, but when you have a thread that will update the UI , the best way is to use AsyncTask ; refer this


text:
Q: So bad at math sometimes I feel depressed about it. I taught myself how to count before I even learned how to talk or read. Playing with numbers was all I did when I was young. I didn't have anyone to foster that type of passion that I believe I still have.
I went to a school where teachers didn't care about math, mostly because none of them knew how to do it. It wasn't until I had started secondary school, in 8th grade, that I finally knew how a fraction works or what it does. My bad luck doesn't stop there; after going to high school, my 6th, 7th, and 8th grade math teachers were so bad at math that they aren't even allowed to teach mathematics anymore today. They genuinely did not do anything. My knowledge was a reflection of this.
When I was in 9th grade I started learning how to do Algebra because we got a new teacher. I actually learned something. From 9th to 11th grade I taught myself how to do math up to a Calculus 1 level. It was very hard in such a quick period of time. I saw some improvements. The textbooks we used are the worst in the country because the school I go to is poor. I can't afford a tutor because I don't have hundreds of dollars to spare every week for it.
I've just finished 11th grade. I dropped math completely. The highest mark for the yearly was 100%, to someone who goes tutoring. The highest mark for non-tutor students was 53%. That person spent his whole two weeks doing nothing but math, but only got 53%. Nearby schools meanwhile get averages of min. 90%, easily.
But I still want to do math, and I don't know how to continue this. What should I do? I think about it a lot and I feel so depressed and embarrassed knowing how bad at math I am. I don't think it's hard to self-teach with my level of understanding, but I need the right book that has everything. I think I am at a level were I can take matters into my own hands.
I know this site hates these types of questions, but sorry, I don't know where else to come. What should I do in my situation? Khan Academy is bad for my case. It teaches a lot of concepts, but all at a basic level. I need something that goes from the ground - up. I want to master Calculus 3 by the end of the year.

A: I think it is safe to say that most of us study math because we all love it. Since you've already have some experience in self-learning, I think you should go on and pursue your dreams, study what you like. You will always find someone who knows more math than you, and this is ok. This goes for all of us. Try to learn from these people, befriend them. On the other hand, you'll always know something these people don't.
I don't like to think that studying math is a competition. Study for yourself, try always hard to be the best you can. What's the point of studying what you like and being unhappy with it?
Since Khan Academy is too basic, take a look at MIT videos. You can search for books here. Go for it.


text:
Q: PyQGIS - importing features selected by location from online GeoJSON file There is a large GeoJSON file stored online with thousands of geometries and I have created and stored a simple polygon .shp file that is the area of interest.
Is there a way to use PyQGIS to import into a QGIS project only the GeoJSON features that are within the polygon shapefile, as if it was a simple selectByLocation?
I know that the code part for the selectByLocation would be:
parameters = {'INPUT':'layer','PREDICATE':[0],'INTERSECT':'polygon','METHOD':0}
processing.run("qgis:selectbylocation", parameters)

but I don't know how to manage the selection of features from an online source.


text:
Q: Regular expression comments multiline I would like to use Regular Expression for comments in multiline in C#. I have @"/[*][\w\d\s]+[*]/" but with that expression only comments the text that appears between /* */ in singleline not in multiline.
Singleline:
       /* xxxxxxxx */

Multiline:
       /*
       xxxxxxx
       */

I don't know if I could explain well, but any questions or if you can refer to somewhere that provides this information I would appreciate it.
EDIT
In my example I have in one class
.
.
.
    public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
    {
        List<ClassificationSpan> classifications = new List<ClassificationSpan>();
        string current = span.GetText();
        bool commentFound = false;
        foreach(var item in _colorTextoLanguage.Comments)
        {
            Regex reg = new Regex(item, RegexOptions.IgnoreCase);
            var matches = reg.Matches(current);
            for(int i=0;i<matches.Count;i++)
            {
                commentFound = true;
                Match m =matches[i];
                Span new_span = new Span(span.Start.Position + m.Index, current.Length - m.Index);
                SnapshotSpan new_snapshot = new SnapshotSpan(span.Snapshot, new_span);
                var newText = new_snapshot.GetText();
                classifications.Add(new ClassificationSpan(new_snapshot, _commentType));
            }
        }
        if(commentFound)
            return classifications;
        Classify(classifications, current, span, _colorTextoLanguage.Custom, _classificationType);
        Classify(classifications, current, span, _colorTextoLanguage.Quoted, _stringType);
        Classify(classifications, current, span, _colorTextoLanguage.Keywords, _keywordType);
        Classify(classifications, current, span, _colorTextoLanguage.IdentifierTypes, _identifierType);
        Classify(classifications, current, span, _colorTextoLanguage.Numeric, _numericType);
        return classifications;
    }

.
.
.
and other class with
class ColorTextoLanguage
{
    #region Member Variables

    private List<string> _comments = new List<string>();
    private List<string> _quoted = new List<string>();
    private List<string> _numeric = new List<string>();
    private List<string> _keywords = new List<string>();
    private List<string> _identiferTypes = new List<string>();
    private List<string> _custom = new List<string>();

    #region Properties

    public List<string> Comments
    {
        get{return _comments;}
    }

    public List<string> Quoted
    {
        get{return _quoted;}
    }

    public List<string> Numeric
    {
        get{return _numeric;}
    }

    public List<string> Keywords
    {
        get{return _keywords;}
    }

    public List<string> IdentifierTypes
    {
        get{return _identifierTypes;}
    }

    public List<string> Custom
    {
        get{return _custom;}
    }

    #endregion

    #region ctor

    public ColorTextoLanguage()
    {
        Initialize();
    }

    #endregion

    #region Methods
    private void Initialize()
    {
        _comments.Add("//");
        _comments.Add(@"/\*(?:(?!\*/)(?:.|[\r\n]+))*\*/");

        _quoted.Add(@"([""'])(?:\\\1|.)*?\1");

        _numeric.Add(@"\b\d+\b")

        _keywords.Add(@"\bif\b");
        _keywords.Add(@"\belse\b");
        _keywords.Add(@"\bforeach\b");
        _keywords.Add(@"\bswitch\b");
        _keywords.Add(@"\bcase\b");
        .
        .
        .

        _identifierTypes.Add(@"\bint\b");
        _identifierTypes.Add(@"\bdate\b");
        _identifierTypes.Add(@"\bstring\b");
        .
        .
        .

    }
    #endregion
    #endregion
};

Not sure if this helps, but from what I see is quite similar to your example.
Thanks in addvance

A: Try the regex:
/\*(?:(?!\*/).)*\*/

With RegexOptions.Singleline
new Regex(@"/\*(?:(?!\*/).)*\*/", RegexOptions.Singleline);

regex101 demo
(?:(?!\*/).)* will match any character except */
EDIT: Version which should work in both modes:
/\*(?:(?!\*/)(?:.|[\r\n]+))*\*/

A: /\*([^*]*\*)*?/

/\* Match a Forward Slash followed by an Asterisk
([^*]*\*)*? (Match everything that is NOT a literal asterisk zero to infinite times, then match a literal asterisk), do this lazily zero or infinite times
/ Match a Forward Slash.  If this fails, backtrack to the previous step and attempt one more lazy iteration.
Not only is this shorter and more clear, it also takes less Regex Steps to perform.  It is the most efficient way.
Note: There is no need to worry about collections.  But if you really care, you could make your group a non-capture group with ?:
    /\*(?:[^*]*\*)*?/

A: To match a multi line comment you need a simple regex like this:
Regex regex = new Regex(@"/\*.*?\*/", RegexOptions.Singleline);

Hope this helps you in your quest.

A: The issue it not the regex at all. The reason this is not working is the fact that only a single line of code is being passed into the GetClassificationSpans() function at any one time. I'm having the same issue as you and from the look of the code you have provided, we followed the same tutorial.
This is not really an answer, it'll just help you identify what the actual issue is.


text:
Q: How do I apply an icon to two form fields in Angular Material? I'm using angular material as my design framework. I'm prototyping the form fields for my website, and the form fields have an icon. Selecting the form field changes the color of the icon to indicate that it's been selected.
My question is I have two fields, side-by-side which both correspond to one icon. I have a first and last name field that both point to the same user icon.
When I choose the first name field, the icon turn blue.See screenshot
When I choose the last name field, the icon remains gray. See Screenshot
How do  I make it so that the user icon also changes blue with the last name field selected?

 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/angular-material/1.0.8/angular-material.css">
        <link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons">

                            <md-input-container class="md-icon-float" layout="row" flex-gt-sm>
                                First Name
                                <md-icon class="material-icons md-18 color-txt-gray">person</md-icon>
                                <input ng-model="user.firstname">
                            </md-input-container>

                            <md-input-container class="" flex-gt-sm>
                                Last Name
                                <input ng-model="user.lastname">
                            </md-input-container>

A: Without seeing the HTML, my guess would be you have two md-input-container elements and the first one has the icon in it, so that's why it turns blue when you focus on the first input field. You could still achieve what you want, but you have to add the same CSS manually to the icon when you focus/blur the 2nd input field.
Edit: After seeing the code, basically what I've just above. One way to do it would be to use a scope variable, and on the 2nd input field use ng-focus="focusingLastName = true", ng-blur="focusingLastName = false" combined with ng-class on the md-icon element in the 1st container. You'll probably have to create a class and just copy the same CSS that Angular Material would've added by default (I'm fairly certain it's just a simple color rule).


text:
Q: Event handling in Java (JTree + JButton) private void createEvents()
{
    menuFileExit.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent arg0)
        {
            System.exit(0);
        }
    });
    ////// Events on tree selection
    jtStoryViewer.addTreeSelectionListener(new TreeSelectionListener()
    {
        public void valueChanged(TreeSelectionEvent arg0)
        {
            DefaultMutableTreeNode selection = (DefaultMutableTreeNode) jtStoryViewer.getLastSelectedPathComponent();
            Object nodeObject = selection.getUserObject();

            ////// Checks if selected node is a String (only story title is a string)
            if(selection.getUserObject().getClass().getName() == "java.lang.String" )
            {
                tfTitle.setText(nodeObject.toString());

                ////// Action listener for Change Button
                btnChange.addActionListener(new ActionListener()
                {
                    ////// Title text swap
                    public void actionPerformed(ActionEvent arg0)
                    {
                        selection.setUserObject(tfTitle.getText());
                        ((DefaultTreeModel)jtStoryViewer.getModel()).nodeChanged(selection);
                    }
                });
            }
            ///// checks if the object is a chapter object
            if(selection.getUserObject().getClass().getName() == "ISW.common.Chapter")
            {
                Chapter chapter = (Chapter) selection.getUserObject();
                tfTitle.setText(chapter.toString());

                ////// Action listener for Change Button
                btnChange.addActionListener(new ActionListener()
                {
                    ////// Title text swap
                    public void actionPerformed(ActionEvent arg0)
                    {
                        chapter.setTitle(tfTitle.getText());
                        ((DefaultTreeModel)jtStoryViewer.getModel()).nodeChanged(selection);

                    }
                });
            }

        }
    });
}

I am using JTree to display and modify some objects. I added a TreeSelectionListener to get the object data on selection. For now I want to be able to change the title of an object, it works fine on first selection on the tree , I change the value in the text box and the "Change" button works just fine, but when I move on to next objects, the change button also modifies the value of all previously selected objects.
I guess it is caused due to my improper usage of the ActionListeners but I can't tell for sure and at this point I'm stuck.
Will be grateful for any hints.

A: Don't keep adding an ActionListener to the btnChange JButton within the TreeSelectionListener#valueChanged method.
This will cause the button to call EVERY ActionListener you have previously
Instead, give the btnChange a single ActionListener, when clicked, can act on the currently selected node (by checking the JTree it self).  You could have the TreeSelectionListener#valueChanged method enable or disable the btnChange based on the validity of the selection
Also, if(selection.getUserObject().getClass().getName() == "ISW.common.Chapter") isn't how String comparison is done in Java, instead you should use something more like if("ISW.common.Chapter".equals(selection.getUserObject().getClass().getName()))


text:
Q: How to switch context in Dragonfly I have tried the Python module for handling speech recognition Dragonfly and successfully run notepad example with Windows speech recognition. Now I would like to try something more general, but I cannot find how contexts are switched, i.e. grammars loaded. There are always lines like:
grammar = Grammar("Eclipse", context=DynamicContext(winContext, nixContext))
grammar.add_rule(rules)
grammar.load()

But the context is always tied to an executable or window title. How do I switch between grammars at will, like a word command or at least mouse click, key press?

A: Create a rule which calls a function which does this:
grammar.disable()
other_grammar.enable()

Have a look at grammar_base.py for other relevant functions.


text:
Q: Join two dataframes on the values present in a specific column in the name_data dataframe using koalas I am trying to join two the dataframes as shown below on the code column values present in the name_data dataframe.
I have two dataframes shown below and I expect to have a resulting dataframe which would only have the rows from the `team_datadataframe where the correspondingcodevalue column is present in thename_data``` dataframe.
I am using koalas for this on databricks and I have the following code using the join operation.
import databricks.koalas as ks

name_data= ks.DataFrame({'code':['123a', '345b', '678c'],
        'id':[1, 2, 3]})

team_data = ks.DataFrame({'code':['123a', '23s', '34a'],
        'id':[1, 2, 3]})

team_data_filtered = team_data.join(name_data.set_index('code'), on='code')

display(team_data_filtered)

The expected output would be to see only the following in team_data_filtered.
Code    id
'123a'   1

But my code is throwing an error stating that  columns overlap but no suffix specified: ['id'].
May someone help to resolve this issue?

A: Try adding suffix parameters:
team_data_filtered = team_data.join(name_data.set_index('code'), on='code',
                                                lsuffix='_1', rsuffix='_2')
team_data_filtered = team_data_filtered.loc[team_data_filtered.id_1==team_data_filtered.id2]
display(team_data_filtered)

An then to clean the columns, if desired:
team_data_filtered.rename({'id_1':'id'}, inplace=True, axis=1)


text:
Q: Time formating troubles in CakePHP 3.x So i have my date in this format:

2014-02-15 16:38:30

And, that's how I'm trying to format it:
<?php echo $this->Time->format('F jS h:i A', $job->created); ?>

And the error:

DateTime::__construct(): Failed to parse time string (F jS hh:i A) at
  position 5 (h): Double timezone specification

How can I fix this Double timezone thing?

A: Please check the api for the right arguments of the TimeHelper format function:
http://api.cakephp.org/3.0/class-Cake.View.Helper.TimeHelper.html#_format
As you can se there, the first argument should be the data, and not the format. Moreover, it is better to just use the date object instead of the helper, for example:
echo $job->create

The date formatted there is controller by the the specified format as explained here:
http://book.cakephp.org/3.0/en/core-libraries/time.html#formatting
You can for example do
echo $job->created->nice();


text:
Q: .htaccess throwing Internal Server Error on Linux Environment Years ago, something around the boom of friendly-urls, guided by a Firefox extension which I think was from Yahoo! Developers, offering some optimization tips after analyzing the page, giving it a grade score (sorry, I don't remember the name) I've built this .htaccess file:
# Far-away Cache Expiration
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Expires "Thu, 15 Apr 2050 20:00:00 GMT"
</FilesMatch>

# Output Compression

<IfModule mod_deflate.c>

    <FilesMatch "\.(css|js|html|php)$">
        SetOutputFilter DEFLATE
    </FilesMatch>

</IfModule>

<IfModule mod_setenvif.c>
    # Netscape 4.x has some problems...
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    # Netscape 4.06-4.08 have some more problems
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    # MSIE masquerades as Netscape, but it is fine
    BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
    # Don't compress images or already compressed files
    SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI .(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI .(?:avi|mov|mp3|mp4|rm|flv|swf|mp?g)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI .pdf$ no-gzip dont-vary
</IfModule>

# Headers Fix

<IfModule mod_headers.c>
    # Make sure proxies don't deliver the wrong content
    Header append Vary User-Agent env=!dont-vary
</IfModule>

# ETag, whatever is that

Header unset ETag

FileETag None

# Rewrite Rules

RewriteEngine On

RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php [L]

Since then I've been using it in every PHP project and I've been scoring a Grade A all the time. But I used to develop always in a Windows environment.
Yesterday, for the first time, I managed to install Linux Mint and setup a development environment in a Virtual Machine.
Despite all the problems a newcomer faces in a different OS, when I tested one of the projects which was working fine in Windows, I received an Internal Server Error.
And, you may think this is ridiculous, but I never learned how to dig information from Apache's logs so I can't solve this issue by myself.
One thing I know is that if I remove everything above the RewriteEngine On line, Apache raises no error and the whole application works fine.
What could it be and, most important, why is this happening?
As requested in comments, the output of apachectl -l:
Compiled in modules:
  core.c
  mod_so.c
  mod_watchdog.c
  http_core.c
  mod_log_config.c
  mod_logio.c
  mod_version.c
  mod_unixd.c

And the output of apachectl -M:
Loaded Modules:
 core_module (static)
 so_module (static)
 watchdog_module (static)
 http_module (static)
 log_config_module (static)
 logio_module (static)
 version_module (static)
 unixd_module (static)
 access_compat_module (shared)
 alias_module (shared)
 auth_basic_module (shared)
 authn_core_module (shared)
 authn_file_module (shared)
 authz_core_module (shared)
 authz_host_module (shared)
 authz_user_module (shared)
 autoindex_module (shared)
 deflate_module (shared)
 dir_module (shared)
 env_module (shared)
 filter_module (shared)
 mime_module (shared)
 mpm_prefork_module (shared)
 negotiation_module (shared)
 php5_module (shared)
 rewrite_module (shared)
 setenvif_module (shared)
 status_module (shared)


text:
Q: TortoiseGit: Push to new remote branch I've set up a project to use TeamCity and Git, and I'd like to use TeamCity's new Branch Remote Run feature.  The way this work is to push your working directory to a remote branch that the TeamCity build is watching, e.g.:
git push origin +HEAD:remote-run/my_feature

What I think this is saying is "push HEAD to the remote branch remote-run/my_feature in the origin repository, creating it if necessary" (I would welcome clarification if that's even slightly incorrect).
My problem is that I'm using TortoiseGit with MSysGit set up to use PuTTY.  This is working fine, but it means I can't drop into Git Bash and issue the command through the command-line as Git Bash relies on OpenSSH.  I'm not up for re-installing MSysGit (and potentially TortoiseGit too).
So, what's the magical set of checkboxes and textboxes to get TortoiseGit to run a push as described above?

A: First make sure pageant is running and has your key loaded... Then you can set the windows env variable GIT_SSH to point to plink.exe and msysgit will use pageant. Link to walkthrough


text:
Q: Find sum of second values in key/value pair just started with PySpark
I have a key/value pair like following (key,(value1,value2))
I'd like to find a sum of value2 for each key
example of input data
 (22, (33, 17.0)),(22, (34, 15.0)),(20, (3, 5.5)),(20, (11, 0.0))

Thanks !

A: At the end I created a new RDD contains key,value2 only , then just sum values of the new RDD
sumRdd = rdd.map(lambda (x, (a, b)): (x, b))\
.groupByKey().mapValues(sum).collect()

A: If you would like to benefit from combiner this would be a better choice.
from operator import add
sumRdd = rdd.map(lambda (x, (a, b)): (x, b)).reduceByKey(add)


text:
Q: how to see pdf files in firefox window without disabling IDM When I triy to open any pdf files in firefox browser internet download manager captures its link and shows the prompt screen to download that file.
I want to open that pdf file in the browser itself without disabling IDM. Is there any shortcut key to do this?

A: 1.Open up IDM, click Options

2.In General tab of IDM's configuration window, click Keys button:

3.Check the check-box Prevent downloading with IDM ,choose any key combination you want.(YOU HAVE TO PRESS AND HOLD THESE KEYS WHILE OPENING A PDF LINK IN FIREFOX)

Another way:
In File types tab, just delete the PDF extension, the below picture shown means IDM will capture the PDF files, to read it in Browser, just delete PDF and click OK. You may have to restart Firefox

A: Press Ctrl + Alt (don't remove your finger from any of the keys) and then click on PDF file link, it will open your PDF in a separate tab.

A: An easy way is to click Alt button.
If you want to temporary disable IDM for single download you may hold Alt button while clicking on the download link to prevent IDM from taking the download.


text:
Q: Advice on a message handling system I'm currently putting together a game engine as part of a university module and one part of it is a message handling system. I'm looking to improve on the lecturer's implementation, so any advice or criticism of my possible changes is most welcome.
Current Message structure
struct Message
{
    Entity* entity;
    std::string message;
    void* data;

    Message(Entity* entity, std::string message, void* data):
        entity(entity), message(message), data(data) {}
};

The initial implementation only has messages being sent to Entities, but I plan on using an 'interface' to allow any component of the game engine to be able to receive messages.
class IMessageReceiver
{
public:
    virtual void handleMessage(const Message& message) {}
};

struct Message
{
    IMessageReceiver* receiver;
    std::string message;
    void* data;
};
//examples
class Entity : public IMessageReceiver { };
class Game : public IMessageReceiver { };

A problem I have with the current system is the void* for the data (I just don't like using void*). This is then cast to the type it needs to be inside the handleMessage function as I know what data it should be receiving (depending on the message string)- typically it has been either a 3D vector or an Entity up to this point, but if I have it sending messages to things other than Entities then this will likely change.
I wanted to change this to use a template instead; however, I'm not sure how I'd go about doing this.
template <typename T>
struct Message
{
    IMessageReceiver* receiver;
    std::string message;
    T* data;
};

I'm somewhat familiar with templates, on a basic level, but I'm likely lacking some deeper knowledge of template trickery. I know I could pass it the type of the data when I create a new message.
//example
Entity* entity;
vec3 someVec;
Message<vec3> message(entity, "Fire", someVec);
MessageHandler::sendMessage(message);

But how would I then write up the handleMessage function declaration in IMessageReceiver, as different implementing classes will have different data in the messages sent to them?
virtual void handleMessage(const Message<?>& message) {}

I had the thought of making IMessageReceiver a template class as well, so when a class inherits from it they set the type of data the messages they receive will be.
template <typename T>
class IMessageReceiver
{
public:
    virtual void handleMessage(const Message<T>& message) {}
};

class Entity : IMessageReceiver<vec3> {};

However, this means that a message receiver can only receive information of one type, but there could be an occasion where I might have to send data of different types to the same receiver- for example, a derived class of Entity usually receives a vec3 as the data part of the message but a new scenario requires it to receive another Entity.
Another issue with this I found is that only the abstract base class Entity inherits from IMessageReceiver (not every derived class of Entity and they receive different information of different types- or could), which would then mean making Entity a template class as well so this could be set by passing it on. But I would still have this inflexible system where something can only receive messages of one type of data.
Perhaps void* is the 'best' approach, and perhaps using an interface class is not. I don't know.
Please feel free to offer up any constructive criticism you can think of. I'm not asking someone to write it for me, I'm just looking for advice on a good way of implementing what I'm attempting to do. Basically, I want to be able to make any component of the engine be able to receive messages; the data that is sent in the message is not predefined; and preferably does not use void*.
Thank you for taking the time to read this. If you require any additional information please let me know.
Gavin

A: Virtual functions require the exact signature to be known at compile time, so you cannot use "template trickery" directly to achieve what you want.
Take a look at Boost.Any as a replacement for the void* Message::data.  It still requires a cast of sorts to convert it to the correct type, but it is done in a type safe manner.  Also, this way the message "owns" the data so you don't have to worry about lifetime issues.
Also, instead of using IMessageReceiver, consider std::function<void(const Message&)> instead.  That way, you can pass the message to any object that has a void operator()(const Message&), and you don't have bother with the complexity of a hierarchy.
Both boost::any and std::function internally use a technique known as type erasure which takes the inheritance out of the interface and allows you to treat things as values, which tends to make the code simpler to reason about.

A: Your pattern suggests that the sender knows the receiver and will send the message directly to a single receiver, so you could have the sender simply call the receiver's method directly and that method could be overloaded with "message"-specific parameters (which also solves the problem of which object "owns" the dynamically allocated message data).
A common reason for making a messaging system rather than directly calling methods on the target is to reduce coupling between objects.  The observer or publish/subscribe pattern reduces coupling by making the senders of messages (mostly) unaware of the receivers of the messages.  In this case, you need a way to abstract message details, which seems to be what the question is about.
You could have a virtual base class for a message, and derive message-specific types from it.  The handleMessage method could then take a pointer to the base class, and then use a dynamic_cast to downcast it to the concrete message type.  This is slightly nicer than passing a void* and doing an arbitrary cast, as you'd at least get some run-time type checking.
Another option is to have multiple overloads in your IMessageReceiver interface (which all have no-op implementations) and to have message senders simply call the specific method directly.  This gives you compile-time type checking, but requires a recompile whenever you invent a new "message" type.  (I put message in quotation marks because, in this scheme, you no longer need message objects.)


text:
Q: 2D Math Equation - Random operator with random integers Im trying to make a game where it players can answer math equations in a 2D way, almost like sudoku. The operands need to be randomised for each new games aswell as the operators. Ive gotten to the point where I can make it in a 1D array, but cant figure out how to solve both column and rowwise functions.. could anyone make some suggestions to point in the right direction..
i can upload my code if that helps..
Thanks in advance.
    int by4equations (int num[2][2] ) {

    srand( time(0) );
    num [2][2] = {
                {(rand() % 9+1),(rand() % 9+1)},
                {(rand() % 9+1),(rand() % 9+1)}
                    } ;

    int operator, sum = 0 ;
    int i, j ;

    operator = rand()%4 ;
}
    if (operator == 0)
        for(i = 0; i < 2; i++){
            for(j = 0; j < 2; j++){
        sum = num[i][j]  + num[i][j];
        }}

    else if (operator == 1){
        for(i = 0; i < 2; i++){
            for(j = 0; j < 2; j++){
        sum = num[i][j] * num[i][j];
        }}}

    else if (operator == 2){
        for(i = 0; i < 2; i++){
            for(j = 0; j < 2; j++){
        sum = num[i][j] / num[i][j] ;
        }}}

    else if  (operator == 3){
         for(i = 0; i < 2; i++){
            for(j = 0; j < 2; j++){
        sum = num[i][j] - num[i][j];
        }}}

edit : something like this is what i want https://www.google.com/url?sa=i&url=http%3A%2F%2Fwww.tamaraladamsauthor.com%2Fday-15-stuck-at-home-free-activity-math-square%2F&psig=AOvVaw3ohQWT7Hen-ewfXGvKSYVf&ust=1630711269359000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCJDq6oO34fICFQAAAAAdAAAAABAD


text:
Q: Load part of the post content asynchronously WordPress In each post, I load an audio file by making an http request to a third party service. I use the filter below and I make this request inside the add_before_content function.
add_filter('the_content', 'add_before_content');

This is causing a performance issue for us. Is there a way I can do that asynchronously so that the post content loads without the audio (and returned from the json-api without it) then the audio request/load later after the text content?


text:
Q: If a coin is selected, what is the probability that is was the 5th coin?
We have $10$ coins such that if the ith coin is flipped, it will
probability of heads of $\frac{i}{10}$ where $i=1,..,10$. We select a
coin at random, flip it, and we obtain heads. What is the probability
that it was the fifth coin??

Attempt
Call A event that the selected coin was the 5th and $B$ event that the coin showed heads after flip. We want to find $P(A \mid B)$. We have
$$ P(A \mid B) = \frac{ P(B \mid A) P(A) }{P(B \mid A) P(A) + P(B \mid A^c) P(A^c) } $$
Notice that $P(B \mid A) = \frac{5}{10} = \frac{1}{2}$ and $P(A) = \frac{1}{10}$. Similarly, $P(A^c) = \frac{9}{10}$. Now,
$$ P(B \mid A^c) = ....$$
If we condition on the event that the coin selected wasnt the fifth coin,  then it must have been one of the other 9th remaining? I get stuck on evaluating this probability. any hints? am I on the right direction?

A: As already discussed in the comments, your work so far is correct, but the denominator will be easier to evaluate if you sum over all $10$ cases instead of separating out the case $i=5$:
\begin{eqnarray*}
\mathsf P(I=5\mid B)
&=&
\frac{\mathsf P(B\mid I=5)\mathsf P(I=5)}{\mathsf P(B)}
\\
&=&
\frac{\mathsf P(B\mid I=5)\mathsf P(I=5)}{\sum_i\mathsf P(B\mid I=i)\mathsf P(I=i)}
\\
&=&
\frac{\frac12\cdot\frac1{10}}{\sum_i\frac1{10}\cdot\frac i{10}}\;.
\end{eqnarray*}
The sum in the denominator is just the average of the probabilities $\frac i{10}$, which is $\frac12\left(\frac1{10}+\frac{10}{10}\right)=\frac{11}{20}$, so
$$
\mathsf P(I=5\mid B)=\frac{\frac1{20}}{\frac{11}{20}}=\frac1{11}\;.
$$
You could obtain the result more easily by using symmetry: Add another coin with $i=0$. Then $P(B)=\frac12$ by symmetry, and $P(I=5\mid B)=\frac1{11}$ by symmetry. (By symmetry, the probability is the same whether you condition on heads or tails, and the average of those two equal conditional probabilities is the unconditional probability of picking $i=5$, which is $\frac1{11}$.) Now note that if you observe heads, you can exclude the possibility that the coin with $i=0$ was picked, so the problem reduces to your problem without the $i=0$ coin; hence the answer to your problem is also $\frac1{11}$.


text:
Q: dataTable does not show any data I'm trying to create a dataTable with my own data:
the code is like this:
<p:dataTable id="bufferData" >
    <p:column headerText="Info" style="width:140px;" >
        <h:outputText value="Total buffer size" />
        <h:outputText value="Entry size" />
        <h:outputText value="Number of entries" />
    </p:column>
    <p:column headerText="R-P Buffer" style="width:140px;">
            <h:outputText value="-" />
            <h:outputText value="-" />
            <h:outputText value="-" />
    </p:column>
    <p:column headerText="P-W Buffer" style="width:140px;">
            <h:outputText value="-" />
            <h:outputText value="-" />
            <h:outputText value="-" />
    </p:column>
</p:dataTable>

but when I run it I see an empty table.
I want to see my data, how can I ?

A: You must set the var and value attributes.
<p:dataTable var="car" value="#{dtBasicView.cars}">
//columns
</p:dataTable>

After that, you will need to bind value attribute with your managedbean.
See the doc and example on the datatable showcase.

A: You have missed few attributes to mention in dataTable tag.
<p:dataTable id="bufferData" value="#{managedBean.listOfObjects}" var="value">
    <p:column headerText="Info" style="width:140px;" >
        <h:outputText value="#{value.field1}" />
        <h:outputText value="#{value.field2}" />
    </p:column>

     // Columns .......

</p:dataTable>


text:
Q: Upgrading Spring Security breaks a project I have a template project I created long time ago. Project can be found on: here
All the libraries have been updated to a new versions expect spring security. If you checkout master branch go to localhost:8080/springdemo/index.htm application will redirect you to login page and once you enter demouser/demopass or userdemo/passdemo you will be logged in and redirected to index.htm.
Problem is when I update to Spring Security 4.2.3.RELEASE application does not work. This code is on spring-security-update branch. I tried a lot of online resources. Messed around with csrf token and disabled it for time being but was unable to get it to work.
Anybody has an idea why is spring security not working?
Thanks in advance

A: This is because of migration from version 3 to version 4. To make all this works you should do this:
1) in your index.jsp change form action from action='/springdemo/j_spring_security_check' to action='/springdemo/login'
2) in your index.jsp change input name from name='j_username' to name='username', same for name='j_password' -> name='password'
3) in your index.jsp change logout url from href="j_spring_security_logout" to href="logout"
Worked for me. Hope it helps


text:
Q: How to merge column output to the end of a row in the previous column? I have a .csv file containing three columns and I need to merge the value of column 2 with the end of the row of column 1.
The .csv file contains thousands of rows and this needs to be done for each row.
Iv'e tried using awk but I'm finding it difficult to get the code correct
cat file.csv | awk '{print $1, $2}'

awk '{if ($2!= " ") {print $1+$2 }}'

These of course don't work

Sample input:
The command used to produce the actual output is simply:
    cat test.csv
[2,4,5,6,2,34,61,32,34,54,34,       22]     0.144354
[3,4,6,4,5,6,7,1,2,3,4,53,23,       34]     0.332453
[2,43,6,2,1,2,5,8,9,0,8,6,34,       21]     0.347643

Desired Output:
             col1                       col2
[2,4,5,6,2,34,61,32,34,54,34,22]     0.144354
[3,4,6,4,5,6,7,1,2,3,4,53,23,34]     0.332453
[2,43,6,2,1,2,5,8,9,0,8,6,34,21]     0.347643

A: Replace "comma followed by one or more spaces" with "comma":
sed 's/, \{1,\}/,/' file.csv
sed 's/, */,/g' file.csv

Print columns $1 and $2 as $1 (optionally separate with a tab):
awk '{print $1 $2, $3}' OFS='\t' file.csv

A: You can try:
awk '{printf("%s%s\t%s\n",$1,$2,$3)}' file.cvs

A: I only see spaces after a comma when you don't want them.
$: sed -E 's/,\s+/,/' file.csv
[2,4,5,6,2,34,61,32,34,54,34,22]     0.144354
[3,4,6,4,5,6,7,1,2,3,4,53,23,34]     0.332453
[2,43,6,2,1,2,5,8,9,0,8,6,34,21]     0.347643

Add -i (after the -E) to make it an in-place edit.
$: sed -Ei 's/,\s+/,/' file.csv
$: cat file.csv
[2,4,5,6,2,34,61,32,34,54,34,22]     0.144354
[3,4,6,4,5,6,7,1,2,3,4,53,23,34]     0.332453
[2,43,6,2,1,2,5,8,9,0,8,6,34,21]     0.347643


text:
Q: Best algorithm for video stabilization I am creating a program to stabilize the video stream. At the moment, my program works based on the phase correlation algorithm. I'm calculating an offset between two images - base and current. Next I correct the current image according to the new coordinates. This program works, but the result is not satisfactory. The related links you may find that the treated video appears undesirable and shake the whole video is becoming worse.
Orininal video
Unshaked video
There is my current realisation:
Calculating offset between images:
Point2d calculate_offset_phase_optimized(Mat one, Mat& two) {

  if(two.type() != CV_64F) {
    cvtColor(two, two, CV_BGR2GRAY);
    two.convertTo(two, CV_64F);
  }

  cvtColor(one, one, CV_BGR2GRAY);
  one.convertTo(one, CV_64F);

  return phaseCorrelate(one, two);

}

Shifting image according this coordinate:
void move_image_roi_alt(Mat& img, Mat& trans, const Point2d& offset) {

  trans = Mat::zeros(img.size(), img.type());
  img(
    Rect(
        _0(static_cast<int>(offset.x)),
        _0(static_cast<int>(offset.y)),
        img.cols-abs(static_cast<int>(offset.x)),
        img.rows-abs(static_cast<int>(offset.y))
    )
  ).copyTo(trans(
    Rect(
        _0ia(static_cast<int>(offset.x)),
        _0ia(static_cast<int>(offset.y)),
        img.cols-abs(static_cast<int>(offset.x)),
        img.rows-abs(static_cast<int>(offset.y))
    )
  ));
}

int _0(const int x) {
  return x < 0 ? 0 : x;
}

int _0ia(const int x) {
  return x < 0 ? abs(x) : 0;
}

I was looking through the document authors stabilizer YouTube and algorithm based on corner detection seemed attractive, but I'm not entirely clear how it works.
So my question is how to effectively solve this problem.
One of the conditions - the program will run on slower computers, so heavy algorithms may not be suitable.
Thanks!
P.S.
I apologize for any mistakes in the text - it is an automatic translation.

A: You can use image descriptors such as SIFT in each frame and calculate robust matches between the frames. Then you can calculate homography between the frames and use that to align them. Using sparse features can lead to faster implementation than using a dense correlation.
Alternately, if you know the camera parameters you can calculate 3D positions of the points and of the cameras and reproject the images onto a stable projection plane. In the result, you also get a sparse 3D reconstruction of the scene (somewhat imprecise, usually it needs to be optimized to be usable). This is what e.g. Autostitch would do, but it is quite difficult to implement, however.
Note that the camera parameters can also be calculated, but that is even more difficult.

A: OpenCV can do it for you in 3 lines of code (it is definitely shortest way, may be even the best):
t = estimateRigidTransform(newFrame, referenceFrame, 0); // 0 means not all transformations (5 of 6)
if(!t.empty()){
    warpAffine(newFrame, stableFrame, t, Size(newFrame.cols, newFrame.rows)); // stableFrame should be stable now
}

You can turn off some kind of transformations by modifying matrix t, it can lead to more stable result. It is just core idea, then you can modify it in the way you want: change referenceFrame, smooth set of transformation parameters from matrix t etc.


text:
Q: Why am I getting a typescript compile error with Aurelia and Gulp? I am receiving the following error messages when running a gulp watch or gulp build command from VS Code.   This is an Aurelia application running in node.
typings\modules\aurelia-dependency-injection\index.d.ts(190,82): error TS1144: '{' or ';' expected.
typings\modules\aurelia-dependency-injection\index.d.ts(190,108): error TS1109: Expression expected.
typings\modules\aurelia-dependency-injection\index.d.ts(190,138): error TS1109: Expression expected.

--au help output
No Aurelia project found Global aurelia-cli v1.0.2
--npm version
6.9.0


text:
Q: NodeMCU Lua bme280: float values on integer build? How can I get float values from a BME280 on a integer build using the BME280 Lua module with bme280_math?
Using the deprecated bme280 c-Module, for instance, temperature values were: temperature in °C * 100, getting float values was like:
tempFloat = tostring(temp/100).."."..temp%100
Now, with bme280 Lua module and bme280_math, the temperature is returned in °C, so on an integer build readings are now "24" instead of "24378". How to get "24378" again?

A: The bme280 lua module used on an integer build will return integer values with 1°C resolution only.


text:
Q: Multiple axis to display day and month year with d3 scaleTime Thanks in advance.I am working with d3.js to create a chart. I want to have two axis on top. one should display month and year and another should display corresponding days for the month and as we zoom both the axis should be narrow down. Like on zoom month should be converted into days and days should be converted into hours. Please refer the below snapshot.

The box display the no of days and above the boxes it shows month and year.
Point 1 :  So when we zoom in, the days should be converted into the lower dimension which is hours and and month should display with day. Please refer the below snapshot

Point 2 : If I zomm more deep, it should come like this :

And if zoom out the scale for days and month should come back to their original form as it was in first snapshot.
My x-axis scale is like this :
        const xtimeScale = d3.scaleTime().domain([d3.min(chartdata, function (d) {
                                return parseTime(d.arrivalTime_data); }),
                           d3.max(chartdata, function (d) {
                                return parseTime(d.departureTime_data); })
                               ])
                           .range([0, WIDTH - MARGIN.LEFT - MARGIN.RIGHT]);

Where "chartdata" is an array of object having structure like this :
      {
              arrivalTime_data: "2020-12-19 14:01:26"
              departureTime_data: "2020-12-20 21:02:02"
              imo_data: "9632480"
              serviceName_data: "Service 1"
              short_service_name: "ML - Service"
              vesselName_data: " Ves_Tax"
       }

Can anyone please help me in achieving the same functionality. or can provide any fiddle for the same. Thanks

A: Basically, you would need to create two scale time x axis and then try zoom functionality.
Check this D3 time series graph- D3 timeseries graph


text:
Q: Magento Translation of option labels and values I have 6 store views for different languages.
My problem is, $_option['label'] and the $_option['value'] which are using in  product-view page, cart page, cart-sidebar, onepage-chekcout is always displaying the admin-side values and not the each language value.
Can anyone help on how to get the translated versions?
Thanks

A: You need to create translation files for each locale.
Put them in app/design/frontend/default/default/locale/.../translate.csv or wherever the appropriate locale directories are.

A: As i know you should have multiple store for multi language so you can assign option label through admin store wise from attribute management like below.
catalog >> Attributes >> Manage Attribute >> open attribute >> click on Manage Label /options tab.
After that define option label language store view wise


text:
Q: Creating shipping label not working with Fedex I integrated with FedEx shipping method in my website but when adding product to package while creating shipping label with this then i got below error:
Fatal error: Call to a member function hasErrors() on a non-object in /usr/www/users/sitename/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract.php on line 328
Can you please help me regarding this?
It's urgent!

A: That line uses a variable that should get an object from the method _doShipmentRequest that is extending the Abstract class. Since I'm not sure which module you are using you will have to check yourself where it fails.
It's probably a WSDL call that should be executed but is failing in some way. You will need to backtrace to figure that out


text:
Q: Reporting Services - Host header and Windows Authentication SQL 2016 - Enterprise Edition
Windows 2016
Reporting Services runs on domain account (SPN registered for new host header)
Problem:
When adding a host header in Reporting Services Configuration tool, like reports.server.net,  users need to login to the reporting services.
When I remove the host header and try to connect to hostname/reports I do not get prompted for user/password.
Fact:
 - When i use the default site address http://servername/Reports, before adding a new host header, the site opens up without login prompt
What I've done:

*

*Created a Host record in DNS for the new address, pointing at reporting services server

*Registered a SPN for the new host record to the service account for reporting service

*Added the new host header to reporting services for web service url and web portal url

*Played around authentication types in the reportserver.config file according to (https://learn.microsoft.com/en-us/sql/reporting-services/security/configure-windows-authentication-on-the-report-server?view=sql-server-ver15&viewFallbackFrom=sql-server-ver13)

*Enabled delegation for the reporting services service account "just in case"

I can't seem to add a host header without beening forced to login, despite above.
Anyone been here?

A: Solved issue by adding new host header address to local intranet site in the browser.