text:
Q: HTML table with two sticky columns and headers (using only CSS) I'm struggling to get two fixed columns and headers using a HTML table + scrollable body.
I've searched a lot and found these approaches:

*

*this (only 1 fixed column/header)

*and this (only 1 fixed column/header; no table markup)

*and I've also created my own solution using a library, which works fine, but I don't like how the html table tag markups getting messed up & moreover initializing the colModal is not that good since I've a dynamic amount of columns.

Since I am not satisfied with any of these solutions, I would like to know if there is a chance to get this job done only using CSS?

A: The closest I came is this.
No HTML table markup and no IE support.
I used position: sticky on the header and the first column.
The dimensions of the table are variable, but the widths of the cells need to be supplied.

A: I don't think that it's possible to achieve what I want only using CSS. So I've found another library called TableHeadFixer which does not duplicate nodes and IDs in your HTML markup.
So I came up with this final solution:
https://jsfiddle.net/4s53f124/2/
All you have to do is to call the tableHeadFixer method of the library (and if you want to some CSS adjusting):
 $(document).ready(function () {
     $("#fixTable").tableHeadFixer({"left": 2});
 });

A: One way to do this with only html and css is to add a second table within the first column where you add the first 2 columns and do the same way for the body. Maybe not the most elegant solution but it does the job with pure html and css.

thead tr>th {
  background: #eee;
  position: sticky;
  padding: .5rem;
  z-index: 2;
  top: 0;
  border-bottom: 1px solid black;
}

.sticky-column {
  border-right: 1px solid black;
}

.sticky-column tr>th {
  border-bottom: 0px solid black;
}

thead tr>.sticky-column {
  z-index: 3;
  left: 0;
  top: 0;
}

tbody tr>.sticky-column {
  background: #fff;
  position: sticky;
  z-index: 1;
  left: 0;
}

             Column 1

              Column 2

        Column 3

        Column 4

        Column 5

        Column 6

        Column 7

        Column 8

              Content 1

              Content 2

        Content 3

        Content 4

        Content 5

        Content 6

        Content 7

        Content 8

              Content 1

              Content 2

        Content 3

        Content 4

        Content 5

        Content 6

        Content 7

        Content 8

              Content 1

              Content 2

        Content 3

        Content 4

        Content 5

        Content 6

        Content 7

        Content 8

              Content 1

              Content 2

        Content 3

        Content 4

        Content 5

        Content 6

        Content 7

        Content 8

              Content 1

              Content 2

        Content 3

        Content 4

        Content 5

        Content 6

        Content 7

        Content 8

              Content 1

              Content 2

        Content 3

        Content 4

        Content 5

        Content 6

        Content 7

        Content 8

              Content 1

              Content 2

        Content 3

        Content 4

        Content 5

        Content 6

        Content 7

        Content 8

              Content 1

              Content 2

        Content 3

        Content 4

        Content 5

        Content 6

        Content 7

        Content 8


text:
Q: Does an endomorphism of $K^n$ always admit a stable strict subspace?
Does an endomorphism of $K^n$, with $n≥2$ and $K = \mathbb C$ or
  $\mathbb R$ or $\mathbb Q$, always admit a stable strict subspace?

I know that if $K = \mathbb C$, all endormphism has an eigenvector (so it is true). And that if $K = \mathbb R$, for all endomorphism there exists a line or a plane stable (so it is true for $n≥3$, for $n=2$ we can consider a rotation in the plane). What about $\mathbb Q$ ?

A: There is an $n\times n$ matrix $A$ with integer entries and minimal polynomial
$x^n-2$, which is irreducible. This means that $\Bbb Q^n$ can have
no nontrivial proper subspaces invariant under $A$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How and when did 8 bits win over 6 bits? Many older computers (such as the UNIVAC 2200 and PDP-15) had words that were multiples of 6 bits (18 and 36 bits being most common).
Octal was used a lot for these systems (an octal digit is three bits, so it fits nicely).
Modern systems have words which are multiples of 8 bits (8, 16, 32 and 64 being common).
Hex is used a lot for these systems (a hex digit is four bits, so it fits nicely).
How, when and why did this happen?
Was the octal->hex change causal or a consequence?
I have already read.


text:
Q: php preg_match find all lines which have match The string is:
#EXTM3U
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=350000
128/prog_index.m3u8?key=2dd12d6d79fa163d539952ec25c6c969&app=com.dcom&part=1-1
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=500000
256/prog_index.m3u8?key=2dd12d6d79fa163d539952ec25c6c969&app=com.dcom&part=1-1
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=750000
500/prog_index.m3u8?key=2dd12d6d79fa163d539952ec25c6c969&app=com.dcom&part=1-1
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1000000
750/prog_index.m3u8?key=2dd12d6d79fa163d539952ec25c6c969&app=com.dcom&part=1-1
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1250000
1000/prog_index.m3u8?key=2dd12d6d79fa163d539952ec25c6c969&app=com.dcom&part=1-1
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1750000
1500/prog_index.m3u8?key=2dd12d6d79fa163d539952ec25c6c969&app=com.dcom&part=1-1

And I want to find all prog_index.m3u8 urls. My code is:
preg_match_all('/(.*?)prog_index.m3u8(.*?)/mis', $get, $found);

A: My solution is:
preg_match_all('/^\d+.*prog_index.m3u8.*/mi', $get, $found);
print_r($found);

Basically include all lines that start with a number, but stop matching at the end of the line (thus the /mi instead of /mis).

A: You can do it without regex:
$result = array_filter(explode("\n", $get), function ($i) {
    return $i[0] != '#' &&
      array_pop(explode('/', parse_url($i, PHP_URL_PATH))) == 'prog_index.m3u8';
});

In this way you can be sure that the line is a URL with prog_index.m3u8 as filename.


text:
Q: Liferay: Get Unique session id on every login I'm writing a code to keep audit trails of every login on my application. For that, I'm getting session id from AuditRequestThreadLocal object by using auditRequestThreadLocal.getSessionID().
Problem is: It is giving same sessionId for user on every login(multiple login of same user).
Regarding that, I fetch sessionId from HttpRequest but It also returns same sessionId for that user on every login.
P.S. (In case of TOMCAT, It seems working fine but In the case of JBOSS it is returning same sessionId)
Thanks.

A: You can try with this solution:
inside the portlet.properties, set session.enable.phishing.protection=true :
#
# Set this to true to invalidate the session when a user logs into the
# portal. This helps prevents phishing. Set this to false if you need the
# guest user and the authenticated user to have the same session.
#
# Set this to false if the property "company.security.auth.requires.https"
# is set to true and you want to maintain the same credentials across HTTP
# and HTTPS sessions.
#
session.enable.phishing.protection=true

A: You can try apply in your portal-ext the next properties:
session.enable.phishing.protection=true
session.phishing.protected.attributes=OPEN_ID_CONNECT_SESSION


text:
Q: show only first 3 elements from a list and then show next 3 loop I have a list of 9 elemets (< li>)
What I'm trying to achieve is: show only the first 3 elements from the list, after 5 seconds hide the first 3 and show the next 3, then again hide these 3 and show the next 3, so hiding the current 3 and showing the next 3 loop..
Here is what I tried to write, but on my code I try to call the action on click of a link..
jQuery('#lbrecentcarousel li:gt(2)').hide();

jQuery('#lbrecentdiv h2 a').live('click',function() {
jQuery('#lbrecentcarousel li').not(':visible').each( function() {

    jQuery(this).slideDown();

});
});

Can somebody please help me on this... Thank you

A: Write:
setInterval(function(){
    var index = $("li:visible:last").index();
    var len = $("li").length;
    var open = 3;
    $("li:visible").hide();
    if(index == len-1){
        $("li:lt("+open+")").slideDown();
    }
    else{
        $("li").slice(index+1,index+open+1).slideDown();
    }
},1000);

Working demo here.

A: Thank you everybody, I sorted it by writing this code:
var elements = jQuery("#lbrecentcarousel li");
var index = 0;

var showNextThree = function (index) {
    if (index >= elements.length) {
        index = 0;
    }
    console.log(index);
    elements.hide().slice(index, index+3).fadeToggle();
    setTimeout(function () {
        showNextThree(index + 3)
    }, 5000);
}
showNextThree(0);


text:
Q: How to pass arguments to controller from route in Symfony2 I'm working on a Symfony2 project and am trying to figure out how to pass parameters from the route configuration to the controller.  I know I can configure default values in the route configuration, and retrieve the values in the controller using the appropriate var name in the function declaration, but that isn't exactly what I want.
My use case is the following.  I have a standard method in my controller that I want to access from 2 or 3 different routes.  Depending on which route is being called, I want to "configure" the method differently.  I can accomplish this in a few ways:

*

*In my controller, check the route name using `$this->container->get("request")->get("_route"), but that is ugly, and then I am hardcoded to the route name.  Moves configuration to the controller, which should just be logic - not configuration.

*Create a base controller class, and subclass each method for my different routes.  Each subclassed method would then have the necessary configuration within the method.  Cleaner soln than #1, but still "heavy" in the sense of having multiple classes for a simple need and still pushes configuration data into the business logic.

*Put configuration data into the route configuration.  In the controller, access the configuration data as required.  Ideal solution, but don't know how.

I can use the route default array to specify my arguments, but then must make sure to use a regex to ensure that the params are not overridden at the URL level (security risk).  This is functional, but still kinda cludgy and not a pretty hack.
I presume that there must a better way to do this, but I can't seem to figure it out.  Is there a way to access the routing object from the controller, and access the different configuration parameters?

A: You can pull the actual route from the router service.  Something like:
$routeName = $this->container->get("request")->get("_route");
$router = $this->container->get("router");
$route = $router->getRouteCollection()->get($routeName);

Not sure if this would be such a great design though.  Consider passing a $configName to your controller method, adding a parameter with the same name in a config file then using getParameter to access it.  That would eliminate the route stuff from the equation.
Something like:
zayso_arbiter_import:
    pattern:  /import
    defaults: { _controller: ZaysoArbiterBundle:Import:index, configName: 'someConfigName' }

public function importAction(Request $request, $configName)


text:
Q: Force php reading into an embed iframe field in Wordpress In my old Wordpress theme I've a special function that allow to insert a YouTube video with iFrame in the right side of Portofolio Posts.
But now I've to insert into this place (for each portfolio posts) a simple shortcode (different for each portfolio post) for a web audio player like this [disk_player id="2513"] .
This code cannot be read and it results as a simple line of text. Also the equivalent php code for the shortcode cannot be read (like this  <?php echo do_shortcode('[disk_player id="2513"]'); ?>.
I've also tried to add [raw] ... [/raw] tags before and after code but it doesn't work.
Can you help me to force the reading of the shortcode in this field?
Big thanks to everyone.
P

A: This is the code of right column:

                <?php if(obox_has_video($post->ID)):
                    $args  = array('postid' => $post->ID, 'width' => 660, 'height' => 660, 'hide_href' => true, 'exclude_video' => false, 'imglink' => false, 'wrap' => 'div', 'wrap_class' => 'post-image fitvid');
                    $image = get_obox_media($args);
                    echo $image;
                else : ?>

                        <?php $attach_args = array("post_type" => "attachment", "post_parent" => $post->ID, "numberposts" => "-1", "orderby" => "menu_order", "order" => "ASC");
                        $attachments = get_posts($attach_args);
                        foreach($attachments as $attachement => $this_attachment) :
                            $image = wp_get_attachment_image_src($this_attachment->ID, "660auto");
                            $full = wp_get_attachment_image_src($this_attachment->ID,  "full"); ?>

                                <a href="<?php echo $full[0]; ?>" rel="lightbox">
                                    <img src="<?php echo $image[0]; ?>" alt="<?php echo $this_attachment->post_title; ?>" />

                        <?php endforeach; ?>

                    <?php if(count($attachments) > 1) : ?>

                            <?php _e("Next", "ocmx") ?>
                            <?php _e("Previous", "ocmx") ?>

                    <?php endif; ?>
                <?php endif; ?>

And the theme is the 1st version of this: http://demo.oboxsites.com/retail-therapy/ (really different from mine).
Thank you


text:
Q: How to reduce the speed of this motor? I have an old Siemens motor with this specification :
220V
80W
0.65A
I need to reduce the speed (slow down) of this motor.
I know it's easy with something like an inverter, but I'm just wondering how about with just a resistor? If it is possible what are consequences? Is it bad for motor (damage or crash?)
If no, let me know how to slow down with resistor or something you suggest, please.

A: You can't really change the speed without changing the frequency of the AC.  That's a synchronous motor - it rotates at a fixed multiple of the line frequency.
If you lower the voltage (or reduce the current) but keep the load the same it will be forced to run slower - it hasn't got the power to force the load to rotate at its designed speed.  That is a bad thing.
If you lower the voltage some, then it will run slower under load but overheat and burn out.  If you lower it more, then it will stop and burn out under load.  If you lower it enough then it won't burn out, but it won't rotate, either.

I used to live in a house with low voltage (outlet voltage was like 90V when it should have been 110V.)  The synchronous motor in the water pump (we had our own well) burned out like three times in a year before my father could convince the power company to do sonething about the low voltage.

A: The motor is almost certainly an induction motor with a capacitor permanently connected to the auxiliary winding, a permanent-split-capacitor (PSC) motor. There is a marking that appears to be the capacitor rating (.1uF 400V?) in the lower left area area of the rating plate. It is possible to control the speed of such a motor to some extent by reducing the voltage with a series resistor or other means. That will work over a limited speed range it the load is a fan or a centrifugal pump that does not have too much static head. That would tend to increase the operating temperature of the motor, but that tendency is offset to some extent by the reduced torque load at reduced speeds. There are several similar questions here that have answers providing additional information.
speed-control-for-psc-induction-motor


text:
Q: Variable in PHP MYSQL query issue I have an SQL query in PHP where I am trying to pass a number into the where clause. If I pass the variable it doesn't work, however if I enter the variable manually it does work.
I tried converting to int and it still won't work.
 $numYear = '2017';
 $numMonth = '3';

 $query_select = "SELECT date, url, EXTRACT(YEAR FROM date) AS numYear, EXTRACT(MONTH FROM date) AS numMonth, MONTHNAME(date) AS nameMonth FROM pages WHERE (url LIKE 'newspage/%' AND url NOT LIKE 'newspage/') AND (YEAR(date) = '.$numYear.' AND MONTH(date) = '.$numMonth.' ) ORDER BY date DESC LIMIT 1";

Have I forgotten something?

A: Maybe You have just used dot so
$query_select = "SELECT url, summary, page_name, created_date, EXTRACT(YEAR FROM created_date) AS numYear, EXTRACT(MONTH FROM created_date) AS numMonth, MONTHNAME(created_date) AS nameMonth FROM pages WHERE (url LIKE 'news/%' AND url NOT LIKE 'news/') AND (YEAR(created_date) = '$numYear' AND MONTH(created_date) = '$numMonth' ) AND active = 1 ORDER BY created_date DESC LIMIT 1";

Check this.
P.S you should use prepared statements.

A: Datetime in where clause.
In datetime would have "" or ''
$DATE = "2017-12-31"
'SELECT * FROM Table WHERE date ='".$DATE."'ORDER BY ASE'

or
$DATE = "'".2017-12-31."'"
'SELECT * FROM Table WHERE date ='.$DATE


text:
Q: vb/aspx single-page model: how to implement server-side captcha while also post form data to another page? I'm using WebCaptcha However I cannot figure out how to do the POST to verify user captcha input and then in-the-same-post-pipeline also submit the form data to a different webpage only if captcha is correct. I know this is hard w/o full code but...yeah. Here is the button that fires the form:
<form runat="server" name="PDFfrm1" id="PDFfrm1" method="post" enableviewstate="false" action=""><!-- action="/Processor.aspx" -->

Empty action= posts page back to itself.
<asp:Button ID="btnSubmit" runat="server" Text=" Submit " Style="border-radius:8px" UseSubmitBehavior="false" OnClick="btnSubmit_Click" OnClientClick="" Width="6em" Height="3em" Borderstyle="Groove" Borderwidth="2" Font-Bold="true" BackColor="Navy" ForeColor="White" />

The UseSubmitBehavior= toggles the button between a normal button and a submit button. Note that Microsoft stuffs a Javascript __DoPostBack() function in the OnClientClick= section that you can block by adding "//" to that attribute.
Then:
Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
lblResult1.Text = "CAPTCHA verification passed, your request has been sent!"
Else
lblResult1.Text = "Sorry, the CAPTCHA text was not entered properly, try again."
End If
End Sub

I was thinking I would have to add code to the Page.IsValid section that does a server-side (ajax??) post to the other webpage because in order for the btnSubmit_Click() to get control, the current page has already done a post to itself and I don't know how to interrupt that pipeline. I cannot just do a Javascript POST then since the client is not in control at this stage.

A: The answer was simple: do Server.Transfer(URL, True) which preserves the existing session data from within the successful Page.IsValid test, allowing the destination page to read the form data as if it had done the POST.


text:
Q: aiohttp test with several servers Trying to do a test that communicates with several instances of a web-server (which also communicates between them). But the second one seems to override the first however I try. Any suggestions of how to solve this.
So far I have this:
import os
from aiohttp.test_utils import TestClient, TestServer, loop_context
import pytest
from http import HTTPStatus as hs

from mycode import main

@pytest.fixture
def cli(loop):
    app = main(["-t", "--location", "global", "-g"])
    srv = TestServer(app, port=40080)
    client = TestClient(srv, loop=loop)
    loop.run_until_complete(client.start_server())
    return client

@pytest.fixture
def cli_edge(loop):
    app = main(["-t", "--location", "edge", "-j", "http://127.0.0.1:40080"])
    srv = TestServer(app, port=40081)
    client = TestClient(srv, loop=loop)
    loop.run_until_complete(client.start_server())
    return client

async def test_edge_namespace(cli, cli_edge):
    resp = await cli.put('/do/something', json={})
    assert resp.status in [hs.OK, hs.CREATED, hs.NO_CONTENT]
    resp = await cli_edge.get('/do/something')
    assert resp.status in [hs.OK, hs.CREATED, hs.NO_CONTENT]

The above call to cli.put goes to the server intended for cli_edge. I will have several more tests that should communicate with the servers.
Using Python 3.7 and pytest with asyncio and aiohttp extensions.

A: The suggested code works, the error was elsewhere in the server implementation.
You can add:
def fin():
    loop.run_until_complete(srv.close())
    loop.run_until_complete(client.close())
request.addfinalizer(fin)

and the request param in the pytest fixtures to close connections nicely.


text:
Q: how to fetch 1 by 1 record from table in db2 sno acco_no amount

1    50001     5000
2    50002     4000
3    50001     2500
4    50002     3100
5    50002     3400
6    50001     1500

in which i want to take 50001's last 2 records one by one.
ie is result'd be :
sno acco_no amount
6 50001 1500-----> i want to move this record to variable1
3 50001 2500-----> i want to move this record to variable2

pls help me anyone

A: Use this to get only the last 2 records
select *
from tbl
where acco_no = 50001
order by sno desc
FETCH FIRST 2 ROWS ONLY;

Then in your code, store the first record into var 1 and the 2nd into var 2.


text:
Q: Managing multiple full calendars I am using the wonderful fullcalendar plugin for jQuery
But i am running into a few complications because i have multiple calendars on the same page.
Each calendar is inside a <div> that has its own id so identifying the proper calendar from the "global scope" is fairly simple.
My issue is actually getting my_custom_val for the current calendar from within its callback functions, such as select which is triggered when the user makes a selection on the calendar. Typically you would want a create event dialog appear after such an event, which is what i have, but for every calendar. Here is the doc for this callback http://arshaw.com/fullcalendar/docs/selection/select_callback/
I have found out that the options passed to the calendar on setup can be found with
$(calendar_id).data("fullCalendar").options.my_custom_option; but the problem is, i can't even figure out the calendar_id from within the select callback.
Here is the partial code related to this issue:
$(calendar_id).fullCalendar({
    my_custom_val: my_custom_val,
    select: function(start, end, allDay){
        // Process selection...
        // need to access my_custom_val here
        // from the global scope, if i know calendar_id, i can simply do
        // $(calendar_id).data("fullCalendar").options.my_custom_option
    }
});

Any suggestion is greatly appreciated, thanks

A: What's inside calendar_id? the value type?


text:
Q: Bugs with button+tooltip "pull-effect" When I move cursor on a camera, button is pulling. Why? Can I solve this problem?
http://jsfiddle.net/uDj9p/

    <button class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Отправить картинку">

    </button><button class="btn btn-default">

    </button>
    <button class="btn btn-default">

    </button>
    <button class="btn btn-default">

    </button>

A: Try adding the following CSS:
.btn {
    margin: 0 !important;
}

http://jsfiddle.net/uDj9p/15/
Sometimes there is a little flicker but not sure what's causing that yet.


text:
Q: how to write a data from vector to a text file at a particular position using c++? If my text file looks so..
usrname@gmail.com  3223434324 data1 data2
name@gamil.com     2343454454 data3 data4
I have read these values using vector.
I need to add a string at the end of first line of the file.
What should I do?
My code is as follows:
system("cls");
cout << "\nView proposal\n";
fstream file1;
string ap, aname, aphno;
file1.open("C:\\Users\\Nandhu\\Desktop\\glosys\\joinpolicy.txt",
    ios::in|ios::app);
while(!file1.eof())
{
    while(getline(file1, text))
    {
        istringstream xstream(text);
        vector<string> vcol;
        while(getline(xstream, word, ','))
        {
            vcol.push_back(word);
        }
        vec.push_back(vcol);
    }
    file1.close();
}
for(vector<vector<string> >::iterator itr = vec.begin();
    itr != vec.end(); itr++)
{
    for(vector<string>::iterator itr2 = itr->begin();
        itr2 != itr->end(); itr2++)
    {
        string str;
        str = *itr2;
        cout << str << " ";
    }
    cout << "\n";
}
cout << "\n1.Approve";
cout << "\n2.Reject";
cout << "\nDo you wish to approve?";
cin >> ans;
if(ans == 'y')
{
    file1.open("C:\\Users\\Nandhu\\Desktop\\glosys\\joinpolicy.txt",
        ios::in|ios::app);
    file1.seekg(0);
    cout << "\nEnter the customer id you wish to approve for:";
    cin >> aname;
    vec.clear();
    if(file1.is_open())
    {
        while(getline(file1, text))
        {
            istringstream xstream(text);
            vector<string> vcol;
            while(getline(xstream, word, ','))
            {
                vcol.push_back(word);
            }
            vec.push_back(vcol);
        }
        file1.close();
    }

    for(vector<vector<string> >::iterator itr = vec.begin();
        itr != vec.end(); itr++)
    {
        vector<vector<string> > vec;
        vector<string> vcol;

        for(vector<string>::iterator itr2 = itr->begin();
            itr2 != itr->end(); itr2++)
        {
            string str;
            str=*itr2;
            if(str==aname)
            {
                itr + 3;
                file1.open("C:\\Users\\Nandhu\\Desktop\\glosys\\joinpolicy.txt",
                    ios::out|ios::app);
                vector<string>.insert(itr->end(), "approved");
                file1 << "approved";
                cout << "approved";
                file1.close();
            }
        }
    }
}
break;

A: You cannot directly insert data in the middle of a file. You can only re-write the entire file or append to it at the end.
To insert data in the middle you have a few options:
1) Read the file into a memory buffer, transform it as needed and then truncate the file to zero length and rewrite it from the buffer.
2) As 1, but instead of truncating the original file, write a new (temporary) file and then rename it over the original.
3) Identify the point where you need to make changes, read everything after that point to a memory buffer and make your changes, then truncate the file to the size previously identified and then write the memory buffer to the file in append mode.
4) Memory map the file, make the changes needed and flush them to the file.


text:
Q: c# Linq with complex result I have the following class:
class Voucher
{
    string AccountId { get; set; }
    Date Date { get; set; } // This class only implements the date part
    decimal Amount { get; set; }
}

with the following data (simplified/sorted for clarification):
1 12/02/2014 100
1 12/02/2014 100
1 23/11/2014 100
1 23/11/2014 100
2 10/01/2014 100
2 10/01/2014 100
2 09/08/2014 100

I want the result to be grouped by Account and Date but the amount should be the total of all the entries which are less than the Date key:
1 12/02/2014 200
1 23/11/2014 400
2 10/01/2014 200
2 09/08/2014 300

I cannot think of a solution where I can do this. Grouping with date as the key will give me the total of amounts on that particular date, which I don't require. Can this be done?
Also, I need this to be done in one query as I will use this query for RavenDB reduce.

A: Edit: Updated with multiple group key.
I could do it like this.
Output:
var result = from i in input
             group i by new { i.Date.Date, i.AccountId }
             into grouped
             select new {
                 accountId = grouped.Key.AccountId,
                 date = grouped.Key.Date,
                 total = (from kv in input
                          where kv.Date.Date <= grouped.Key.Date && kv.AccountId == grouped.Key.AccountId
                          select kv).Sum(i => i.Amount)
             };

Result:

Input:
var input = new[] {
    new Vocuher() {
        AccountId = "1",
        Date = DateTime.Parse("12/02/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "1",
        Date = DateTime.Parse("12/02/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "1",
        Date = DateTime.Parse("23/11/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "1",
        Date = DateTime.Parse("23/11/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "2",
        Date = DateTime.Parse("10/01/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "2",
        Date = DateTime.Parse("10/01/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "2",
        Date = DateTime.Parse("09/08/2014"),
        Amount = 100
    }
};


text:
Q: Why does HTTPURLConnection.getInputStream() takes time I have a task to download & upload a file using HTTP protocol in Android (Java platform).
I am using following code for uploading a file:
HttpURLConnection httpURLConnection = (HttpURLConnection) serverUrl.openConnection();
....
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();

And Using following code for downloading a file:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
...
urlConnection.connect();
DataInputStream stream = new DataInputStream(urlConnection.getInputStream());

As per my observation connect() for both the case takes time because it is communicating with network at this point. And for file upload, getOutputStream() gets execute very fast so does it means it is not communicating to network?
Whereas getInputStream() (in file download) takes some time (around 200 to 2500 mili sec) to execute. Does it mean it is communicating with network at this point? If yes then why so?
Experts, Please provide your comments on this & correct me if I am wrong anywhere.

A: HTTP is a request/response protocol. You need a TCP connection. The connect() method creates that. Then you need to send a request. You call getOutputStream() for that, and you write it.
At this point nothing has been written to the network (in normal transfer mode), because the content-length header has to be set, and Java doesn't know when you've finished writing. So when you call getInputStream() (or getResponseCode()), Java sets the content-length header, writes the request, waits for the server to start generating a response, reads all the response headers, and then gives you an input stream positioned at the beginning of the body of the response. All those steps take time.

A: You must limit buffering by specifying the streaming mode either by giving the final length of the uploaded information via setFixedLengthStreamingMode method, or setting mode to streaming if final length is not known via setChunkedStreamingMode method:
    // For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance,
    // or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory
    // before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.
    //
    // see: https://developer.android.com/reference/java/net/HttpURLConnection.html

    _connection.setChunkedStreamingMode(1024);

If you don't, the real transfer will occur when you call getInputStream().
See https://developer.android.com/reference/java/net/HttpURLConnection.html


text:
Q: Stop pip installing dependancies already installed using apt-get How do I make sure packages installed using pip don't install dependancies already installed using apt-get?
For example, on Ubuntu you can install the package Numpy using apt-get install python-numpy. Which gets installed to:
usr/local/lib/python2.7/dist-packages

I've noticed that when I install a package that requires numpy using pip for example, pip install scipy instead of skipping the numpy dependancy it installs again to a different location.
/usr/lib/python2.7/dist-packages

What pip should do is skip any python packages installed globally, right?

A: In key here is to prevent multiple package managers to install into the same directories.
One strategy is to create a virtualenv that is aware of the package of its parent interpreter. This can be done by using the --system-site-packages option.
virtualenv -p /usr/bin/python --system-site-packages py27
source py27/bin/activate

This environment will not be empty by default. You may want to compare /usr/bin/python -m pip list and python -m pip list.
See also this question

For many (scientific) packages there are also wheels available on pypi. Wheels are already binary and thus need no further compilation.


text:
Q: Optimizing AS3 DropShadowFilter I'm using GreenSock's TweenMax to fade in a TLFTextField with a DropShadowFilter applied. The framerate drops to about 8fps when I try to do this. Without the shadow, the transition is a consistent 24fps. I know Flash is redrawing the shadow each frame - is there any way I can avoid this?
cacheAsBitmap seems to have no noticeable effect. I could draw the textfield to a bitmap, but I'd like that to be a last resort. Is there any override for redrawing the shadow? Or perhaps an alternative method?
Any help would be appreciated.
Thanks in advance.

A: Embed the TextField to fade in into a parent Sprite, cache that sprite as bitmap, and fade the parent in by tweening its alpha. This should make Flash draw the drop shadow only once per entire processing.
var fadeholder:Sprite=new Sprite();
fadeholder.addChild(tf); // your textfield
tf.alpha=1;
// it should have filter applied already
fadeholder.cacheAsBitmap=true;
addChild(fadeholder);

After you do this, initiate tween on fadeholder.alpha, and once it's over, add the textfield to a proper parent ("this", maybe) and remove the obsolete fadeholder from display list.


text:
Q: Using Option[Boolean] from Java I've got a Scala Trait with a method that returns Option[Boolean]. I'd like to write a Java class that implements this trait. Unfortunately the compiler complains about the following code:
trait WithBoolean {
  def doSth(): Option[Boolean]
}

public class MyClass implements WithBoolean {
  @Override
  public Option<Boolean> doSth() {
    return null;
  }
}

The compile error is:
doSth() in MyClass cannot implement doSth() in WithBoolean
public Option<Boolean> doSth() {
                       ^
return type Option<Boolean> is not compatible with Option<Object>

It does compile if i change the code slightly:
public class MyClass implements WithBoolean {
  @Override
  public Option<Object> doSth() {  //return type has been changed to Object
    return null;
  }
}

But this is obviously not a nice solution. What do I need to change in order to be able to use the correct return type?

A: I can't test this right now, but my best guess is that you have some imports mixed up, and thus try to override Option<scala.Boolean> with Option<java.lang.Boolean>.

A: Could you try
public class MyClass implements WithBoolean {
  @Override
  public Option<? super Boolean> doSth() {
    return null;
  }
}

A: You can try this :
(value != null)?new Some<T>(value):scala.Option.apply((T) null);

(value != null)?new Some<Boolean>(value):scala.Option.apply((Boolean) null);

A: From the class description:

Boolean (equivalent to Java's boolean primitive type) is a subtype of [[scala.AnyVal]]. Instances of Boolean are not represented by an object in the underlying runtime system.

Java Boolean extends AnyRef (more about this here).
AnyRef and AnyVal both extends Any which is equivalent to java.lang.Object.
This is why only Option<Object> works.
If you want type safety you could do this:
trait WithBoolean {
  def doSth(): Option[Boolean]
}

abstract class WithBooleanForJava extends WithBoolean {

  override def doSth(): Option[Boolean] = doSthJava().map(Boolean.box(_))

  def doSthJava(): Option[java.lang.Boolean]
}

So you java class will look like you wanted:
public class MyClass extends WithBooleanForJava {

    @Override
    public Option<Boolean> doSthJava() {
        return null;
    }
}


text:
Q: HOw to use local instance of TPrinter I need to do some printing using TPrinter. The problem is I can not, for various reasons, use Global object Printer.
I want to be able to create my instance of TPrinter and print using that one.
I tried with:
MyPrinter := TPrinter.Create;
MyPrinter.BeginDoc;

but this generates AV.
Any idea what does it take to print something using my instance of TPrinter?
Regards
Goran Nagy

A: If you look at the soucre for printers, the AbortProc uses the global FPrinter object.
You can solve this by call Printer function before caling TPrinter.Create, then it dosn't generate a AccessViolation.
It will posibly solve your problem, but MyPrinter.Abort wil NOT propoply not work correcty.
Telling why you can't use the global object, gives other users a posibility to suggest alternative solutions.

A: The TPrinter object is not really designed to be created locally, but instead is designed to be used from the 'singleton' function Printer in the Printers unit. Generally you would use that.
From the help:

Use TPrinter to manage any printing performed by an application. Obtain an instance of TPrinter by calling the Printer function in the Printers unit.

Edit: Actually, having had a think you could do something like this:
procedure PrintThings;
var
  LMyPrinter: TPrinter;
  LOldPrinter: TPrinter;
begin
  LMyPrinter := TPrinter.Create;
  try
    LOldPrinter := SetPrinter(LMyPrinter);
    try

      // your printing code goes here

    finally
      SetPrinter(LOldPrinter);
    end;
  finally
    LMyPrinter.Free;
  end;
end;


text:
Q: rndc querylog - Can you specify log file other than messages? When logging BIND requests using rndc querylog, the logging defaults to /var/log/messages. Is it possible to change this logging destination and specify my own log file?

A: In the man pages for named.conf, there is a section on logging.
Just make sure that if you are using a chroot for your DNS service, that your log destination is interpreted properly.
Specifically, the syntax chart is as follows:

      logging {
            channel string {
                 file log_file;
                 syslog optional_facility;
                 null;
                 stderr;
                 severity log_severity;
                 print-time boolean;
                 print-severity boolean;
                 print-category boolean;
            };
            category string { string; ... };
      };

A: Yes! You can define a query log channel and direct that output to a specific log file destination of your choosing if you do not want this in the syslog messages file.
 channel queries_log {
      file "/var/named/log/queries" versions 600 size 20m;
      print-time yes;
      print-category yes;
      print-severity yes;
      severity info;
 category queries { queries_log; };

Remember that you can enable and disable query logging using rndc as needed for debugging issues. This will help save you some CPU cycles and disk I/O when operations are normal. Adjust the sample I posted so that you do not end up with 600 20MB files with logged queries sitting on your file system.
Just as a matter of practice, try to have a dedicated partition and file system for your logs so that filling it up will not negatively impact other system operation.
i.e. putting /var/log on it's own partition/slice. Worst case if that fills up you may loose some log data however system functions can continue.


text:
Q: Tensorflow optimiser.compute_gradients runs way slower on the first step I have a complex rnn model written in tensorflow for multigpu training. When I run my tf code, the graph building happens in reasonable time.
But, when I call sess.run to run the graph, the optimiser.compute_gradients takes a lot of time to run for the first step, but gets much faster(around 10X faster) for the subsequent steps. Every batch in my dataset are of the same shape.
Why is this happening?
Thanks


text:
Q: Why is my css grid not enclosing its child elements? I am trying to create two 4 by 6 grids nested inside of a 1 by 2 grid. The outermost grid is not containing the children grids. So they are semi collapsing in over each other.
This should be fairly easy.
I've gone through this site:

*

*https://css-tricks.com/snippets/css/complete-guide-grid/
I've gone through youtube tutorials.
I've also tried these tools:

*

*https://grid.layoutit.com/

*https://cssgrid-generator.netlify.com/
I've tried setting columns and rows with fr, %, and px.
I've tried using line numbers, and area. etc.

#outside {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: repeat(2, 1fr);
  grid-auto-rows: 10%;
  //grid-row-gap: 300px;
  justify-content: center;
  align-content: center;
  background-color: red;
}

.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(6, 20%);
  grid-auto-rows: 300px;
  grid-gap: 8px;
  justify-content: center;
  align-items: center;
  background-color: green;
}

.item {
  padding: 20px;
  background-color: blue;
}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

A: There is no height defined on your grid containers. This creates two problems:

*

*On the primary container, without a defined height, the height is determined by its content. Therefore, there is no extra space available and 1fr doesn't do anything. So you may as well switch to auto in your grid-template-rows: repeat(2, 1fr) rule.

*On the nested containers, without a defined height, 20% on the rows will render unreliably / quirky across browsers because the browser doesn't know: 20% of what? Therefore, either define a height on the container (knowing that 6 * 20% will overflow) or switch to auto in your grid-template-rows: repeat(6, 20%) rule.
These posts may also help you understand the forces at work here:

*

*Working with the CSS height property and percentage values

*Why heights need to be defined, but not widths

*The difference between percentage and fr units in CSS Grid Layout

#outside {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: repeat(2, auto); /* adjustment */
  /* grid-auto-rows: 10%; */
  justify-content: center;
  align-content: center;
  background-color: red;
}

.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(6, auto); /* adjustment */
  grid-auto-rows: 300px;
  grid-gap: 8px; /* creates space between grid items only; "gutters" */
  padding: 8px;  /* creates space between container and items */
  justify-content: center;
  align-items: center;
  background-color: green;
}

.item {
  padding: 20px;
  background-color: blue;
}

body {
  margin: 0;
}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

jsFiddle demo


text:
Q: Can you send json from VisualForce to Apex and have it be valid? I have this JSON object that I've gotten from the front end. I want to send it to Apex and finally send it to my external API.
Visualforce:
 ct_4_sf.RecordingTest.saveVideo(
     data, //{key:'value',key2:'value2'}
     function(response){

     }
 );

If I attempt to just send it from visualforce to this apex function:
Apex:
@RemoteAction
global static String saveVideo(String data) {
    System.debug(LoggingLevel.INFO,'saving ' + data);
    return Connector.saveVideo(JSON.serialize(data));
}

The saving log will print something like this:
{key=value, key2=value2}

All the colons are now replaced with equal signs, which is invalid JSON.
How can I either turn this back into valid json, or send valid json in a way that it doesn't corrupt on the other side?

A: Convert the JSON into string before sending to controller using JSON.stringify(). Please check below link,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Also if there is no other operation that needs to be done in controller before sending to external system. Try to do it in page only using javascript/jQuery AJAX
http://api.jquery.com/jquery.ajax/

A: One way i can think of is to have a class for your JSON .
public class wrapperclass{
  public String key;    //value
   public String key2;  //value2
 }

Your remoting function will be tweeked like below
@RemoteAction
global static wrapperclass saveVideo(wrapperclass wrap) {
   return wrap;
}

Another alternate approach can be as below if your keys are dynamic in nature
global class RecordingTest{
  @RemoteAction
  global static map<string,Object> saveVideo(map<string,Object> inputmap) {
     return inputmap;
  }
}

The page code that I tested with is as below
<apex:page controller="RecordingTest">

<script type="text/javascript">
     function RemoteTest() {
     var testdata={key:'value',key2:'value2'};
    Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.RecordingTest.saveVideo}',
        testdata,
        function(result, event){
            if (event.status) {

              console.log(result);//print the log and inspect console to see result returned in form of JS object.You can generate string from JSON object using stringify

   console.log(JSON.stringify(result));

            } else if (event.type === 'exception') {

            } else {

            }
        },
        {escape: true}
    );
}
</script>

<button onclick="RemoteTest()">Test</button>


text:
Q: Salesforce AppCloud - Where is WAVE? During dreamforce Salesforce has announced "app cloud". Part of app cloud are the following technologies:

*

*FORCE

*HEROKU ENTERPRISE

*LIGHTNING

*THUNDER

One technology plattform is missing: WAVE.
Question:
Is Wave part of AppCloud? (and why?)

A: Wave is a product , and heroky, force, lightning and thunder are technologies to develop your product

A: App cloud includes following features:

*

*Force.com platfrom & Lightning

*Heroku Enterprise

It is introduced to customers for creating applications by point and click only. App cloud users can download applications from appexchange and use on their Salesforce instance.
Lightning Components are most useful for App cloud users, which can be downloaded from appexchange and create application using different type of components.
APIs access will also be provided so user can interact with the platform.
With more better App cloud license. Heroku Enterprise level access will be provided so a custom app (build on other technology but on heroku platfrom) can be used with Salesforce. It provides a database and processing unit on Heroku Environment.
Wave is a separate product. It is not a part of any other Salesforce product or technology. It is more about data processing, visualization and distributing apps built over it. It is itself divided in two parts, view and build. Appcloud doesn't come in this category.


text:
Q: How can I build professional module in DotNetNuke 5.6.2? How can I build custom module that can later be useful in other DNN websites.

*

*"standard" : module can be installed once only in one DNN portal

*"professional" : module can be installed in multiple portals

*"Enterprise" : module can be installed multiple times in multiple portals

*"Trial release" : module can be installed only in 1 portal with limited access.

Is this possible to fulfill this requirement in module development?

A: As of this point in time there is no API for you to do this automatically, but you are more than able to add your own licensing process to make this happen.

A: There are two concepts here that should be clarified.
Installation - taking a module and making it available to be used on a DNN site.  Typically this is done via a .zip package and the module installation wizard, but there are other ways to make a module available to site.  A module can be installed at the Admin (portal) level which means it can only be used in that specific portal, or it can be installed at the Host level which means it can be used on any portal.
Module Instance - once a module is installed it can be added one or more times to one or more pages.  Each time a modules is added, an additional module instance is created.  It is possible to share a single instance in multiple locations.
A "normal" module is unrestricted.  It may be installed at the Admin or Host level and an infinite number of instances may be created throughout the portal(s).  There is nothing in the framework to restrict the installation or instances of a module.  Each module developer is left to provider their own commercial licensing mechanism.

A: This sounds more a licensing issue rather than one of functionality. You can consider each of these as different editions of your module. If you integrate the module with a DNN licensing solution such as Licence Master, you can control which features of the application are "switched on" in each of the different editions.


text:
Q: xml to json string without double qoutes in number and decimal type in c# I have an XElement I am trying to convert into a JSON string.
Below is my XElement:
<myxml>
  <gstin>28GSDUH1331G155</gstin>
  <fp>122016</fp>
  <gt>3782969.01</gt>
  <b2b>
    <ctin>29GSDUH1331G155</ctin>
    <inv p2:Array="true">
      <inum>S008502</inum>
      <idt>15-11-2016</idt>
      <val>10000.00</val>
      <pos>27</pos>
      <rchrg>N</rchrg>
      <prs>Y</prs>
      <od_num>8401</od_num>
      <od_dt>14-11-2016</od_dt>
      <etin>30GSDUH1331G155</etin>
      <itms p2:Array="true">
        <num>1</num>
        <itm_det>
          <ty>G</ty>
          <hsn_sc>G1221</hsn_sc>
          <txval>10000.00</txval>
          <crt>1.00</crt>
          <camt>100.00</camt>
          <srt>1.00</srt>
          <samt>100.00</samt>
          <csrt>100.00</csrt>
          <csamt>100.00</csamt>
        </itm_det>
      </itms>
    </inv>
  </b2b>
</myxml>

I am using this  string jsonString = JsonConvert.SerializeXNode(myxml);
to convert in json string
and i am getting the jsonstring
"{\"myxml\":{\"gstin\":\"28GSDUH1331G155\",\"fp\":\"122016\",\"gt\":\"3782969.01\",\"b2b\":[{\"ctin\":\"29GSDUH1331G155\",\"inv\":[{\"inum\":\"S008502\",\"idt\":\"15-11-2016\",\"val\":\"10000.00\",\"pos\":\"27\",\"rchrg\":\"N\",\"prs\":\"Y\",\"od_num\":\"8401\",\"od_dt\":\"14-11-2016\",\"etin\":\"30GSDUH1331G155\",\"itms\":[{\"num\":\"1\",\"itm_det\":{\"ty\":\"G\",\"hsn_sc\":\"G1221\",\"txval\":\"10000.00\",\"crt\":\"1.00\",\"camt\":\"100.00\",\"srt\":\"1.00\",\"samt\":\"100.00\",\"csrt\":\"100.00\",\"csamt\":\"100.00\"}}]}]}]}}"

The problem that i am running into is that integer and decimal values are being surrounded by backslashes and double quotes(\" \") . I don't want backslash double quotes on numbers and decimals.
This is the JSON string which i want as an output.
"{\"myxml\":{\"gstin\":\"28GSDUH1331G155\",\"fp\":122016,\"gt\":3782969.01,\"b2b\":[{\"ctin\":\"29GSDUH1331G155\",\"inv\":[{\"inum\":\"S008502\",\"idt\":\"15-11-2016\",\"val\":10000.00,\"pos\":27,\"rchrg\":\"N\",\"prs\":\"Y\",\"od_num\":8401,\"od_dt\":\"14-11-2016\",\"etin\":\"30GSDUH1331G155\",\"itms\":[{\"num\":1,\"itm_det\":{\"ty\":\"G\",\"hsn_sc\":\"G1221\",\"txval\":10000.00,\"crt\":1.00,\"camt\":100.00,\"srt\":1.00,\"samt\":100.00,\"csrt\":100.00,\"csamt\":100.00}}]}]}]}}"

A: As the comments have already pointed out - more information would likely help (as your XML is currently invalid).
Also in the future it is always best to show Minimal, Complete, and Verifiable examples to the questions you are asking - not only to show that you have tried, but to give people who are helping more information.
When simply inspecting the element in the debugger as you did it does in-fact show backslashes
"{\"myxml\":{\"gstin\":\"28GSDUH1331G155\",\"fp\":\"122016\",\"gt\":\"3782969.01\",\"b2b\":{\"ctin\":\"29GSDUH1331G155\",\"inv\":{\"@Array\":\"true\",\"inum\":\"S008502\",\"idt\":\"15-11-2016\",\"val\":\"10000.00\",\"pos\":\"27\",\"rchrg\":\"N\",\"prs\":\"Y\",\"od_num\":\"8401\",\"od_dt\":\"14-11-2016\",\"etin\":\"30GSDUH1331G155\",\"itms\":{\"@Array\":\"true\",\"num\":\"1\",\"itm_det\":{\"ty\":\"G\",\"hsn_sc\":\"G1221\",\"txval\":\"10000.00\",\"crt\":\"1.00\",\"camt\":\"100.00\",\"srt\":\"1.00\",\"samt\":\"100.00\",\"csrt\":\"100.00\",\"csamt\":\"100.00\"}}}}}}"

These backslashes are just inserted as escape characters and are NOT actually there.
If you inspect the actual values of jsonString you will find your expected value.  When you are viewing the jsonString in the debugger you are looking at a raw JSON string, but in the below screenshot you are looking at a representation of a JSON object.


text:
Q: React Native: verificar qual checkbox esta selecionado dentro de uma lista de checkboxes Olá, estou com o seguinte problema tenho uma lista de checkbox, e gostaria de verificar qual checkbox esta selecionado depois de clicado no botão.
import React, {
    Component
} from 'react';

import {
    Platform,
    StyleSheet,
    Text,
    View,
    ScrollView,
    CheckBox
} from 'react-native';
import Checkbox from 'react-native-custom-checkbox';

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            checked: false,
            check: []
        };
    }

    _myFunction(value, name, checked) {
        console.log("Log:  " + value, checked);
    };

    clickButton() {

    }

    render() {

        let checkboxes = [];

        for (let i = 0; i < 5; i++) {
            checkboxes.push( <
                View >
                <
                Checkbox

                name = 'checkbox2'
                checked = {
                    false
                }
                size = {
                    30
                }
                style = {
                    {
                        backgroundColor: '#f2f2f2',
                        color: 'blue',
                        borderRadius: 5
                    }
                }
                onChange = {
                    (name, checked) => this._myFunction(name, i, checked)
                }
                /> <
                /View>
            );
        }

        return ( <
            View >
            <
            Button onPress = {
                () => this.clickButton()
            } > < /Button> {
                checkboxes
            }

            <
            /View>
        );

    }

}

Alguém poderia me ajudar

A: Fiz a solução em react para web, mas pode ser adaptada ao React Native.
https://codesandbox.io/s/649kry59y3
Espero que seja útil.
Abraços!


text:
Q: AllenNLP Reading Comprehension results are different in UI Demo and Python Library I am trying AllenNLP reading comprehension with the Transformer QA Model to get the answer to question "Who is CEO of ABB?" from the passage "ABB opened its first dedicated global healthcare research center for robotics in October 2019.".
As expected, the UI demo shows no answer returned. The API response in network tab also shows that. In the json response, best_span_str is empty, but best_span_scores is 9.9. Screenshot of demo UI and API response in network tab.
When I execute the similar code via python library, I get a different result.
from allennlp.predictors.predictor import Predictor
import pandas

def allen_nlp_demo_1():
  import allennlp_models.structured_prediction
  import allennlp_models.rc
  predictor = Predictor.from_path("https://storage.googleapis.com/allennlp-public-models/transformer-qa-2020-05-26.tar.gz")
  data = predictor.predict(
    passage="ABB opened its first dedicated global healthcare research center for robotics in October 2019.",
    question= "Who is CEO of ABB?"
  )
  print(data)

if __name__ == '__main__':
  allen_nlp_demo_1()

provides following json output
{
  "span_start_logits": [...],
  "best_span": [
    7,
    15
  ],
  "best_span_scores": -10.418445587158203,
  "loss": 0,
  "best_span_str": "healthcare research center for robotics in October 2019",
  "context_tokens": [...],
  "id": "1",
  "answers": []
}

Here I see best_span_str coming up, and best_span_scores as -10.418445587158203.  Attaching python code and output snippet.
Why is this difference in output in the UI demo vs library? Also, what is the range of best_span_scores and where can I decide a threshold to discard false results?

A: *

*Regarding the discrepancy in the demo's output and your run, it is because the actual demo uses a different archive file. The usage code on the demo has been updated now to reflect the new file path (transformer-qa-2020-10-03.tar.gz).

*For finding the best_span, the model considers a prediction of cls token to mean that the question is not answerable. This is indicated by best_spans, which is [-1, -1] when the question is not answerable. For the case when the question is actually answerable, the span scores are relative to each other; we pick the span with the highest score. So, there isn't a fixed threshold that can be used in all cases.


text:
Q: How to insert 3rd party script widget into Angular 2+ ASP.NET Core project I want to insert a widget from Tradingview into my Angular 2+ ASP.NET Core website.
<!-- TradingView Widget BEGIN -->
<script type="text/javascript" src="https://s3.tradingview.com/tv.js">
</script>
<script type="text/javascript">
new TradingView.widget({
  "width": 980,
  "height": 610,
  "symbol": "NASDAQ:AAPL",
  "interval": "D",
  "timezone": "Etc/UTC",
  "theme": "Light",
  "style": "1",
  "locale": "en",
  "toolbar_bg": "#f1f3f6",
  "enable_publishing": false,
  "allow_symbol_change": true,
  "hideideas": true
});
</script>
<!-- TradingView Widget END -->

So, I tried two ways. Option 1 using the DomSanitizer. I initialize the above script into as a string variable in my component. Then in my template I assign:
In component:
myScriptInComponent = the script above;

In my template

<div [innerHtml]="script">
</div>

After which OnInit I call:
this.script= this.sanitizer.bypassSecurityTrustScript(this.mySriptInComponent);
In this case I get an error.
Required a safe HTML, got a Script
Then I tried inserting the js file from https://s3.tradingview.com/tv.js into my application with webpack by using webpack --config webpack.config.vendor.js.
After that I simply imported this js file into my component and called the new TradingView.widget ...etc. onInit but here I'm getting an error which says cannot read property 'widget' of undefined.
Kind of stuck with what to try next. Would really appreciate any hints. Thank you.

A: So after I have read and tried hopelessly about everything there is on DOM manipulation the only thing that worked was actually postscribe which I ignored at first.
First install using npm install --save postscribe, then add to webpack.config.vendor.js and run webpack --configure webpack.config.vendor.js after which in your template create a div with an id. In your component do the following:
import * as postscribe from 'postscribe';

ngAfterViewInit() {
     postscribe('#yourDivId', '<script>yourscriptstring</script>');
{

Good luck!


text:
Q: index.js:1 Warning: Failed prop type: Invalid prop `value` of type `object` supplied to `DataTable`, expected `array`. in DataTable index.js:1 Warning: Failed prop type: Invalid prop value of type object supplied to DataTable, expected array.
    in DataTable
render() {
    return (

    <DataTable value={this.state.ilac} selectionMode="single" selection={this.state.selectedIlac} onSelectionChange={e => this.setState({ selectedIlac: e.value })} >
      <Column field="id" header="ID"></Column>
      <Column field="ilacAdi" header="İLAÇ ADI"></Column>
    </DataTable>
  </Panel>
);

}

A: This is a warning from validating your DataTable component's prop value (this.state.ilac).
The Datatable expects an array but this.state.ilac is actually an object.
try Object.values(this.state.ilac).

A: maalesef olmadı.Teşekkürler cevap için


text:
Q: Software Project Management Software I have recently been tasked with writing a fairly large (for 1 person) program and would like to know what is the best software to use to be able to manage this project. Something that I can list what needs to be done and check it off when it is done, something to keep me on track.

A: I'm a FogBugz user here.  Does exactly what you're asking and if there's just going to be one user then you can use it for free.
Another option for the basic task scheduling/prioritization duties is SmartSheet - never clicked with me personally but a lot of people seem to like it.  It's worth checking out as an alternative.

A: you can check out this one too, simple and easy to use http://checkvist.com/

A: If you find free and open source project management software, you can use Trac or Collabtive. We use both of them for project management activity.
Otherwise, if you have money and require professional service, why not try FogBugz or BaseCamp for free trial?

A: I would suggest Mylyn if you are into Eclipse. Trac is a great ticket/task tracking system.

A: We have used XPlanner it's neat and easy to use.

A: We use http://easyprojects.net/ and it works quite well.

A: If you are using visual studio there are some task list features built in I'm sure some other IDE's also have similar features.  In the company I work for MS project is the defacto standard.  I don't really see the value in it for a one person project.  I use Todolist for personal Time management.

A: You might want to consider fossil.
It's a source code management system with built in ticket system and wiki.
It's trivial to get it working (just one binary file).
It's crossplatform.
It stores the whole repository into an SQLite database.

A: *

*Open Atrium

*BugZilla


text:
Q: Laravel: Not able to access belongsToMany relation in nested whereHas I am using whereHas in nested where clause but i am not able to do so. Following is my model:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function scopePickedUser($query, $pickedTypeID)
    {
        return $query->where(function($query) use ($pickedTypeID)
        {
            $query->whereHas('photos', function($query) use ($pickedTypeID)
            {
                 $query->whereTypeId($pickedTypeID);
            });

            if($condition){
                $query->orWhere('another_column_id',$var);
            }
        });
    }

    public function photos()
    {
        return $this->belongsToMany(Photo::class);
    }
}

If i call, App\Models\User::pickedUser(4)->get() i am getting error BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::photos()'. Why is that? What am i doing wrong?

A: Just refer laravel with for Eager Loading and Lazy Eager Loading . I guess you can try these two types
App\Models\User::with('photos')->pickedUser(4)->get()

Or
public function scopePickedUser($query, $pickedTypeID)
    {
        $query->load('photos');
        return $query->where(function($query) use ($pickedTypeID)
        {
            $query->whereHas('photos', function($query) use ($pickedTypeID)
            {
                 $query->whereTypeId($pickedTypeID);
            });

            if($condition){
                $query->orWhere('another_column_id',$var);
            }
        });
    }


text:
Q: Read text using XML I have an issue with this code.I am tring to read the text file from a .txt doc using XML Http Object request.The code runs but nothing happen,the content of the div changes(the button disappear) but not with my file from the .txt doc
<!DOCTYPE html>

Using the XMLHttpRequest Object

<button type="button" onclick="loadXMLDoc()">Change Content</button>


text:
Q: Testing Distributed Object Connections in OSX with Objective C On Mac OSX with Objective C and Distributed Objects (IPC API), how can a server determine if the client has closed down their application and thus the NSConnection pointer has been broken? I mean, I might be in a while loop, reading a lot of data to send back from the server to the client, and I can test for stuff if I just knew what the trick was to determine if the client has suddenly disconnected.

A: Add this to your server's vended object class and then check it when doing something in any kind of loop for long periods of time. Replace "servicetest" phrase in the code below with the name of your actual process. You can run your client app and then check ps -ef at command line to see what your process is, if uncertain. It'll be the one with DerivedData if running temporarily in XCode.
A little warning, though. This routine is kind of heavy and you shouldn't call it with every loop iteration. Instead, check like every 500 iterations of your while loop you might be in, for instance. You could also have a background timer that runs and checks. Or you could use rand to determine 1 in 5 odds and run it then.
Note that this routine only runs properly with Distributed Objects on the same system, as in application to application IPC, rather than Distributed Objects over a LAN.
So, when I detected that a client suddenly disconnected, I do a break on my while loop (where I was reading slow process data) and then did a pclose() on that process because there was no sense running it anymore.
/* requires these includes
#include <libproc.h>
#include <sys/sysctl.h>
#include <string>
*/

- (bool)_clientSuddenlyDisconnected;
{

  int numberOfProcesses = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
    pid_t pids[1024];
    bzero(pids, 1024);
    proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
    for (int i = 0; i < numberOfProcesses; ++i) {
            if (pids[i] == 0) { continue; }
            char pathBuffer[PROC_PIDPATHINFO_MAXSIZE];
            bzero(pathBuffer, PROC_PIDPATHINFO_MAXSIZE);
            proc_pidpath(pids[i], pathBuffer, sizeof(pathBuffer));
            if (strlen(pathBuffer) > 0) {
                    std::string sTest(pathBuffer);
                    sTest = "/" + sTest + "$$$";
                    if (sTest.find("/servicetest$$$") != std::string::npos) {
                        return false;
                    }
            }
    }
    return true;
}


text:
Q: Password protected xls data transfer to master sheet I am quite new to python and currently writing a code to speed up a VBA process which takes 5 to 6 hours to complete and want to speed it up. The code needs to open a password protected excel, extract certain sheet and cell data to a master sheet and if column A is that same number then override so no duplicates:
Process:
Step 1: Open password protected xls
step 2: check for the duplicated number in column A and if the same value exists then override, copy required cells from each sheet to master wb and data sheet as shown below
step 3: go back to step one until all xls are done.
This is part of the VBA to show the process to a degree:
wbThis.Worksheets("Data").Range("A" & Store_Row_no) = NewNumber
wbThis.Worksheets("Data").Range("B" & Store_Row_no) = DateNew
wbThis.Worksheets("Data").Range("C" & Store_Row_no) = wbNew.Worksheets("Sheet1").Range("F2").Value
wbThis.Worksheets("Data").Range("D" & Store_Row_no) = wbNew.Worksheets("Sheet2").Range("H152").Value
wbThis.Worksheets("Data").Range("E" & Store_Row_no) = wbNew.Worksheets("Sheet3").Range("D3").Value

and this is my current code but cant work out how I open a password protected excel and copy to master sheet and then overide for data column A if it is a duplicate.
Python code so far:
import win32com.client
import sys
import os

foldername = ('C:\\Users\\')
password = 'ORANGE
pmaster = (r'C:\Users')
xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = False

master = xlApp.Workbooks.Open(Filename=pmaster)

wb = xlApp.Workbooks.Open(foldername, False, True, None, password)
sh1 = wb.Sheets('sheet1') #sheet name1
sh2 = wb.Sheets('sheet2') #sheet name2
sh3 = wb.Sheets('sheet3') #sheet name2

out1 = sh1.Range("B2").value
out2 = sh1.Range("D2").value
out3 = sh1.Range("F2").value
out4 = sh2.Range("H152").value
out5 = sh3.Range("D3").value
print(out1,out2,out3,out4,out5)

Just need to loop through help and copy to new master wb
Thank you so much in advance


text:
Q: Unable to prove -100000000000000 eligible as an long input I have written a program to determine whether any input fits the range of various data-types in java, and if it does the print the eligible data-types.
The program first takes an integer input to determine the total constants for which
I want to test the eligibility. It then runs a loop the required number of times determined by the query, to check eligibility for each constant entered.
The problem which I am facing is that-- I am checking the eligibility for a single input, but when I enter "-100000000000000"(-1 followed by 14 zeroes), no output comes and the cursor takes the input and then just blinks indefinitely.
Any other constant input gives desired output, but the problem with the program happens only after I enter "-100000000000000". I have been trying to solve the problem myself for a long time now, and hence any lead would help me.
Here is my code -->
import java.util.*;
import java.io.*;
import static java.lang.Math.pow;
class Solution{
public static void main(String []argh)
{

    Scanner sc = new Scanner(System.in);
    int t=sc.nextInt();

    for(int i=0;i<t;i++)
    {

        try
        {
            long x=sc.nextLong();
            System.out.println(x+" can be fitted in:");
            if(x>=-128 && x<=127){
                System.out.println("* byte");
            }
            if(x>=(int)(pow(-2.00,15.00)) && x<=(int)(pow(2.00,15.00)-1)){
                System.out.println("* short");
            }
            if(x>=(int)(pow(-2.00,31.00)) && x<=(int)(pow(2.00,31.00)-1)){
                System.out.println("* int");
            }
            if(x>=(int)(pow(-2.00,63.00)) && x<=(int)(pow(2.00,63.00)-1)){
                System.out.println("* long");
            }
        }
        catch(Exception e)
        {
            System.out.println(sc.next()+" can't be fitted anywhere.");
        }
    }
}
}

A: I see in your code that you're trying to parse pow(-2.00,63.00) to an Integer, which will not return the value you're expecting.
You can just replace your casting in the Long data-type check like this:
if(x>=(long)(pow(-2.00,63.00)) && x<=(long)(pow(2.00,63.00)-1)){
    System.out.println("* long");
}

Also, just in case you didn't knew, you could simply use "Long.MIN_VALUE | Long.MAX_VALUE" instead of "pow(-2.00,63.00) and pow(2.00,63.00)-1" respectively. Same goes for the others data-types (Byte, Short, Integer).


text:
Q: HTTP 204 error when sending File in response REST This is my write to excel method which returns javax.ws.rs.core.Response
public  Response writeToExcel(UserDeatilsVOWrapper listBook) {
    XSSFWorkbook  workbook = new XSSFWorkbook();
    XSSFSheet spreadsheet = workbook.createSheet("Resource Information");

    int rowCount = 0;
    createHeaderRow(spreadsheet);
    for (UserDetailsVO detailsVO : listBook.getUserDetailsList()) {
        Row row = spreadsheet.createRow(++rowCount);
        writeBook(detailsVO, row);
    }
    Response response = null;

    try (FileOutputStream outputStream = new FileOutputStream(new File("ResourceInformation.xlsx"))) {
        workbook.write(outputStream);

        // header required to enable download pop-up and set file name
        Response.ok().header("Content-Disposition", "attachment; filename=" + "ResourceInformation.xlsx").build();
    }

    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return response;
}

This is my web service:
@POST
    @Path(WebServiceConstants.DOWNLOAD_EXCEL)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response getFile(UserDeatilsVOWrapper wrapper) {
   Response respose=new ExportToExcel().writeToExcel(wrapper);
    return respose;}

I get a HTTP204 error. I'm using postman. I know, I'm doing a big mistake  in write to excel method and when trying to send file along with response.
Also is there any possible way to write a file object on REST response without saving file on server? I'm doing terrible in here. any help is appreciated.

A: I do not see where you set your file to the response. Normally you would do something like this
File file = new File("ResourceInformation.xlsx"))

// Do your excel-writing here...

ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=" + "ResourceInformation.xlsx");
return response.build();


text:
Q: Command Block Question for "if, then" statement On the latest version of Minecraft Bedrock edition is it possible to have a command block (When activated) check for the nearest player's name and kill them if it does not add up to a pre-entered name?
For example, if "Player1" steps on the pressure plate that activates the command block they do not die, however, if "Player2" steps on the pressure plate that activates it, they die.
Edit: Using more than one command block.

A: Simpler solution
There is often a better command that can be used instead of /testfor, if you have a pressure plate that should only kill "Player2", you can simply use this command:
/kill @a[name=Player2,x=~,y=~2,z=~,r=1]

This is assuming that you have the command block 2 blocks under the pressure plate.
More general solution with /execute
Whenever you want to use /testfor, you can likely use /execute instead, simply by putting the target selector from the /testfor command into it.
If you want to kill "Player2" if a zombie is within 5 blocks distance from the command block, then you could use /testfor @e[type=zombie,r=5] in a command block and then /kill Player2 in a conditional chained command block.
This could be done more easily by putting the target selector from the first command into an /execute command:
/execute @e[type=zombie,r=5] ~ ~ ~ kill Player2

Even more general solution
In some extremely rare cases I can't think of any situation where you really need anything beyond /execute right now even this may not be enough, maybe you want to execute several commands as a specific group of mobs that may not be detectable with the same target selector after every command.
If you really need something like this, then you can set up a scoreboard objective:
/scoreboard objectives add objectives dummy

You would use one repeating command block that continuously sets the score of all entities to 0, the scoreboard objectives will be used to determine what entities to execute as:
scoreboard players reset * objectives

For every system that you want to set up you would then set the scoreboard score with the same target selector you would use with /testfor, or /execute. Each score value should be unique to every setup:
scoreboard players set @e[type=zombie] objectives 1

You would then use a chain of command blocks, one for each command that you want to execute. You would likely use /execute again, maybe in a command like this:
execute @e[scores={objectives=1}] ~ ~ ~ kill @a[r=5]

This example would kill all players within 5 blocks of any zombie, it could be done more easily with /execute @e[type=zombie] ~ ~ ~ kill @a[r=5].

A: You can use testfor to test if the player is at the specified position, then use a comparator to trigger another command.
Put testfor @p[name=Name,x=X,y=Y,z=Z,r=maxRadius] in an impulse, unconditional, needs redstone command block that would activate when the pressure plate is activated. Name is the name of the player (in your example Player2). maxRadius is the maximum distance (Euclidean) from X, Y, Z that the player needs. Alternatively, you can use dx, dy, and dz to define cubic volumes. Without these, testfor will always be successful as it would find Name, no matter how far away.
For example: testfor @p[name=Player2,x=10,y=40,z=5,r=2] would activate the second command if Player2 is within 2 blocks of 10, 40, 5.
Then put a comparator (comparison mode) facing away from the command block into another command with the command, such as kill Player2.


text:
Q: IP Address Filtering I'm looking at implementing IP Address filtering for my Rails SaaS app. In a nutshell I want administrators to be able to specify one or more IP Addresses (or a range of IP Addresses) and then my app only accept requests on their instance from the specified addresses.
I'm looking at using IPAddress (http://github.com/bluemonk/ipaddress) for the parsing/validating of each address/range of addresses. Is this a good fit or are there better/more appropriate libraries?
Has anyone implemented this kind of filtering who could describe an approach that has worked for them or are there any gotchas I need to worry about?
Alternatively, is there an existing Ruby library that handles all of this automatically that has managed to elude my Googling?
Many Thanks,
Ash

A: ipaddress is an awesome library (I know the author), but you won't probably need it unless you are planning to perform some advanced manipulation of IP Addresses.
In fact, the most simple way is to

*

*store the array of IP addresses to filter somewhere. You can use the string representation (192.168.1.1) or the long int representation. With the string version, you can even allow wildcards (192.168.1.*)

*then configure a before_filter in the controller that will load the list of banned IPs and perform a simple string match to check whether current request.ip_address (request.remote_ip in rails 3) matches a banned IP. If true, redirect to the error page.
As you can see, you don't even need to convert the IPs into IP objects, unless you need to perform other kind of manipulations.

A: A little late to the party, but since I was looking for something similar and bumped into this nice Ruby gem I'll add it here to contribute to the thread. I like @simone's solution, but if you need a more control then Rack::Attack may be a good choice.

https://github.com/kickstarter/rack-attack
Rack::Attack!!!
A DSL for blocking & throttling abusive clients

A: I think you can achieve what you want using Rails 3 built-in routing features. Gregg Pollack introduces Rails 3 Action Dispatch and mentions (from the screencast) :constraints => {:ip => /192\.168\.1\.\d{1,3}}/} option where you can supply a regular expression matching the IP address range you want to allow.
Extending that a bit more, looking at the Advanced constraints and their example demonstrates pulling a list of blacklisted IPs out from the database and checking if the request.remote_ip is in the list of blacklisted IPs. It looks like you want a list of accepted (aka whitelist IPs) but the code would be nearly identical to the example in Rails guides.
So I would build your admin view to be able to input approved IP addresses, then the application routing can pull this list for incoming requests.


text:
Q: AWS ECS Fargate update docker image only Have deployed a Fargate cluster/service/task using pulumi (Python).
"pulumi up" works well.
Now we want to keep all pieces as are, load balancer etc, and just update the docker image of the running task.
How is this done?
Running "pulumi up" again, creates a new cluster.


text:
Q: Flutter (Web) how to listen to javascript event or pass javascript data to flutter? I am currently writing a flutter web application and am creating a fullscreen button that makes the page fullscreen and edits the page so that a container is maximized upon clicking. This button works by tracking a boolean called "isfullscreen", which edits the ui in flutter and maximizing the browser window by calling a javascript function with dart:js. This button works fine, and allows the user to exit out of fullscreen when clicking as well, and everything is reset to default. However, if the user clicks on the fullscreen button and then manually leaves fullscreen (f11 key, esc key on browser), flutter doesn't pick up the event and the contents of the webpage are mangled (isfullscreen=true but browser is not fullscreen). Is it possible to a) listen to a javascript event within flutter, or b) listen to the javascript event and then somehow pass the data to the flutter web page so that the boolean isfullscreen=false when the user manually exits fullscreen without clicking the button?
Thanks for helping.

A: you can post a message in your js code when the event occures
window.parent.postMessage('any message', "*");

and listen to it in your dart code
@override
void initState() {
  super.initState();

  //setup listener ---------------------------------
  window.addEventListener("message", (event) {
    MessageEvent event2 = event;
    print(event2.data);
  });
  //------------------------------------------------

}


text:
Q: Is there a way to write an xUnit test to check if the data validation annotations in DTOs work? My DTO comes with over 20 properties, hence instead of using data validation in the service layer, I used data annotations to validate the values. But now I want to know if its possible to write an xUnit test for the same.
If there is a way to trigger the data annotations in DTOs, that would help.
I want to avoid writing manual validations for each of the properties. Thanks in advance.


text:
Q: JMeter: comparing ASCII character When I run Jmeter, a test case fails because it compares unwanted ASCII character
following is the result:
Data '£107.29K' is missing;
Data '£131.72K' is missing;
Data '£67.05K' is missing;
Data '£93.84K' is missing;
Data '£107.29K' is new;
Data '£131.72K' is new;
Data '£67.05K' is new;
Data '£93.84K' is new;

When I check the responses, there is no such character in expected response. Not any difference is shown in comparing the responses.
How can I skip this comparison?

A: Try coverting your string to utf-8
byte[] utf8Bytes = original.getBytes("UTF8");
String roundTrip = new String(utf8Bytes, "UTF8");

You can refer this https://docs.oracle.com/javase/tutorial/i18n/text/string.html


text:
Q: QML/C++ Changing the painted scene via a QML button I have a mixxed QML/C++ Application which overall works fine apart from one issue:
In a class Foo inheriting from QDeclarativeItem I want to paint a QtMobility::QGeoMapData and a QGraphicsWidget.
When a qml-button is pressed I switch the object which is painted from a QtMobility::QGeoMapData to a native QGraphicsWidget containing a scene.
When the scene is filled during the construction of Foo this works as expected and the painter takes the native scene.
Alas, I need to create the QGraphisWidget dynamically when the button is pressed and destroy it later. The creation works well and the scene is populated but when the painter is called afterwards it hangs and the programm eats up all the system memory. Any suggestions how this could be solved ?


text:
Q: Compare enums only by variant, not value I have an enum with the following structure:
enum Expression {
    Add(Add),
    Mul(Mul),
    Var(Var),
    Coeff(Coeff)
}

where the 'members' of each variant are structs.
Now I want to compare if two enums have the same variant. So if I have
let a = Expression::Add({something});
let b = Expression::Add({somethingelse});

cmpvariant(a, b) should be true. I can imagine a simple double match code that goes through all the options for both enum instances. However, I am looking for a fancier solution, if it exists. If not, is there overhead for the double match? I imagine that internally I am just comparing two ints (ideally).

A: As of Rust 1.21.0, you can use std::mem::discriminant:
fn variant_eq(a: &Op, b: &Op) -> bool {
    std::mem::discriminant(a) == std::mem::discriminant(b)
}

This is nice because it can be very generic:
fn variant_eq<T>(a: &T, b: &T) -> bool {
    std::mem::discriminant(a) == std::mem::discriminant(b)
}

Before Rust 1.21.0, I'd match on the tuple of both arguments and ignore the contents of the tuple with _ or ..:
struct Add(u8);
struct Sub(u8);

enum Op {
    Add(Add),
    Sub(Sub),
}

fn variant_eq(a: &Op, b: &Op) -> bool {
    match (a, b) {
        (&Op::Add(..), &Op::Add(..)) => true,
        (&Op::Sub(..), &Op::Sub(..)) => true,
        _ => false,
    }
}

fn main() {
    let a = Op::Add(Add(42));

    let b = Op::Add(Add(42));
    let c = Op::Add(Add(21));
    let d = Op::Sub(Sub(42));

    println!("{}", variant_eq(&a, &b));
    println!("{}", variant_eq(&a, &c));
    println!("{}", variant_eq(&a, &d));
}

I took the liberty of renaming the function though, as the components of enums are called variants, and really you are testing to see if they are equal, not comparing them (which is usually used for ordering / sorting).
For performance, let's look at the LLVM IR in generated by Rust 1.60.0 in release mode (and marking variant_eq as #[inline(never)]). The Rust Playground can show you this:
; playground::variant_eq
; Function Attrs: mustprogress nofree noinline norecurse nosync nounwind nonlazybind readonly uwtable willreturn
define internal fastcc noundef zeroext i1 @_ZN10playground10variant_eq17hc64d59c7864eb861E(i8 %a.0.0.val, i8 %b.0.0.val) unnamed_addr #2 {
start:
  %_8.not = icmp eq i8 %a.0.0.val, %b.0.0.val
  ret i1 %_8.not
}

This code directly compares the variant discriminant.
If you wanted to have a macro to generate the function, something like this might be good start.
struct Add(u8);
struct Sub(u8);

macro_rules! foo {
        (enum $name:ident {
            $($vname:ident($inner:ty),)*
        }) => {
            enum $name {
                 $($vname($inner),)*
            }

            impl $name {
                fn variant_eq(&self, b: &Self) -> bool {
                    match (self, b) {
                        $((&$name::$vname(..), &$name::$vname(..)) => true,)*
                        _ => false,
                    }
                }
            }
        }
    }

foo! {
    enum Op {
        Add(Add),
        Sub(Sub),
    }
}

fn main() {
    let a = Op::Add(Add(42));

    let b = Op::Add(Add(42));
    let c = Op::Add(Add(21));
    let d = Op::Sub(Sub(42));

    println!("{}", Op::variant_eq(&a, &b));
    println!("{}", Op::variant_eq(&a, &c));
    println!("{}", Op::variant_eq(&a, &d));
}

The macro does have limitations though - all the variants need to have a single variant. Supporting unit variants, variants with more than one type, struct variants, visibility, etc are all real hard. Perhaps a procedural macro would make it a bit easier.


text:
Q: Issue when parsing JSON with NodeJS I'm reading a JSON file and parsing it with NodeJS, the JSON file looks like this:
{
    "id": 5,
    "x": 9.996,
    "y": 0.135,
    "v": {
        "x1": 0.653,
        "y1": -0.064
    },
    "z": 1.4730991609821347
}, {
    ...
}

So I can easily put that into a variable, JSON.parse() it and access it without any problems:
var parsed = JSON.parse(jsonVar)
console.log(parsed.id) // prints 5

The problem comes when I try to access x1 or y1 from parsed.v. It comes out with an object and it behaves really weird.
I have tried:
 parsed.v.x1 // gave me an error, x1 doesn't exist

also
 var string = JSON.stringify(parsed.v) // returns {"x":0.653,"y":-0.064}

Trying to parse the above and access it also gives me an error
var parsedNew = JSON.parse(string)
console.log(parsedNew.x) //error

Am I missing something there? Running out of ideas really.

A: Actually, there is no need to parse or do anything to access the data, as it already is a javascript object, try something like this:
var json = {
    "id": 5,
    "x": 9.996,
    "y": 0.135,
    "v": {
        "x1": 0.653,
        "y1": -0.064
    },
    "z": 1.4730991609821347
};

console.log(json.v.x1); // this will output '0.653'

And by the way, JSON.stringify() just converts the input into a String, so it is not really what you need.
Hope this helps!


text:
Q: Query is taking to much time to execute? I am trying to get all the Users in a template but the below function and query is taking forever to load! How can i optimized the below function and query? The query almost takes 1 minute to load the users if the users are 6k+ in $search_params parameter.
Let say search parameter is:

  $searchParams = array('start_date' => date('Y-m-d', strtotime('-2 days')) , 'end_date' => date("Y-m-d"));

Query:
public static function getBtqUsers($search_params) {
    $criteria = new Criteria();

    $criteria->clearSelectColumns();
    $criteria->addSelectColumn("btq_user.id as id");
    $criteria->addSelectColumn("btq_user.drid as drid");
    $criteria->addSelectColumn("btq_user.name as name");
    $criteria->addSelectColumn("btq_user.email as email");
    $criteria->addSelectColumn("btq_user.active as active");
    $criteria->addSelectColumn("btq_user.lead_from as lead_from");
    $criteria->addSelectColumn("btq_user.source as source");
    $criteria->addSelectColumn("btq_user.http_referer as http_referer");
    $criteria->addSelectColumn("btq_user.sms_status as sms_status");
    $criteria->addSelectColumn("btq_user.telefon as telefon");
    $criteria->addSelectColumn("btq_user.datain as datain");
    $criteria->addSelectColumn("btq_user.kall as kall");
    $criteria->addSelectColumn("btq_user.ip_address as ip_address");

    $criteria->addSelectColumn("count(btq_user_track_blog_video.counter) as total_video_viewed");

    $criteria->addSelectColumn("btq_doctors.id as dr_id");
    $criteria->addSelectColumn("btq_doctors.drname as dr_name");
    $criteria->addSelectColumn("btq_doctors.drphone as dr_phone");
    $criteria->addSelectColumn("btq_doctors.initials as dr_initials");
    $criteria->addSelectColumn("btq_doctors.drmail as dr_mail");

    $criteria->addSelectColumn("event_data.btq_user_id as event_user_id");
    $criteria->addSelectColumn("count(if(event_data.event_parent_id=2, event_data.event_parent_id, null)) as kms_total_video_viewed");
    $criteria->addSelectColumn("count(if(event_data.event_parent_id=1, event_data.event_parent_id, null)) as kms_total_blog_viewed");

    $criteria->addSelectColumn("state.pres as pres");
    $criteria->addSelectColumn("state.state as state");

    $criteria->addSelectColumn("btq_user_sales_choice.type as choice_type");
    $criteria->addSelectColumn("btq_user_sales_choice.opt_value as choice_value");
    $criteria->addSelectColumn("btq_user_sales_choice.opt_text as choice_text");
    $criteria->addSelectColumn("btq_user.pfu_customer_id as pfu_customer_id");
    $criteria->addSelectColumn("lead_schedule.id as schedule_id");
    $criteria->addSelectColumn("lead_schedule.created_at as schedule_date");

    $criteria->addJoin(self::STATE_ID, StatePeer::ID, Criteria::LEFT_JOIN);
    $criteria->addJoin(self::BTQ_USER_SALES_CHOICE_ID, BtqUserSalesChoicePeer::ID, Criteria::LEFT_JOIN);
    $criteria->addJoin(self::ID, LeadSchedulePeer::LEAD_ID, Criteria::LEFT_JOIN);
    $criteria->addJoin(self::DRID, BtqDoctorsPeer::ID, Criteria::LEFT_JOIN);
    $criteria->addJoin(self::ID, BtqUserTrackBlogVideoPeer::USER_ID, Criteria::LEFT_JOIN);
//    $criteria->addJoin(self::DRID, BtqDoctorPfuAdminPeer::BTQ_DOCTOR_ID, Criteria::LEFT_JOIN);
//    $criteria->addExtraJoin(BtqDoctorPfuAdminPeer::PFU_ADMIN_ID, PfuCustomerPeer::PFU_ADMIN_ID, Criteria::LEFT_JOIN, " AND " . PfuCustomerPeer::EMAIL . " = " . self::EMAIL);

    $criteria->addJoin(self::ID, EventDataPeer::BTQ_USER_ID, Criteria::LEFT_JOIN);

    //$criteria->addGroupByColumn(self::ID);
    $criteria->addGroupByColumn(self::EMAIL);
    //$criteria->addGroupByColumn(EventDataPeer::BTQ_USER_ID);
    $criteria->add(BtqUserPeer::IS_DUMMY_DETAIL, "1", Criteria::NOT_EQUAL);

    $criteria->addDescendingOrderByColumn(self::DATAIN);
    if (!empty($search_params)) {
      foreach ($search_params as $key => $param) {

        if (trim($param)) {
          $param = addslashes($param);

          switch ($key) {

            case 'name':
              $criteria->add(BtqUserPeer::NAME, "%" . $param . "%", Criteria::LIKE);
              break;

            case 'email':
              $criteria->add(BtqUserPeer::EMAIL, "%" . $param . "%", Criteria::LIKE);
              break;

            case 'dr_name':
              $criteria->add(BtqDoctorsPeer::DRNAME, "%" . $param . "%", Criteria::LIKE);
              break;

            case 'phone':
              $criteria->add(BtqUserPeer::TELEFON, "%" . $param . "%", Criteria::LIKE);
              break;

            case 'lead_from':
              $criteria->add(BtqUserPeer::LEAD_FROM, $param, Criteria::EQUAL);
              break;

            case 'start_date':
              $criteria->add(BtqUserPeer::DATAIN, $param . " 00:00:00", Criteria::GREATER_EQUAL);
              break;

            case 'end_date':
              $criteria->addAnd(BtqUserPeer::DATAIN, $param . " 23:59:59", Criteria::LESS_EQUAL);
              break;

            case 'location':
              if ($param == "Local")
                $criteria->add(StatePeer::PRES, array("MD", "VA", "DC"), Criteria::IN);
              else if ($param == "Non Local")
                $criteria->add(StatePeer::PRES, array("MD", "VA", "DC"), Criteria::NOT_IN);
              break;
          }
        }
      }
    }//FB::log($criteria);
    return $criteria;
//    return self::doSelectStmt($criteria)->fetchAll();
  }

If there is anything else you need i will provide!
Thanks

A: As you have a lot of joins and even more condition on fields which are very likely not indexed, the query can take its time. If you have a lot of data 1 Minute seems normal to me.
You can try adding a table you may call user_index in which you just put all those columns you want to query from all the tables you want to join (lets call them source tables). And every time you add/update/remove a row in any of those source tables you have to update the user_index too. If its not that neccesary that your user_index is always accurate you can also create a cron job which updates the user_index let's say every 5 minutes. Using this method your query will be a lot faster, if you update your user_index on every change of the source tables the save operations will be a little slower though.
Also check if the fields you have in your conditions are indexed correctly, the same accounts for the user_index table.


text:
Q: Word Macro AutoOpen not running I've got a Word document that contains an AutoOpen macro. It works fine until I upload it to out intranet for people to download. When some users opens it from the intranet, it opens an embedded instance of word within IE, the doucment opens but the AutoOpen does not run. If they download the document, then open it, it work correctly.
If I open the document from the Intranet from my PC it works correctly. So I suspect there is a problem with their setup. I have looked at the security level in word and it is medium.
Any Ideas on how to get it to run AutoOpen when opening from an intranet site?

A: You may want to check your clients' browser security settings. They might disallow execution of active content.


text:
Q: Why is using the framework's features considered wrong I joined a company as a junior developer and I get assigned to do maintenance and fixes to various applications.
In every project that I had to work in a team I always heard complains about my code being too "framework coupled" and that I should write the code using plain Java rather than using the Spring Framework's features (heck, I even got yelled at for using @Autowired rather than Constructor Injection)
I am really frustrated by this thing and I want to know if I am in the wrong. Aren't the framework's features the main reason a programmer is going to use that framework?

A: Usually, the reasoning behind that way of thinking is that it would be easier to one fine day swap the Framework you use today to some other with the minimum required effort. You might argue that this isn't something very common or that you do very often, but still, even if the reason does not convince you it is generally a good practice to try to decouple your code as much as possible from the underlying Framework for multiple reasons (in addition to the one just mentioned you also have unit testing made easier).
In regards to the @Autowired topic, constructor injection is usually preferred for two main reasons:

*

*You clearly define the dependencies for your class to work properly;

*It is easier to unit test it because mocking its dependencies is way easier if you can "inject" them via the constructor.

A: Please do not get confused between two different concepts: "conding standards for particular project" and "best practices" - if you are a junior developer you just need to accept conding standards, if you are a team lead you should carefully evaluate whether the "best practices" are actually best. Spring Framework is not only DI-framework but it also provides a lot of other useful capabilities (externalized configs, post-processors, AOP, transaction management, converters, etc - a lot of them), if your team decided to not get coupled with Spring Framework it means they are missing a lot of features (or need to implement those features from scratch) for the sake of hypothetical possibility to switch DI-framework in the future.
As regards to the evilness of "field injection", the problem is evangelists of "constructor injection" completely leave out the fact that there are a lot of cases where it does not work at all, for example consider the following code:
@Component
@RequiredArgsConstructor
class A {
  private final B b;
}

@Component
@RequiredArgsConstructor
class B {
  private final A a;
}

DI-framework will fail to bootstrap those beans due to circular dependencies, and you have the following options to make it work:

*

*do not use constructor injection

*put "somewhere" @Lazy annotation (or create your own proxy in order to stay clear of Spring). Where to put it? Actually in both classes, because the behaviour depends on the root of dependency resolution: if we start with A then B needs to be @Lazy and vice versa. But the problem is this workaround just moves the issue from bootstrap phase to runtime

*accept that you code smells and refactor it, but always keep in mind that bootstrap phase may fail any time, i.e. do the job that DI-framework is supposed to do