text:
Q: SQL - Get the antepenultimate (before previous group/phase) I have the following table and I'd like to get the antepenultimate or the value before the previous value.
I already have group, value and prev_value, dateint... I'm trying to derive prev_prev_value
 grp  value  prev_value    prev_prev_value     dateint
 -----------------------------------------------------------
 1       x       null         null               20200101
 1       x       null         null               20200102
 2       y        x           null               20200103
 2       y        x           null               20200104
 2       y        x           null               20200105
 3       z        y             x                20200106
 3       z        y             x                20200107
 3       z        y             x                20200108
 4       a        z             y                20200109

This is the table with test data (as a CTE)
with test as (
    select  1  as grp,     'x' as value ,      null as prev_value , 20200101 as dateint
    union
    select  1  as grp,     'x' as value ,      null as prev_value , 20200102 as dateint
    union
    select  2  as grp,     'y' as value ,      'x' as prev_value  , 20200103 as dateint
    union
    select  2  as grp,     'y' as value ,      'x' as prev_value  , 20200104 as dateint
    union
    select  2  as grp,     'y' as value ,      'x' as prev_value ,  20200105 as dateint
    union
    select  3  as grp,     'z' as value ,      'y' as prev_value ,  20200106 as dateint
    union
    select  3  as grp,     'z' as value ,      'y' as prev_value ,  20200107 as dateint
    union
    select  3  as grp,     'z' as value ,      'y' as prev_value ,  20200108 as dateint
    union
    select  4  as grp,     'a' as value ,      'z' as prev_value ,  20200109 as dateint

)

Any ideas on how to derive prev_prev_value I'd like to use window functions and avoid joins.
I've tried LAG but I have not been successful.

A: It appears that a nested FIRST(LAG.. did the job:
The logic behind that was to get the previous (lag) prev_value and get the FIRST value of that group
select grp,
       value,
       prev_value,
       FIRST(LAG(prev_value) over (order by dateint)) over (partition by grp order by dateint) as prev_prev_value,
       dateint
from test order by dateint

A: Use a window frame:
select t.*,
       LAST_VALUE(prev_value) OVER (ORDER BY dateint
                                    RANGE BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
                                   ) as prev_prev_value
from test t
order by dateint ;


text:
Q: postfix 'd+0' in Fortran real literal expressions Does anyone knwow what the postfix "d+0" means in the assignments to M1, M2 and M4 below or is there any resource on the web or a book where one is very likely to find this information?

      subroutine plot( t, x, p, q, nga, nt, wron,
     &                 ngq, gq, ngaq1, ngaq2, gaq, rwh, iwh )
        implicit none

        integer*4 nga, nt, ngq, ngaq1, ngaq2, iwh(*)

        real*8 t, x(*), p(*), q(*), wron(nga,*),
     &         gq(ngq,*), gaq(ngaq1,ngaq2,*), rwh(*)

        real*8 M1, M2, M3, M4, mr, mst, h3, Tc
        integer*8 iflag

c       DISCRETIZE1( Tc, rwh, iwh )

        M1 = 0.1362d+0
        M2 = 0.09806d+0
        M3 = M1 + M2
        M4 = 0.236d+0

        mr = M1*x(1) + M2*x(2) + M3*x(3) + M4*x(4)
        mst =  M1*q(1) + M2*q(2) + M4*q(3)

        call mess3( t, x, h3, p, q, rwh, iwh, iflag )

        write (10,100) t, x(1), x(2), x(3), x(4), Tc, h3, mr-mst
100     format( e20.10, 7(1x,e20.10) )

  end

A: It means "double precision" and the +0 means 10 to the zeroth power (zero is the exponent).
Here's a quote from first reference I could find:

A number stored in a computer is
limited in magnitude and precision.
The limits depend on the particular
computer. Thus, a REAL number has only
a certain number of significant
digits. If more significant digits are
required for a calculation, then
DOUBLE PRECISION numbers must be used.
A DOUBLE PRECISION constant is written
in the same exponential form as a
single precision REAL constant except
with a D instead of an E separating
the mantissa from the exponent.

And here is a quote from a better reference, www.fortran.com, specifically the F77 standard.

4.5.2 Double Precision Constant.
The forms of a double precision
constant are:

*

*Basic real constant
followed by a double precision
exponent

*Integer constant followed by
a double precision exponent

The value
of a double precision constant is the
product of the constant that precedes
the D and the power of ten indicated
by the integer following the D. The
integer constant part of form (2) may
be written with more digits than a
processor will use to approximate the
value of the constant.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GStreamer: dynamically link a tee while pipline is PLAYING Using GStreamer 1.16.3 on Ubuntu 20, C/C++. At some point during runtime, I'm trying to link a tee element (its src_0 is already linked and playing) to a recording bin which ends with a filesink.
The following snippet: create the recording bin, get the new filesink element, set its location property, add the recording bin to pipeline, sync recording bin state with pipeline, get pipeline's tee element, get its src request pad, get recording bin's sink pad, link src and sink pads to complete the process.
auto error = (GError *)nullptr;
auto recording_bin = gst_parse_bin_from_description("queue ! filesink name=recording_filesink", true, &error);
auto filesink = gst_bin_get_by_name(GST_BIN(recording_bin), "recording_filesink");

g_object_set(G_OBJECT(filesink), "location", "/home/.../record.ts", NULL);
g_object_unref(filesink);
gst_bin_add(GST_BIN(pipeline), recording_bin);
gst_element_sync_state_with_parent(recording_bin);

auto tee = gst_bin_get_by_name(GST_BIN(pipeline), "tee");
auto tee_src = gst_element_get_request_pad(tee, "src_%u");
auto recording_sink = gst_element_get_static_pad(recording_bin, "sink");
auto ret = gst_pad_link(tee_src, recording_sink);

g_object_unref(recording_sink);
g_object_unref(tee_src);
g_object_unref(tee);

After executing this above, ret is GST_PAD_LINK_OK, but the pipeline gets stuck - not displaying (1st tee src) and not recording (2nd tee src).
Is this the right way to dynamically link a tee src to a recording bin?


text:
Q: Kendo Grid custom action button icon OK, this is driving me nuts.
I have a Kendo UI grid control with a couple of custom toolbar items.  The same toolbar also has some "built-in" commands (Export to Excel, Export to PDF)
All works as designed, but... the built-in commands render as buttons with icons on the left.  For the life of me I cannot figure out what I need to do to get my custom toolbar items to have the same look and feel as the built-in commands, i.e., having a specified icon on the left of the text for the buttons.
Additionally, the custom buttons are rendering as anchor links, whereas the built-in commands render as buttons.
I don't want to replace the entire toolbar with a template (it's basically re-inventing the wheel for the built-in functions) but I want my custom commands to look and render like the built-in commands.
Is there a way of doing this?  I've already spent way too much time on this thing that seems like it should be very simple.
What I have tried:
I have tried making the HtmlAttributes of the custom commands to have classes of various permutations of k-icon, k-plus, and k-refresh... unfortunately, as these render as anchors instead of buttons, the library does not render the icon in the contained span element.
It also seems that we cannot apply templates to individual commands, which is quite frustrating, so I cannot manually structure these commands to look similar to the built-in commands.
        .ToolBar(tb =>
            {
                tb.Custom().Action("Create", "Cycle").Text("Create New Cycle").HtmlAttributes(new {@class = "k-plus"});
                tb.Custom().Name("update-inventory").Text("Update Inventory").HtmlAttributes(
                    new {onclick = "onUpdateInventory()", title = "Update the system inventory from the OMS", @class="k-refresh"});
                tb.Excel();
                tb.Pdf();
            })

There has to be a simple solution to this... doesn't there?

A: I ran into the same problem a while back, from what I've gathered on the forums it seems template is the way to go.  But you could use either the kendo menu or the kendo button widgets to make it look slick:
.ToolBar(toolbar =>
    {
        toolbar.Template(
            @<text>
            @*Menu*@

                @(Html.Kendo().Menu().Name("Toolbar").Items(items =>
                {
                    items.Add().Text("Add").ImageUrl(Url.Content("image.png"));
                }))

            @*or Button*@

                @(Html.Kendo().Button()
                    .Name("iconButton")
                    .HtmlAttributes( new {type = "button"} )
                    .SpriteCssClass("k-icon k-i-ungroup")
                    .Content("Sprite icon"))

            </text>);
    })

A: OK, I figured out how to make it look right, but there has to be a better way to do this.
First, some observations.
1) The "Name" method for a custom action seems to not do anything.  At all.  It does not create an ID property for the element, like it does for just about every other Kendo widget, so I had to add the id into the HtmlAttributes method.
2) The k-plus and k-refresh point to the wrong positions on the sprite sheet.  Well, the k-plus points to the wrong position; k-refresh, while documented, does not seem to exist in Kendo styling.  I was able to fix this by adding my own positioning for the icons:
.k-icon-plus {
    background-position: -48px -64px;
}

.k-icon-refresh{
    background-position:-48px -112px;
}

Now, interestingly, the custom command buttons, while rendering as anchor elements instead of button elements like the built-ins, still render an empty span element inside of them like the built-ins, as (presumably) a placeholder for an icon.  Of course, it's not accessible in the configuration wrapper for MVC, so some jQuery magic needs to be employed.
First, I created an event to fire when the grid bound to data in my MVC wrapper like so:
.Events(e => e.DataBound("onDataBound"))

Next, I modified the HtmlAttributes for my custom commands like so:
tb.Custom().Action("Create", "Cycle")
    .Text("Create New Cycle").HtmlAttributes(new{id="create-cycle"});
tb.Custom().Text("Update Inventory").HtmlAttributes(
    new { onclick = "onUpdateInventory()", title = "Update the system inventory from the OMS", id="update-inventory" });

Then, I wired this up in the JavaScript function I referenced:
function onDataBound() {
    $('#create-cycle span').addClass('k-icon k-icon-plus');
    $('#update-inventory span').addClass('k-icon k-icon-refresh');
}

Now... this works.  But it sucks.  It's still an anchor element and not a button element, and the next release of kendo could completely break this.  I would dearly love for someone to show me how I just had to do something really simple instead of this ridiculous workaround.
Please please PLEASE somebody tell me this is not the right way to do this.


text:
Q: MPMoviePlayerController playing movies in reverse (backwards) is not smooth in iPhone App I am developing an iPhone application where I need to reverse a video playback. I am currently using XCode 4.2. I am trying to play a movie in reverse with the MPMoviePlayerController.
But when it plays in reverse it is not as smooth as playing it forward. It becomes a bit choppy and is not at all smooth. The following is my code.
- (void)viewDidLoad{
//code for initializing the movie player
MPMoviePlayerController videoPlayer =
[[MPMoviePlayerController alloc] initWithContentURL:"URL"];
self.videoPlayer = videoPlayer;
[videoPlayer release];
self.videoPlayer.view.userInteractionEnabled = NO;
self.videoPlayer.initialPlaybackTime = -1;
self.videoPlayer.shouldAutoplay=NO;
[self.videoPlayer prepareToPlay];

//code for initializing the button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

[button setTitle:@"Reverse" forState:UIControlStateNormal];

[button addTarget:self
action:@selector(reverseMovie) forControlEvents:UIControlEventTouchDown];

button.frame = CGRectMake(0, 0, 50, 40);

[self.view addSubview:button];
}

-(void)reverseMovie{
[self.videoPlayer setCurrentPlaybackRate:-1.0];
}

What could be the possible solution to this?

A: I tried to do the same in AVFoundation. I had to work it quite a lot before I managed to get it to work.
What I did was to generate image, reverse the order, put them in to an assetWriter, export the video and then play it.
You can download my code here: https://github.com/mikaelhellqvist/ReverseClip

A: Try this with AVPlayer
 avPlayer.rate=-1.0f;

This will set the rate to -ve,hence playing the video in reverse smoothly. :)


text:
Q: How to click on an element that is in the body pragmatically from inside of an angular component? I have a website on which I have crisp chat service running and I'm trying to click on the chat box from one of my component's typescript files.
The crisp chat box is a div with the id of crisp-client inside body tag. How do I click on it from inside my typescript?

A: You can use the ViewChild decorator and pass a template reference variable as a string, and manipulate the event. Here's a simple example of clicking Button 1, which programmatically clicks Button 2 and due to that click, the text of Button 2 is changed:
<button #button1 (click)="clickButton2()">
  Click to change the text of Button 2
</button>

<button #button2 (click)="changeText()">{{ buttonText }}</button>

buttonText = 'Button 2';

  @ViewChild('button2') button2: ElementRef<HTMLElement>;
  clickButton2() {
    let el: HTMLElement = this.button2.nativeElement;
    el.click();
  }

  changeText() {
    this.buttonText="Changed!"
  }

Here's a Stackblitz demo
UPDATE
You can access elements of body using document object in Angular. This way, you can achieve the click of the element which is inside body. Here's one more example where I am clicking the button which is inside body from a component.
<button (click)="handleClick()">Programatically click the button inside body</button>

ngOnInit() {
    let btn = document.getElementById('main');
    btn.addEventListener('click', (e: Event) => btn.innerHTML = "Clicked!");
  }

  handleClick() {
    document.getElementById('main').click();
  }

index.html

    <my-app>loading</my-app>
    <button id="main">Click</button>

Here's a Stackblitz demo.

A: Inject Renderer2 in constructor -
constructor(private renderer: Renderer2) {}

Get the crisp-client element in your component -
let crispClient = this.renderer.selectRootElement('#crisp-client');

Perform click() event -
crispClient.click();

Working demo here
Added a test method on div to check -


text:
Q: test class for batch apex not covering execute method I have written a batch class for cloning the opportunity and updating the stage field. Class is working fine. But test class is not covering the execute method. Logically I felt the test class is correct. Please provide any suggestions. Thanks in advance.

Following is the code for cloning to be tested-
global class UpdateOpportunity implements Database.Batchable<sObject>{

string query;

global Database.querylocator start(Database.BatchableContext BC){

String oppRecordTypeID = Schema.getGlobalDescribe().get('Opportunity').getDescribe().getRecordTypeInfosByName().get('Small Group').getRecordTypeId();

Query = 'Select id, name,StageName,RecordTypeId,Type,Description,CloseDate,Amount,Reason_for_loss__c,Renewal_date__c From Opportunity where StageName = \'Closed Won\' AND RecordTypeId = :oppRecordTypeID AND Renewal_date__c != null ';
return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<Opportunity> scope1){
List<Opportunity> list1 = new List<Opportunity>();
Date t = Date.today();
for(Opportunity p : Scope1){
if(p.Renewal_date__c == t)
{
Opportunity opp=new Opportunity();
opp = p.clone();
opp.StageName = 'Qualification';
list1.add(opp);
}
}

try {

insert list1;
}
catch(Exception e) {
System.debug(e);
}
}

global void finish(Database.BatchableContext BC){
}
}

Test Class -
@isTest
public class TestOpp
{
    static testMethod void BatchProcessAccount_TestMethod (){

         List<Opportunity> orglist = new List<Opportunity>();
         List<Opportunity> clonedlist = new List<Opportunity>();
         integer i = 0;

         for(i=0;i<5;i++)
         {
             Opportunity opp=new Opportunity();
                        opp.Name = 'opp' + i;
                        opp.StageName = 'Qualification';
                        opp.Type = 'New Customer';
                        opp.Description = 'test desc';
                        opp.CloseDate = Date.today();
                        opp.Renewal_date__c = Date.today();
                        opp.Amount = 2220;
                        opp.Reason_for_loss__c = 'abc';
                        opp.RecordTypeId = Schema.getGlobalDescribe().get('Opportunity').getDescribe().getRecordTypeInfosByName().get('Small Group').getRecordTypeId();
                        orglist.add(opp);
         }

        insert orglist;

        for(Opportunity p : orglist){
            Opportunity opp=new Opportunity();
            opp = p.clone();
            opp.StageName = 'Qualification';
            clonedlist.add(opp);

        }
        try{
            insert clonedlist;
        }
        catch(Exception e){
            system.debug(e);
        }

        Test.startTest();
        UpdateOpportunity tb = new UpdateOpportunity();
        Id batchId = Database.executeBatch(tb);
        Test.stopTest();

  }

}

A: If the execute() method isn't covered, that means the start() method returned an empty list.
Your start() method is:
Query = 'Select id, name, StageName, RecordTypeId, Type, Description,' +
      ' CloseDate,Amount,Reason_for_loss__c,Renewal_date__c' +
   ' From Opportunity ' +
   ' where StageName = \'Closed Won\' AND ' +
   ' RecordTypeId = :oppRecordTypeID AND ' +
   ' Renewal_date__c != null ';
return Database.getQueryLocator(query);

Hence, your mock test data doesn't match the criteria.
So, how to diagnose?

*

*after inserting the mock data in the test method, requery it and use system.debug to verify the values. This way you can check to see if any triggers or Process Builder/Flows have altered the data such that it no longer meets the start() method filter.

A: In Batch class you have query on opportunity object where StageName = 'Closed Won' and in test class you dont have any records of opportunity with the Stage field value as Closed Won.
In batch class execute method is not covered because the query is not returning any result to execute method.


text:
Q: "CSRF detected" with Omniauth and Google I'm getting this

OmniAuth::Strategies::OAuth2::CallbackError at /auth/google/callback
  csrf_detected | CSRF detected

My code:
require 'sinatra'
require "sinatra/json"
require "sinatra/config_file"
require 'omniauth-oauth2'
require 'omniauth-google-oauth2'

use Rack::Logger

config_file "config/app_config.yml"
use Rack::Session::Cookie, secret: '5fb7w345y3489f523y4h'

configure do
  enable :sessions
end

use OmniAuth::Builder do
  provider :google_oauth2, settings.google[:client_id], settings.google[:secret],
    {
      :scope => "userinfo.profile",
      :access_type => "offline",
      :prompt => "select_account consent",
      :name => "google"
    }
end

get '/list' do
  json get_list
end

get '/' do
  %Q|Sign in with Google|
end

get '/auth/:name/callback' do
  @auth = request.env['omniauth.auth']
  @auth.inspect
end

My callback is returning both code and state.

A: This problem occurs with rails when the domain defined in /config/initializer/session_store.rb is different from the origin/redirect_uri defined in the google api console.
MyApp::Application.config.session_store :cookie_store, key: '_app_session', domain: 'my_app.com'

Removing the domain params or using the same domain on both sides fixed the problem.

A: If you are using Devise with OmniAuth you need to skip the extra omniauth.rb initializer file and simply add config.provider "KEY", "SECRET" inside your initializers/devise.rb and then carry on with your implementation.

A: Got the same problem

(google_oauth2) Callback phase initiated.
  (google_oauth2)
  Authentication failure! csrf_detected:
  OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF
  detected

Last Omniauth-oauth2 update introduced the "state" param has a mandatory field.
Some people suggest using provider_ignores_state: true but it's a bad idea because it introduces csrf flaw
Guess we'll have to downgrade to previous version to keep google_oauth2 working.
Issue it on https://github.com/intridea/omniauth-oauth2/issues/58

A: Are you hitting back and reattempting to log in? I was getting this issue and it was really confusing me, but it was because I was going back to retry. If I typed in the address again, I wouldn't get the issue


text:
Q: SQL update - how to toggle? I want to create a 'toggle' effekt in an SQL update statement. If the value of 'important' is 1 then query should update it to 0 and vice versa. If the value is 0 the query should update it to 1 within the database.
UPDATE items SET important = case when 0 then 1 else 0 end WHERE id = x

A: Use arithmetic:
UPDATE items
    SET important = 1 - important
    WHERE id = x;

However, your code should also work.
Perhaps an even better way in MySQL is using NOT:
UPDATE items
    SET important = NOT important
    WHERE id = x;

This will not work in other databases, but it works in MySQL because it treats numbers as booleans in a boolean context, with 1 for true and 0 for false.

A: One more way to toggle, using ELT() function
UPDATE items
SET important = ELT(important + 1, 1, 0)
WHERE id = x;

ELT() returns the Nth element of the list of strings


text:
Q: vNext for Windows installer Windows installer version 5.0 released long time ago. Will there be any future development on this or Microsoft is going to deprecate it?
I am asking this as we are creating many new installers based on MSI technology. If not MSI, what it's alternative?

A: Windows Installer hasn't had a roadmap in years. It's not deprecated either though.  It just is what it is and still works and is still supported.
There's been a half dozen attempts to replace MSI with the latest being MSIX but all of them fall short of what MSI can do.
MSI is still the best choice for most installers IMO.  (Been writing installers since 1997 and MSI since 2003.)

A: At FireGiant, we've taken to calling the Windows Installer (MSI) the "Anything Installation Engine". It is the only Windows installation technology that is powerful and flexible enough to install anything.
While I'd like to see Windows continue to invest in the technology over more constrained installation technologies, they don't need to.
This fact leads to the sole upside of a stable installation technology: They aren't messing with it. :)


text:
Q: Drag and Drop issue with Anypoint Studio I am new to Mule and Anypoint Studio (64bit Version: 5.2.0), I can't add "Byte Array to String" transformer using drag and drop.

A: Validate your <%installation_Direcotry%>/AnypointStudio.ini for assigned memory, it should be :
-Xms584m
-Xmx1024m
-XX:MaxPermSize=784m

A: First check you assigned memory by checking the <%installation_Direcotry%>/AnypointStudio.ini file in case your studio gets hanged.
If it is ok then you have multiple options to place to place a processor in palette.

*

*select the transformer in the palette then drag & drop it to the process area where you want to put the transformer.

*select the transformer in the palette then directly click on the process area where you want to put the transformer.you don't need to drag & drop.

*you can also write the xml configuration for the same just by pressing ctrl + space options that would pop-up the list of components.

HTH.

A: You have to drop the 'Byte Array to String' transformed within the 'Process' box of the flow, not outside it.


text:
Q: expandable optional parameter to enumerate environment The MWE below, by using paralist package, is supposed to allow \begin{enumerate}[...] where ... is flexible in "some way" (inherits from enumerates above).
\documentclass[a4paper,10pt]{report}

\usepackage{paralist,xargs}

\newcommand\mwe[2]{[{\ref{#1}.}.#2]}

\begin{document}

\newenvironmentx{enumwe}[2][2=1]{%
  \begin{enumerate}\mwe{#1}{#2}%
  %\expandafter\begin\expandafter{\expandafter enumerate\expandafter}\mwe{#1}{#2}%
  \ignorespaces%
}{\end{enumerate}%
  \ignorespacesafterend%
}

\begin{enumerate}[{A}1]

\item \label{one} {\bfseries~Appendix One}

  \begin{enumwe}{one}
    \item text
  \end{enumwe}

\end{enumerate}

\end{document}

However, the commented line seems a wrong attempt, while the MWE typesets wrong.
The expanded result expected would be the following.
\begin{enumerate}[{A}1]
\item \label{one} {\bfseries~Appendix One}
  \begin{enumerate}[{A1.}1.]
    \item text
  \end{enumerate}
\end{enumerate}

I appreciate any help or suggestions.
P.S.: I actually need to expand a macro in the optional parameter to enumerate environment, like \begin{enumerate}[\mwe{...}1.], but it's not working (the ?? occurs everywhere) and this MWE is my approach, but I got stuck  with the weird error:
! LaTeX Error: \begin{enumerate} on input line 21 ended by \end{enumerate}.

A: \expandafter only steps over a single token not brace groups, so the simplest thing is to put everything you want to step over into a single token:
\documentclass[a4paper,10pt]{report}

\usepackage{paralist,xargs}

\newcommand\mwe[2]{[{\ref{#1}.}.#2]}

\begin{document}

\newenvironmentx{enumwe}[2][2=1]{%
  \def\temp{\begin{enumerate}}%
  \expandafter\temp\mwe{#1}{#2}%
  \ignorespaces%
}{\end{enumerate}%
  \ignorespacesafterend%
}

\begin{enumerate}[{A}1]

\item \label{one} {\bfseries~Appendix One}

  \begin{enumwe}{one}
    \item text
  \end{enumwe}

\end{enumerate}

\end{document}


text:
Q: How to preserve the value of thread variable in a multi-threaded program I have a code which spawns a new thread every 5 seconds and each thread periodically prints out the value of a counter. It starts up to 10 threads in total.
Here's the code:
public static void main(String[] args) {
    ScheduledExecutorService task = Executors.newScheduledThreadPool(10);
    AtomicInteger counter = new AtomicInteger(0);
    int i = 0;
    while (i < 10) {
        // sleep 5 seconds
        sleep(5);
        task.scheduleAtFixedRate(() -> {
            String threadName = Thread.currentThread().getName();
            int newCounter = counter.get();
            System.out.println(String.format("[%s] counter = %d" , threadName, newCounter));
        }, 0, 2, TimeUnit.SECONDS);

        counter.getAndIncrement();
        ++i;
    }
}

private static void sleep(int sleepTime) {
    try {
        TimeUnit.SECONDS.sleep(sleepTime);
    } catch (InterruptedException ie) {

    }
}

Here's the output:
[pool-1-thread-1] counter = 1
[pool-1-thread-1] counter = 1
[pool-1-thread-2] counter = 1
[pool-1-thread-3] counter = 1
[pool-1-thread-1] counter = 2
[pool-1-thread-2] counter = 2
[pool-1-thread-4] counter = 2
[pool-1-thread-5] counter = 2
[pool-1-thread-3] counter = 2
[pool-1-thread-1] counter = 3
[pool-1-thread-7] counter = 3
[pool-1-thread-6] counter = 3
[pool-1-thread-8] counter = 3
[pool-1-thread-4] counter = 3
[pool-1-thread-9] counter = 3
[pool-1-thread-5] counter = 3
[pool-1-thread-10] counter = 3
[pool-1-thread-1] counter = 4
   .......

I want each thread to print out its original value, for example, pool-1-thread-1 should print out 0 or 1 (depending on whether counter gets incremented first or the thread starts first) all the time,  the second thread should emit previous counter + 1 persistently, ... such as follows:
[pool-1-thread-1] counter = 1
[pool-1-thread-1] counter = 1
[pool-1-thread-2] counter = 2
[pool-1-thread-3] counter = 3
[pool-1-thread-1] counter = 1
[pool-1-thread-2] counter = 2
[pool-1-thread-4] counter = 4
[pool-1-thread-5] counter = 5
[pool-1-thread-3] counter = 3
[pool-1-thread-1] counter = 1
[pool-1-thread-7] counter = 7
  .......

My question is how do I make the newCounter local variable keeps its original value in each thread. The way I can think of is to store the mapping of thread name to its original value in a thread-safe hash table. Is there any cleaner way to accomplish this? Thanks

A: To bind a value to a particular thread, you can use a ThreadLocal variable.
The ThreadId sample class in the javadoc can be easily adapted to solve your use-case.
public static void main(String[] args) {
    ScheduledExecutorService task = Executors.newScheduledThreadPool(10);
    AtomicInteger counter = new AtomicInteger(0);
    ThreadLocal<Integer> id = ThreadLocal.withInitial(counter::incrementAndGet);
    int i = 0;
    while (i < 10) {
        // sleep 5 seconds
        sleep(5);
        task.scheduleAtFixedRate(() -> {
            String threadName = Thread.currentThread().getName();
            System.out.println(String.format("[%s] counter = %d" , threadName, id.get()));
        }, 0, 2, TimeUnit.SECONDS);

        ++i;
    }
}

private static void sleep(int sleepTime) {
    try {
        TimeUnit.SECONDS.sleep(sleepTime);
    } catch (InterruptedException ie) {

    }
}


text:
Q: Error: The input character is not valid in MATLAB statements or expressions I have an error when I try to run this on Matlab r2012b
t=-2:.1:5;
x=3*exp(0.4*t);
y=2*exp(-0.9*t);
plot(t,x,t,y,':');
legend('x(t)','y(t)')

Yielding the error:
>> t=-2:.1:5;
 t=-2:.1:5;
   |
Error: The input character is not
valid in MATLAB statements or
expressions.

Editors note:
First code line of original post contained a "hidden" character (single source of error) which was, due to SO formatting, lost in the first edit (intended to fix code formatting). Even when re-rolling back to revision 1, the "hidden" character is lost.

t={Character: ASCII Code 2}-2:.1:5;

Original code (thanks Daniel) can be found here

*

*http://pastebin.com/SyEHKpjR

A: In your code the third char of t=-2:.1:5; is not a whitespace (ASCII Code 32) like MATLAB displays it,  it is a start of text (ASCII Code 2). I have no idea how these control chars got into your code, but to clean it up I recommend a text editor which allows to display all hidden chars.


text:
Q: Recursive binary search program Here's my method for a recursive binary search. This is suppose to find a phone number from a sorted list, but it's only working for the first number in the file and says everything else is not found. Can anyone help me figure out what's wrong?
static int binary (String num, String[] phone, int low, int high)
{
    if ((high - low) <= 1)
    {
        if (phone [low].equals (num))
        {
            return low;
        }
        else if (phone [high].equals (num))
        {
            return high;
        }
        else
        {
            return -1;
        }
    }
    int mid = (low + high) / 2;
    if (phone [mid].compareTo (num) > 0)
    {
        return binary (num, phone, 0, mid);
    }
    else if (phone [mid].compareTo (num) < 0)
    {
        return binary (num, phone, mid, high);
    }
    else
    {
        return -1;
    }
}

A: I think you want
if (phone [mid].compareTo (num) > 0)
{
    return binary (num, phone, low, mid-1);
}
else if (phone [mid].compareTo (num) < 0)
{
    return binary (num, phone, mid+1, high);
}

Also, you do more checks than are necessary:
static int binary (String num, String[] phone, int low, int high)
{
    if(low > high)
    {
        return -1;
    }
    int mid = (low + high) / 2;
    int compare = phone[mid].compareTo(num);
    return compare > 0 ? binary (num, phone, low, mid-1);
        : compare < 0 ? binary (num, phone, mid+1, high);
        -1;
}


text:
Q: Artifacts Between rating bar images I Created My custom Rating bar in android but I'm having some problems on devices with Lower lvl API's.
I successfully implemented it on a htc one x with ICS however on a htc desire with android 2.2 I have artifacts between the images.
I created png resources for every screen density.
Here is an image of htc desire with hdpi screen:

Here is an image of htc one x with xhdpi screen:

Following is included in my layout file:

Following is my drawable resource:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background"
          android:drawable="@drawable/bone_empty" />
    <item android:id="@+android:id/progress"
          android:drawable="@drawable/bone_full" />
</layer-list>

And Following is my res/values-hdpi/styles.xml (used by htc desire)
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="dogBar" parent="@android:style/Widget.RatingBar">
        <item name="android:progressDrawable">@drawable/dog_rating_bar</item>
        <item name="android:minHeight">48dp</item>
        <item name="android:maxHeight">48dp</item>
    </style>
</resources>

And Following is my res/values-xhdpi/styles.xml (Used by htc one x)
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="dogBar" parent="@android:style/Widget.RatingBar">
        <item name="android:progressDrawable">@drawable/dog_rating_bar</item>
        <item name="android:minHeight">64dp</item>
        <item name="android:maxHeight">64dp</item>
    </style>
</resources>


text:
Q: Using Mapnik's OGR plugin for Oracle Spatial Database Mapnik wiki page of OGR plugin says that I can use the plugin for MSSQL server in the following manner:
<Layer name="mssql" srs="+proj=latlong +datum=WGS84">
    <StyleName>mssql_style</StyleName>
    <Datasource>
        <!-- mssql database must contain geometry_columns and spatial_ref_sys metadata tables-->
        <Parameter name="type">ogr</Parameter>
        <Parameter name="string">MSSQL:server=localhost;database=gis;trusted_connection=yes</Parameter>
        <Parameter name="layer_by_sql">SELECT * FROM dbo.planet_osm_line</Parameter>
        <Parameter name="extent">-180,-90,180,89.99</Parameter>
    </Datasource>
</Layer>

I want to use it for Oracle Spatial Database. How should I modify the parameter with name = "string" in the XML so that I can?
Also, do I need to install any additional software and make any configurations on my machine so that I can connect to the database?
By the way, the database is not on my localhost but in a remote location.


text:
Q: Solidity - Check if an index exists in contract A from Contract B I have two contracts called A and B. I defined an array variable in contract A. I want to check if an index exists or not from contract B.
A.sol
contract A {
    SomeStruct[] private myArray;
    /// @notice Check if an index exists
    function isIndexExists(uint256 index) public view returns (bool) {
      if (myArray[index].isExist) {
        return true;
      } else {
        return false;
      }
    }
}

B.sol
contract B is A {
  function todo(uint256 index) public view returns (bool) {
    if (isIndexExists(index)) {
      // ... logic
    } else {
      revert("Index in not exist")l
    }
  }
}

The isIndexExists function works well When called directly from contract A, But in B an error occurs.
I make this call from the JS test environment in Truffle.
Error:
Error: Returned error: VM Exception while processing transaction: revert

A: The error is caused by either of two reasons:

*

*Out of bounds: You're accessing a non-existing index of the array in the myArray[index] expression.

*Missing return: You're not returning any value in the // ... logic section of the todo() function that promises to return a bool.

A: Array myArray is dynamically sized. You cannot safely try to access an element with an arbitrary index using the [] operator, you first need to check if the index is out of bounds. Here is how you could change your function in contract A to achieve this:
function isIndexExists(uint256 index) public view returns (bool) {
  // If the index is out of bounds, then there is no such element
  if (index >= myArray.length) {
    return false;
  }

  // We know that there is an object with that index, so check its 'isExist' property
  return myArray[index].isExist;
}

BTW, note that when you are checking some expression that returns a boolean, you can directly return that value. You don't need the redundant if-else, which takes 5 lines compared to this approach which only takes one line of code.


text:
Q: How to configure default DISPLAY variable on gdm for x11vnc to work (changed in CentOS 8 from CentOS 7) Problem: GDM/KDE is defaulting to use DISPLAY :1 instead of DISPLAY :0 in CentOS 8, and I want it to use DISPLAY :0 like in CentOS 7. This is affecting x11vnc and causing more of a headache to VNC into the machines (I cannot VNC into the login screen at all now).
Old/Working Version

*

*CentOS 7

*KDE SC Version 4.14.8

*GDM Version 3.28.2

When ssh'ing into old machine to run x11vnc, we can see that :0 is the DISPLAY
$ w -us
USER   TTY   FROM  IDLE   WHAT
user   :0    :0    ?xdm?  /bin/sh /usr/bin/startkde

Broken/New Version

*

*CentOS Stream 8

*KDE Plasma Version: 5.18.4

*GDM Version 40.0

When ssh'ing into new machine to run x11vnc, we can see that :1 is the DISPLAY
$ w -us
USER   TTY   FROM  IDLE   WHAT
user   :1    :1    ?xdm?  /usr/libexec/gdm-x-session --register-session --run-script /usr/bin/startplasma-x11
user   pts/0 :1   46:05  kded5

So now to starting x11vnc in a logged in session on CentOS 8 I need to run x11vnc -display :1, which isn't a big deal, just a little annoying and affects some scripts. The bigger issue is that I cannot VNC into the login screen now. Using variations off ssh -X x11vnc -display :1, running as root, & more.
Both have exact same ssh config (X11 forwarding and stuff).
Edit:
Errors when trying to VNC into login screen:
~> ssh user@centos8
$ echo $DISPLAY

$ x11vnc # this works on CentOS 7 w/ and w/o X11 forwarding
...
10/06/2021 16:28:55 *** XOpenDisplay failed. No -display or DISPLAY.
Invalid MIT-MAGIC-COOKIE-1 key10/06/2021 16:28:59 XOpenDisplay(":0") failed.
10/06/2021 16:28:59 Trying again with XAUTHLOCALHOSTNAME=localhost ...
Invalid MIT-MAGIC-COOKIE-1 key10/06/2021 16:28:59 XOpenDisplay(":0") failed.
10/06/2021 16:28:59 Trying again with unset XAUTHLOCALHOSTNAME ...
Invalid MIT-MAGIC-COOKIE-1 key10/06/2021 16:28:59
...
10/06/2021 16:28:59 ***************************************
10/06/2021 16:28:59 *** XOpenDisplay failed (:0)
...

$ x11vnc -display :1
10/06/2021 16:30:16 *** XOpenDisplay failed (:1)
$ exit

~> ssh -X user@centos8
$ echo $DISPLAY
localhost:10.0
$ x11vnc
...
10/06/2021 16:24:16 WARNING: DISPLAY starts with localhost: 'localhost:10.0'
10/06/2021 16:24:16 WARNING: Is this an SSH X11 port forwarding?  You most
10/06/2021 16:24:16 WARNING: likely don't want x11vnc to use that DISPLAY.
10/06/2021 16:24:16 WARNING: You probably should supply something
10/06/2021 16:24:16 WARNING: like: -display :0  to access the physical
10/06/2021 16:24:16 WARNING: X display on the machine where x11vnc is running.
...
X11 MIT Shared Memory Attach failed:
  Is your DISPLAY=localhost:10.0 on a remote machine?
  Note:   DISPLAY=localhost:N suggests a SSH X11 redir to a remote machine.
  Suggestion, use: x11vnc -display :0 ... for local display :0

caught X11 error:
10/06/2021 16:24:17 deleted 53 tile_row polling images.
X Error of failed request:  BadRequest (invalid request code or no such operation)
  Major opcode of failed request:  130 (MIT-SHM)
  Minor opcode of failed request:  1 (X_ShmAttach)
  Serial number of failed request:  56
  Current serial number in output stream:  111

$ x11vnc -display :1
...
10/06/2021 16:26:16 *** XOpenDisplay failed (:1)
...

Similar errors running as root

A: I downloaded from CentOS7 gdm-3.28.2-26.el7.x86_64.rpm and pulseaudio-gdm-hooks-10.0-6.el7_9.x86_64.rpm and installed (downgraded) these two packages on Rocky Linux 8 (8.4) using:
dnf install gdm-3.28.2-26.el7.x86_64.rpm pulseaudio-gdm-hooks-10.0-6.el7_9.x86_64.rpm
gdm in this slightly older version is using "DISPLAY :0" and I can log into login screen using x11vnc.
Not sure what dependencies gdm has and what side effects may occur. Updating OS will reinstall the newer gdm version of Rocky Linux 8 which is using "DISPLAY :1".

A: I have this same issue, really annoying. My brute force solution was just to wrap VNC inside a script, that tries each of :0 and :1 displays. :0 is always the login screen, and :1 is always the gnome session.  So with this, I can VNC into the workstation, log in. Then the VNC session is terminated, i have to restart it, then I can see my desktop. Logging out also kills X, so the VNC session is terminated again.
Something like,
(
while true; do
   for displayNum in {0..1} ; do
      if ! pgrep -f "x11vnc -repeat -display" > /dev/null; then

         currentUserId=$(pgrep -x gnome-shell |
                         xargs --no-run-if-empty ps -ho uid |
                         awk '{print $1}')

         x11vnc -repeat -display ":${displayNum}" -rfbport 5900 \
                -shared -auth /run/user/${currentUserId}/gdm/Xauthority \
                -forever
         sleep 0.5
      else
         sleep 10
      fi
   done
done
) &


text:
Q: Tapku Library - Show Appointment Detail I have a TKCalendarDayTimelineView displaying several events.  When I click on an event it fires the gotSingleTapAtPoint method.  Using this method, I want to display the details of the event that was clicked on in a new view.  How do I go about this?  Is there a way to determine what event was chosen from the selected point?
- (void)tapDetectingView:(TapDetectingView *)view gotSingleTapAtPoint:(CGPoint)tapPoint
{
    //get the selected event, use the details to init a new view
    CGPoint pointInTimeLine = CGPointZero;
    pointInTimeLine = [view convertPoint:tapPoint toView:self.scrollView];
}

A: You should implement the optional calendarDayTimelineView:eventViewWasSelected method of the TKCalendarDayTimelineViewDelegate protocol. Don't mess with tapDetectingView:gotSingleTapAtPoint.
- (void)calendarDayTimelineView:(TKCalendarDayTimelineView*)calendarDayTimeline eventViewWasSelected:(TKCalendarDayEventView *)eventView
{
   // Access the event that was tapped by "eventView.sourceEvent". Something like:
   EKEvent *event = eventView.sourceEvent;
   // Now use EKEventViewController to display the event
}


text:
Q: Is an irrational number odd or even? My sister just asked this question to me: "Is an irrational number odd or even?" I told her that decimals are not odd or even and that does imply that not recurring and non repeating decimals will also not be odd or even. But I want a rigorous math proof for this. Can someone help me with this proof? Also, can I do this proof by contradiction?

A: The original concept of even and odd is defined on integers. However, one can ask: Is there a natural extension to all real numbers? And if so, what would be the evenness or oddness of irrational numbers?
Now, what would we demand of such an extension? Well, the most important demand is, of course, that integers are even under the extended definition if and only if they are even under the normal definition (that is, also our new definition should for example give us that $2$ is even and $5$ is odd).
Let's therefore try a few properties of even/odd integers:

*

*An number is even if can be written as $2x$.
In the real numbers, every number can be written as $2x$. Thus this definition does not work.

*A number is even if it is twice an integer.
This of course works on the real numbers (and makes all non-integers odd). But it seems to be an odd extension; it's certainly not very useful.

*The sum of two even or two odd numbers is even, the sum of an even and an odd number is odd; 1 is odd.
Since $1=\frac12+\frac12$, $\frac12$ could be neither even nor odd. This definitiion could probably be made work by making three types of numbers: even, odd or neither. But there are many ways this could be done; the most natural one would be to declare all non-integers as neither even nor odd; but that's where we started anyway. For rational numbers, it would also work if a number is even if for the maximally cancelled form the numerator is even, and odd if both numerator and denominator are odd. But that definition has no natural extension to irrational numbers (except, again, all being neither even nor odd).

*Adding $1$ to an even number gives an odd number, and vice versa.
Again, this gives not an unique definition. The most natural definition would be to use a rounding function $\mathbb R\to\mathbb Z$ (like rounding to nearest, rounding up, rounding down, or rounding towards zero) and defining $x$ to be even if $r(x)$ is even. However, which rounding function to choose?
So there are ways to extend even/odd to reals, however you'll definitely have to give up some properties of even/odd numbers, and it is not clear which of those that are possible should be chosen, especially given that the resulting definitions are not too useful anyway. None of them really capture the concept of even and odd numbers.

A: An irrational number only makes sense if we look at numbers beyond the rationals. In any extension of the rationals we will find the number $\frac 12$. And then any number is divisible by $2$.
We could say, in this context, that every number is even. The problem with this is that the concept simply ceases to be useful when used in that way. So we don't use it like that, and retain it for contexts where divisibility by $2$ makes a difference.

A: One useful approach to generalize odd and even numbers to the irrational numbers is to quantify the "amount of evenness" of a number. We will see that $12$ is "twice as even" as $6$. Then, instead of asking whether an irrational number is odd or even, ask how even it is.
First, start with Patrick Da Silva's answer to the linked question. He explains the basics much better than I could.
Still with me? Good! Now the challenge is to extend the 2-adic valuation $\nu_2$ from the rational numbers to the real numbers. This can indeed be done, and it gives us simple answers for some irrational numbers. For example, $\nu_2(\sqrt 2)=\frac12$. In this sense you could say that $\sqrt 2$ is "half even", although that's not standard terminology!
Sadly, there isn't a unique extension of $\nu_2$ to all real numbers. I can't tell you what $\nu_2(\pi)$ is, because it depends on the extension. Nonetheless, the mere fact that an extension exists turns out to be useful. For example:

*

*Monsky's theorem. It is not possible to dissect a square into an odd number of triangles of equal area.

That sounds like a classical result of ancient Greek geometry, right? Nope, it was proved in 1970 using the existence of an extension of $\nu_2$ to the real numbers! The proof hinges on an elaborate coloring of the plane that, at its core, and in layman's terms, does what you want: it calls irrational numbers odd or even.

A: I guess that the original "motivation" for the odd/even distinction in human culture was to know if a number of things (like apples or stones) could be divided between two people in a fair way without having to cut or break a remainder one. And also to known if things could be paired: three women and three men was fine, but one woman and two men meant conflict!
The above distinction makes sense with natural numbers... But what motivation would we have to define odd/even for the rational or irrational for example? Any rational divided by two results in a rational, e.g. 1.5 / 2 = 0.75. If we accept cut or broken things, then we don't care about remainders!

A: Definition.

Let $n\in \mathbb{Z}$ be an integer. $n$ is called even if ...

According to the definition only integers are even or odd. It is not something that you have to prove.

A: What you need first and foremost is not a proof but a definition.
Normally, one will say something like: one calls an integer even if it is divisible by $2$, and odd otherwise.
Then, being "even" and "odd" is a property of integers, and it makes no sense to ask it for other numbers. It also makes no sense to ask if a circle is even.
Now, you might have a different defintion of "even" and "odd" that makes sense for more numbers and the answer changes.
For example, if you extend the defintion as given above directly to the real numbers, then every number is even: in the real numbers every number is divisible by $2$, since $2X =a$ has a (real) solution for every $a$.

A: Here is one more perspective. Think of the congruence mod 2 relation $x \equiv y$, defined as "$x\equiv y$ if and only if $x-y$ is an integer multiple of $2$". (This is usually denoted $x \equiv y \pmod 2$, but I will omit the parenthesis because there will be no chance of confusion.)
It is not hard to verify that this is an equivalence relation: it is reflexive, symmetric, and transitive. The relation is well-defined over any subset of the real numbers, including, of course, the integers $\mathbb Z$. There are only two equivalence classes of $\mathbb{Z}$ modulo the "$\equiv$" relation: the even integers $[0] = \{0 + 2n: n \in \mathbb{Z}\}$ and the odd integers $[1] = \{1 + 2n: n \in \mathbb{Z}\}$.
Similarly, we can define the equivalence classes of the reals $\mathbb{R}$ modulo the "$\equiv$" relation. Here there are many more equivalence classes: except the odds $[1]$ and the evens $[0]$, there are also the equivalence classes $[0.5] =\{0.5 + 2n: n \in \mathbb Z\}$ and $[\sqrt{2}]=\{\sqrt{2} + 2n: n \in \mathbb{Z}\}$, for example. In fact there is a distinct equivalence class $[x] = \{x + 2n: n \in \mathbb{Z}\}$ for every $x \in [0, 2)$.
So in that sense, an irrational number, or in fact any number which is not an integer, is neither odd nor even, because it does not belong to either of the equivalence classes $[0]$ and $[1]$. This is because if $x$ is not an integer, then $x-0$ and $x-1$ are not integers either, and, therefore, neither of them is an integer multiple of $2$.

A: Closely related to other answers but might be good for the purpose. By contradiction:
For a given irrational a, assume it is odd.
a/2 is also irrational; call it b
2b is obviously even since odd + odd = even
so a is even.
So all irrationals are even,
which shows they cannot be split into two categories at least.
All rationals can be expressed as the product of two irrationals
(which is  just saying that a rational divided by an irrational is irrational)
so all rationals are even too.

∴ 1 is even

A: An even number is any integer that is divisible by 2 so the equations for any even number is:
 $N_E=2n:   n\in\Bbb Z$
An odd number is any integer that is not divisible by 2 so the equation for any odd number is:
$N_O=2n-1:  n\in\Bbb Z$
And if you put any integer (replaced by n shown on the equations above) to the equations shown above, none of the equations will give an irrational value so therefore an irrational number is not even and not odd, they are simply IRRATIONAL NUMBERS .

A: All odd numbers on the pascal triangle are in a Sierpinski triangle, which is  a fractal.

The binomial coefficient $\binom{n}{k}$ is defined for integers, but it can be extended to any real number.
$$\binom{\alpha }{k}= \frac{\alpha ^{\underline{k}}}{k!} $$
Another way is by using the Gamma function:
$$\binom{\alpha }{k}=\frac{\Gamma \left ( \alpha +1 \right )}{\Gamma \left ( k +1 \right )*\Gamma \left ( \alpha-k+1 \right )}$$
The thing with the Sierpinski triangle, is that since it is a fractal, it has infinite detail, if you zoom in.
So the concept of being odd can be extended to all numbers  $\binom{n}{k}$ whose coordinates (n,k) fall in the Sierpinski triangle, in the sense that they share a property of odd numbers.
I don't know if the white triangles (made of even numbers on the pascal triangle) also contain odd numbers for non integer coordinates, but if they do, and also conform a fractal, the same concept apply.


text:
Q: Is it possible to integrate with respect to a defined segment instead of a given axis? Today I was solving a calculus exercise related to solids of revolution and I came up with, I think, a very difficult question. The exercise, as shown below in the link, asks for the volume of a solid when you rotate some areas around a couple of given segments.

The exercise becomes pretty simple if you rotate any of the given areas with respect to $\overline{OA}$ or $\overline{OC}$ , x and y axis respectively, but what has actually made me thinking was if you tried to rotate, for example, $\mathcal{R}_3$ around $\overline{OB}$. That would be the solid created by rotating $y=\sqrt[4]{x}$ with respect the segment $\overline{OB}$. Now I have the conception that in order to integrate this, the best way is to rotate the function to get an integral like $\int_{a}^{b} f(x)\, dx$ and be able to do it as usual with respect to x or y axis.
Alright, so the question I have is: Can you integrate with respect to a custom segment instead of the traditional x and y integration? No matter how hard it is, I just want to find out if it is possible.

A: It can be done indeed and you're correct about rotating the function and then taking the integral like you normally would but I'd do it so that instead of rotating the function, I would rotate the axis. In this case you would take the integral with respect to the "new $x$-axis". Let's see how it would be done with your particular example.
Let's begin by naming our new axis: Let $z$ and $w$ represent the "new $x$ and $y$ axis" respectively. Since the $z$-axis must go trough the line segment $\overline{OB}$, it can be represented with the equation $y=x$. We can choose the $w$-axis to be represented by $y=-x$. We say:
$$z=y-x\\w=y+x$$
EDIT:
This transformation of the axis also scales them by $\sqrt{2}$. To counteract that, we must multiply by $1/\sqrt{2}$:
$$z=(y-x)/\sqrt{2}\\w=(y+x)/\sqrt{2}.$$
Now we have to express the equation $y=\sqrt[4]{x}\Leftrightarrow y^4 = x$ in terms of $z$ and $w$.
We do it by first solving a system of equation for $x$ and $y$.
$$
\begin{cases}
z=(y-x)/\sqrt{2}
\\
w=(y+x)/\sqrt{2}
\end{cases}
\Leftrightarrow x=\frac{w-z}{\sqrt{2}} \quad \textrm{and} \quad y=\frac{w+z}{\sqrt{2}}
$$
Now we just need to substitute.
$$\begin{align}
\label{eqn:eqlabel}
\begin{split}
y^4&=x
\\
(\frac{w+z}{\sqrt{2}})^4&=\frac{w-z}{\sqrt{2}}
\end{split}
\end{align}$$
Now you would in theory solve for $w$ and integrate $\pi\int_0^{\sqrt{2}}w^2dz$ but the equation for $w$ is so huge that it's practically impossible to integrate by hand (See Wolfram|Alpha)...
You can check that all of this is correct by plotting $(\frac{w+z}{\sqrt{2}})^4=\frac{w-z}{\sqrt{2}}$. You will see that the resulting curve is basically $y=\sqrt[4]{x}$ but rotated by $45^{\circ}$(Plot here)


text:
Q: How to stretch svg to 100% width of parent I have the following svg triangle:
<svg class="triangle" viewBox="0 0 2 2"><path d="M0,2 h2, v-2 Z"/></svg>

I added some styling to the svg, but the 100% width doesn't work...
.triangle {
  fill: yellow;
  width: 100%;
}


text:
Q: Network Communication between a java socket (server) and a C++ socket (client) I know this must be a pretty common problem, but I haven't been able to find a definitive answer on how to do it.
First, assume we have a java server that accepts queries such as (I've just put the relevant lines, and I've taken out the exception handling for clarity):
    ServerSocket socket = new ServerSocket(port);
    while (true) {
        ClientWorker w;
        w = new ClientWorker(socket.accept());
        Thread t = new Thread(w);
        t.start();
    }

and then in the ClientWorker
    BufferedReader inFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
    DataOutputStream outToClient = new DataOutputStream(client.getOutputStream());

    String query = inFromClient.readLine();
    // process query here
    String response = "testresponse";

    outToClient.writeBytes(response + "\n");

    outToClient.close();
    inFromClient.close();
    client.close();

Right now I can get a java client that works with this server:
String query = "testquery";
Socket queryProcessorSocket = new Socket(queryIp,queryPort);
DataOutputStream queryProcessorDos = new DataOutputStream(queryProcessorSocket.getOutputStream());
BufferedReader queryProcessorReader = new BufferedReader(new InputStreamReader(queryProcessorSocket.getInputStream()));
queryProcessorDos.writeBytes(query + "\n");
String response = queryProcessorReader.readLine();

But how can I get a C++ client to do the same thing as the java client? I've tried many things but nothing seems to work. Ideally I wouldn't want to touch the java server, is that possible? If someone could point me to a good example or some sample code, that would be much appreciated. I searched through a lot of websites but to no avail.

A: Here I put a simple code to connect to a server. It may help you if this is your problem.
void client(const char* server_address, short server_port)
{
     int     sockfd;
     struct sockaddr_in servaddr;

     sockfd = socket(AF_INET, SOCK_STREAM, 0);

     memset(&servaddr, 0x00, sizeof(servaddr));
     servaddr.sin_family = AF_INET;
     servaddr.sin_port = htons(server_port);
     inet_pton(AF_INET, server_address, &servaddr.sin_addr);

     connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

     //from this point you can start write to the server and wait for its respose

     std::string buffer = "testquery";
     writen(sockfd, buffer.c_str(), buffer.length());

     char *ReadBuffer[512];
     while(1)
     {
         memset(ReadBuffer, 0x00, sizeof(ReadBuffer));
         int n = readn(sockfd, ReadBuffer, sizeof(ReadBuffer));
         if(n <= 0)
         {
             //or you dont have anything to read, or you have a problem
             break;
         }
         //this function does the hard job of knowing what to do with all these data
         processBuffer(ReadBuffer, n);
     }

 close(sockfd);

 }

I'm using Posix standard and the code is very simplified but I think its a start point.
Regards.

A: How do you mean "it doesn't work" ?
Without studying the code too carefully, my first concern is that you're converting a String (in chars, or byte-pairs) to bytes, and then sending these down the socket. Are you retrieving these in the same fashion on the C++ end ? i.e. using the same character encoding ?

A: As long as your're not using a language specific protocol (such as Java RMI) and using straight sockets (or some other language neutral protocol like web services) then it will work. You just have to make sure your client and server are speaking the same protocol (e.g. TCP/IP + your custom protocol on top). If using straight sockets you're basically sending binary over the wire - so you need to make sure you're encoding/decoding the data the same on both sides. Typically this is done with some sort of byte level protocol if you're rolling your own. As an example Project Dark Star is a game server written in Java but has clients in Java, C/C++, Flash etc. It uses user defined a binary protocol for cross language communications.

A: Yes you can have a C++ client (or a C client or a COBOL client or a perl client or a ruby client or a ... client) talk to a java server.  All you do is port the java code to the equivalent C++ code (or C code or COBOL code or perl code or ruby code or a ... code).  The server neither knows nor cares what language the client is written in.
I would start with this reference Internet Sockets and then use the POSIX API Documentation.

A: I had the same problem prior. The client was C++ based and it has to connect to my Java-based server both running on Windows. I was stumped for the longest time why the Java server would drop connection upon client connection.
Later I realised it because of the endian problems. Java VM = big endian, C++ (on my hardware) was little endian. Small problem but took a while to figure out for this amateur.


text:
Q: Trying to get a mean of CSV files after using concat() I have a directory of 20 CSV files so I have used the concat function to load them all in for reading purposes. However, I would like to take a mean of the columns but it's not working for me. Here is what I have so far...
path = r'/Users/Bry/Desktop/data'
filenames = glob.glob(path + "/*csv")

df = []
for filename in filenames:
    df.append(pd.read_csv(filename))
pd.concat(df, ignore_index =False)
df.mean()

I keep getting AttributeError: 'list' object has no attribute 'mean'

A: pd.concat returns concatenated DataFrame which you are ignoring.
mergedf = pd.concat(df, ignore_index=False)
mergedf.mean()

I am storing the return value of pd.concat in mergedf. Then you use this mergedf data frame to find mean and do other stuff.


text:
Q: Angular Xeditable - can't get correct value for validation using onbeforesave event I am trying to add validation logic to the editing of message format values we use. I have created plunker here to show the issue. Here is the code for the curly brace validation.
vm.formatCheck = function (resource) {

console.log(resource.Value);

if (resource.Value.indexOf('{') > -1 || resource.Value.indexOf('}') > -1) {

    var x = resource.Value.split('{').length - 1;
    var y = resource.Value.split('}').length - 1;

    if ((x + y) % 2 === 1) {
        alert("Incorrect Message format");
        return;
    }

  }
};

Example: If you edit the first value ({JobRole} for {Organisation}) and remove the trailing curly brace ({JobRole} for {Organisation)
The alert("Incorrect Message format"); never shows because it gets the original value - {JobRole} for {Organisation} and not {JobRole} for {Organisation
If I move the validation logic to the onaftersave event I get the correct value and validation fires, but it will show/save the incorrect value, which I do not want. So how can I get around this? Any help appreciated.

*

*Not sure if I could use defer, promise to resolve this - but not sure if even possible with Angular Xeditable?

A: Here is my plunker with it working: Plunker
Basically, I changed your html to this:
{{ res.Value || 'empty' }}

I'm passing $data instead of the 'res'. $data is the value of the object property you are actually changing.
And in the controller, your validation function. 'Resource' is now the $data which contains the value of your property you are trying to change. So you check it, and you return an error message. If you don't want a error message to show up next to the field return "";
vm.formatCheck = function (resource) {

        console.log(resource);

        if (resource.indexOf('{') > -1 || resource.indexOf('}') > -1) {

            var x = resource.split('{').length - 1;
            var y = resource.split('}').length - 1;

            if ((x + y) % 2 === 1) {
                alert("Incorrect Message format");
                return "Incorrect Message format";
            }

        }
    };


text:
Q: How can I modify the GLCameraRipple example to process on a background thread? I'm trying to modify the GLCameraRipple sample application from Apple to process video frames on a background thread. In this example, it handles each frame on the main thread using the following code:
// Set dispatch to be on the main thread so OpenGL can do things with the data
[dataOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];

If I change this code to process in a background thread:
dispatch_queue_t videoQueue = dispatch_queue_create("com.test.queue", NULL);
[dataOutput setSampleBufferDelegate:self queue:videoQueue];

then program crashes.
When I try to create a second EAGLContext with sharing, as specified in Apple's documentation, then I only see a green or black screen.
How can I modify this sample application to run on a background thread?

A: This was actually fairly interesting, after I tinkered with the sample. The problem here is with the CVOpenGLESTextureCacheCreateTextureFromImage() function. If you look at the console when you get the green texture, you'll see something like the following being logged:

Error at CVOpenGLESTextureCacheCreateTextureFromImage -6661

-6661, according to the headers (the only place I could find documentation on these new functions currently), is a kCVReturnInvalidArgument error. Something's obviously wrong with one of the arguments to this function.
It turns out that it is the CVImageBufferRef that is the problem here. It looks like this is being deallocated or otherwise changed while the block that handles this texture cache update is happening.
I tried a few ways of solving this, and ended up using a dispatch queue and dispatch semaphore like I describe in this answer, having the delegate still call back on the main thread, and within the delegate do something like the following:
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    if (dispatch_semaphore_wait(frameRenderingSemaphore, DISPATCH_TIME_NOW) != 0)
    {
        return;
    }

    CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CVPixelBufferLockBaseAddress(pixelBuffer, 0);
    CFRetain(pixelBuffer);

    dispatch_async(openGLESContextQueue, ^{
        [EAGLContext setCurrentContext:_context];

        // Rest of your processing

        CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
        CFRelease(pixelBuffer);

        dispatch_semaphore_signal(frameRenderingSemaphore);
    });
}

By creating the CVImageBufferRef on the main thread, locking the bytes it points to, and retaining it, then handing it off to the asynchronous block, that seems to fix this error. A full project that shows this modification can be downloaded from here.
I should say one thing here: this doesn't appear to gain you anything. If you look at the way that the GLCameraRipple sample is set up, the heaviest operation in the application, the calculation of the ripple effect, is already dispatched to a background queue. This is also using the new fast upload path for providing camera data to OpenGL ES, so that's not a bottleneck here when run on the main thread.
In my Instruments profiling on a dual-core iPhone 4S, I see no significant difference in rendering speed or CPU usage between the stock version of this sample application and my modified one that runs the frame upload on a background queue. Still, it was an interesting problem to diagnose.


text:
Q: jQuery - List Flickr photos in one column using
*
* tags I have the following code...
<!DOCTYPE html>

    <title>Flickr</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"/>

        <form method="get" name="photoform" id="photoform">
            Keyword: <input type="text" name="keyword" id="keyword" value="" /><input type="submit" name="findphoto" id="findphoto" value="Find" />

        </form>

I want to display the Flickr API photos into one column using the

tags. Refer to the $.getJSON in the code for an example. But when I run it, it doesn't spit out the photos in one column. It spits them out in 5 columns. Any suggestions?

A: I'm looking at  a part of your code here:
$('#photolist').append('

');

This suggests that the images will be shown one on top of the other. If that is the case and you are not happy with that, it should suggest that you want the images next to each other in one line.
if that is true you should change the line above to the one below:
$('#photolist').append('

');

also add the following in the stylesheet declarations:
ul#photolist li{
width: 20%;
display: inline-block;
}


text:
Q: 3d Plot of (x,y,z) that looks like histogram3d I'd like to create a 3d "bar plot" of data with three coordinates (xn,yn,zn). The Histogram3d function in Mathematica 11 looks great, but I just want to plot triplets, I don't want to count the number of ocurrances of anything. Is there some way to plot various heights associated with points in the (x,y) plane using this nice graphical style?
[(x1,y1,z1),
(x2,y2,z2),
...
(xn,yn,zn)]

A: If your data is regularly spaced you can use WeightedData with Histogram3D.  If not you could create your own plot with Cuboid and Graphics3D.
First I'll create some regularly spaced triplet $\{x,y,z\}$ data in dat.
SeedRandom[12345];
With[{hl = HistogramList[RandomVariate[NormalDistribution[0, 1], {500, 2}]]},
 dat = MapThread[Append,
    {Flatten[Outer[List, Sequence @@ hl[[1, All, 2 ;;]]], 1],
     Flatten@hl[[2]]}];
 ]
dat // Short

{{-3,-(5/2),0},{-3,-2,0},{-3,-(3/2),0},{-3,-1,0},{-3,-(1/2),0},{-3,0,1},
 <<156>>,
 {7/2,1/2,1},{7/2,1,0},{7/2,3/2,0},{7/2,2,0},{7/2,5/2,0},{7/2,3,0}}

Regularly Spaced Data
With WeightedData each $\{x,y\}$ can be given a weight of $z$.  Histogram3D understands this information. All that is needed is to specify bins that match the spacing of the data.  In dat both $x$ and $y$ are spaced by $\frac{1}{2}$.
wdat = WeightedData[dat[[All, ;; -2]], dat[[All, -1]]];
Histogram3D[wdat, {{1/2}, {1/2}}]

Triplets in General
For triplets in general you can create your own histogram-like plot using Cuboid and Graphics3D.  Here a cuboid is created for each set by taking $\{x,y,0\}$ as the lower corner and  $\{x+\Delta,y+\Delta,z\}$ as the upper corner.  Deltas, colour, lighting, and the rest I leave to you.
Graphics3D[{Orange, Cuboid[{#1, #2, 0}, {#1 + .2, #2 + .2, #3}] & @@@ dat},
 BoxRatios -> {1, 1, 1}, Axes -> True]

Hope this helps.


text:
Q: Checksum of file in vbscript I have the following command
"C:\Program Files\File Checksum Integrity Verifier\fciv.exe" -sha1 "D:\new.txt"
How to run this command from vbscript? Can anybody help me?

A: VBScript comes with a couple of different ways to execute command lines, both of which are on the WshShell object (WScript.Shell)
Using WshShell.Exec
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec("""C:\Program Files\File Checksum Integrity Verifier\fciv.exe"" -sha1 ""D:\new.txt""")

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

WScript.Echo oExec.Status

Using WshShell.Run
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")

WshShell.Run """C:\Program Files\File Checksum Integrity Verifier\fciv.exe"" -sha1 ""D:\new.txt""", 1, true


text:
Q: Self cache-proxying all outcoming http/https request Is there a way to setup squid (or another caching proxies) to cache any http/https request from my own computer?
i will use it to record all request and get the downloaded files from software that does not show the url's or redownload packages that already been downloaded (such as Yaourt --> this package always redownload packages that already been downloaded, it's really takes too much bandwidth for big packages)

A: Caching https is hard to set up, sorry.  You need to create a local CA certficate, and configure the client programs to accept it.  I don't know what proxy software you'd have to use for it.
Squid isn't great for caching large downloads.  It doesn't support partial instances, i.e. resuming interrupted downloads.
Polipo supports partial instances, and I love it as a personal proxy.  It has been slightly unreliable at times.  In particular it may suffer if you have an old dnsmasq implementation on your home router, which gets confused by simultaneous DNS queries for ipv4 and ipv6.  It does not support https interception/caching.
Hopefully your client software respects the standand environment variables like $http_proxy.  If your distro supports it, you can set e.g. http_proxy=http://localhost:8123/ in /etc/environment, and it will be set at login time by pam_env. (debian suffered from a bug at some recent point which disabled this, but I think it's working on my current debian unstable machine).


text:
Q: What is the shortest most readable way to print the n'th line of a file? Its about Unix and Linux.
Yes, there are many solutions to that, e.g. see http://mywiki.wooledge.org/BashFAQ/011. Some of them are fast as hell (not reading the whole file) and some are slow but short and much more readable. I am interested in a solution that works on small files < 1MB, that is easy to remember and easy readable and should finish below 1sec. Of course I could write a script or shell alias, but when I come to new installed computers I have to reestablish my environment first, so I prefer a solution that works with most Unix and Linux Distris out of the box, or at least after installing the desired tool via package management. Can someone beat this?:
 awk NR==42 file

A: As long as there is a head and tail command
This will print the 12th line of file abc. Keep tail -n 1, and just change 12 to whatever line number you want to print.
$ head -n 12 abc | tail -n 1
If you're willing to install the a tool via package management, then you should be willing to use a script you write, and also, i'd guess that maybe all your linux and unix distros have head and tail commands. but if not then install them, or install awk or perl, of course whatever you use will work the same on any system, as long as the system has the tool, be it head and tail, awk or perl.

A: The awk and perl solutions both have the disadvantage that they continue reading after printing the Nth line.  The yes command, which prints infinitely many lines, can be used to test this.
A short solution that shares this problem is:
 sed -n 42p file

This one quits after printing the line:
sed -n '42{p;q}' file

A: I don't think I can beat your AWK example for brevity or readability, but here is a Perl example
  perl -ne 'print if $. == 42' file

A: use sed:
sed -n 42p file

It is easy to type (no uppercase letters, no need to hit "Shitft") and is very short.

A: You can use the sed.  In the following command, the -n option disables printing each line, so only explicit printing (p commands) is carried out. 12 matches the 12th line and p issues a print.
sed -n '12 p'


text:
Q: Find the length of $AD$ in the parallelogram. Problem: In the parallelogram $ABCD, \quad \measuredangle DBC=45^{\text{o}}, \quad\measuredangle BDC=30^{\text{o}}$ and $|AB|=5\sqrt{2}$. Find the length of $AD.$
I drew this:

Is this interpretation correct? I know that $\measuredangle BAD=\measuredangle BCD=105^{\text{o}},$ using the law of cosines I get
$$|BD|^2=x^2+(5\sqrt{2})^2-10x\sqrt{2}\cos{105^{\text{o}}}.$$
I also know that $\measuredangle ABD=30^{\text{o}},$ so now I can apply law of cosines again on $\triangle ABD$ with sides $BD, \quad 5\sqrt{2}$ and the angle between the two sides $30^{\text{o}}.$ So:
$$x^2=|BD|^2+(5\sqrt{2})^2-10|BD|\sqrt{2}\cos{30^{\text{o}}},$$
but this is a polynomial of the 4th degree with only complex solutions. I'm probably making it a lot harder than it is. Any tips?

A: $$\begin{array}{rcl}
\dfrac{AD}{\sin \angle ABD} &=& \dfrac{AB}{\sin \angle ADB} \\
\dfrac{x}{\sin 30^\circ} &=& \dfrac{5\sqrt2}{\sin 45^\circ} \\
2x &=& 10 \\
x &=& 5 \\
\end{array}$$

A: Note that $AD=BC$ and $AB=CD$
$CD/\text{sin}45^\circ=x/\text{sin}30^\circ$

A: Let $CE$ be an altitude of $\Delta DEC$.
Thus, since $\measuredangle EDC=30^{\circ}$, we obtain
$$EC=\frac{1}{2}\cdot5\sqrt2=\frac{5}{\sqrt2}$$ and since $\measuredangle DBC=45^{\circ}$, we obtain:
$$BC=EC\cdot\sqrt2=5.$$
Done!


text:
Q: A word for a place where you store antiques I'm writing a song and I'm trying to come up with a word for a place, a room, a shop, or even a piece of furniture where people store old things or collectible objects. The idea is to imply that something is old or is more like a collection piece now by saying it is getting saved there (in the song).

A: A hutch or a curio cabinet would be used to store curiosities within someone's house or apartment. If you're speaking of china specifically, a china cabinet would work.
A shop/place where used or old collectible items are sold could be an antique store, vintage shop, thrift store, flea market, swap meet (regional), estate sale (implies that a collector is going to the deceased's house rather than a store), or even a garage sale depending on what you're going for.

A: It's called a lumber room.  The term is common in English literature, since the writers of a certain period (think Jane Austen) tended to set their stories in the large houses that contained them.
There is a short story by Saki, called The Lumber Room, which can be read online in several places, including East of the Web, from which I copied the following passage, which describes what young Nicholas sees as he escapes from his severe aunt and finds his way into the forbidden space:

...objects of delight and interest claiming his instant attention; there were quaint twisted candlesticks in the shape of snakes, and a teapot fashioned like a china duck, out of whose open beak the tea was supposed to come. How dull and shapeless the nursery teapot seemed in comparison! And there was a carved sandalwood box packed tight with aromatic cotton-wool, and between the layers of cotton-wool were little brass figures, hump-necked bulls, and peacocks and goblins, delightful to see and to handle.

A: Possibly the use of one of the definitions of "gallery", "archive", or "repository" would be suitable, or use of the mere description of something as a "curio" (often used with cabinet) implying such an object's place as part of a "collection".
https://www.thefreedictionary.com/gallery
https://www.thefreedictionary.com/archive
https://www.thefreedictionary.com/repository
https://www.thefreedictionary.com/curio


text:
Q: Update ListItem in List if key already exists (ReactJS, MaterialUI) First of all want to let you know that I am using material-ui with ReactJS and Redux pattern.
Problem:
I am having a set of array which is being populated in a List with ListItem. But when array is updated the props are changed and render() method of Component is called and when data starts populating second time, it shows the error the key already exists.
Code:
 render(){
    return <div>
             <List id='requestList'>{this.bindListItems()}</List>
         </div>
    }

  bindListItems() {

        var listview = document.getElementById('requestList');

        var sortedList = this.props.requestList.sort(function (a, b) {
            return (a.requestedTime - b.requestedTime);
        });

        return sortedList.map((name, index) => {
            var listItem = <ListItem key={name.requestKey} primaryText={name.description} />;
            return listItem
        });

    }

ERROR Stacktrace
bundle.js:1099 Warning: flattenChildren(...): Encountered two children with the same key, `-KnIXRCJbOqY6rykfand`. Child keys must be unique; when two children share a key, only the first child will be used.
    in div (created by List)
    in List (created by RequestListContainer)
    in div (created by RequestListContainer)
    in div (created by RequestListContainer)
    in RequestListContainer (created by Connect(RequestListContainer))
    in Connect(RequestListContainer) (created by Home)
    in div (created by Home)
    in div (created by Home)
    in Home (created by Connect(Home))
    in Connect(Home) (created by Main)
    in Main (created by Connect(Main))
    in Connect(Main) (created by AppBarExampleIconButton)
    in MuiThemeProvider (created by AppBarExampleIconButton)
    in AppBarExampleIconButton
    in Provider

How to tackle this problem?

*

*Should i remove the previous ListItem and add new ListItem.
If Yes then how to identify the ListItem in List of material-ui.

*Should i update the existing ListItem.
If Yes then how?
Actually new to ReactJS.
Thanks

A: The problem is not with your logic. The problem is in your data. You have specified name.requestKey as key in your code. Take a look at the data that is being fed into the component, you have two different objects with the same value on that attribute.
For using the key, you need to specify something that is unique across your data.


text:
Q: Change character automatically whilst being input in c++? I'm having trouble working this out. Basically my program has a standard input, I want to modify this so if the user enters a space it automatically replaces it with a / whilst they're typing. I have no idea how i'd even go about doing this or if it is even possible so I am grateful for any help either way.

A: I believe that if you want to do manipulation of the text on the console like that, you're going to need a library such as ncurses.

A: You would need to turn off echoing of the characters typed and then echo them yourself after validating them, replacing characters as necessary.  There are different ways to do that for different operating systems (e.g. Linux vs. Windows), and even more unfortunately, that can mean taking control of the entire screen just for this simple function since the backspace/delete key would need to be handled properly (even over multiple lines if necessary).  In short, you're taking control away from the user while making yourself responsible for the common functionality that a user would expect, which makes things rather difficult because you can't know how certain terminals behave, not to mention issues with locales.  It's easier just to replace the characters yourself after the input is received or issue an error message, depending on your purpose and specific use-case.
Edit: PDCurses is cross-platform, so you might try that if you're still interested.  It's easier than coding for specific platforms.


text:
Q: Finding the class rank of a student from results of whole class I haven't learnt how to do this in my maths classes since we're starting probability in a couple months but I need to determine my rank within my cohort for chemistry.
The cohort consists of ~50 students and the highest mark was 93/100. The top 25% of the cohort got 77+/100 and 50% was 69+/100, if I got 83/100, how would I determine what rank I could possibly be among the 50 students?
(Again, sorry I can't attempt this myself since I haven't learnt anything to do with probability at all yet).
Thanks

A: @quasi has already given you the most direct answer possible.
Here is a little additional terminology that may be useful answering
such questions in the future.
A five-number summary of a dataset consists of the minimum, lower quartile $Q_1$,
median (third quartile, sometimes denoted $H$ or $Q_2$), upper quartile $X_3$, and maximum.
Roughly speaking, 25% of the observations in the sample lie below $Q_1$,
50% below $Q_2$ and 75% below $Q_3.$ With 'about $n=50$' students it may not
be possible to find three values that partition the sorted data into
four subsets of size precisely $n/4$. Also, tied observations can cause
difficulty in finding the quartiles.
Each textbook and statistical software
package has its own rules for making the necessary compromises. However,
the differences among these rules become relatively unimportant for large $n$.
Below is how R statistical software finds the five number summary (plus the
sample mean) for a contrived dataset x of size $n = 50$ that roughly matches your
specifications. (Numbers in brackets are the indexes of the first observation
on each line.)
x
 [1] 13 13 17 21 21 22 24 25 30 31 35 38 40 41 44 47 47 53 55 58 60 60 62 66 69
[26] 69 70 70 72 73 73 74 74 75 75 75 76 77 77 80 83 89 89 90 91 92 92 93 94 98
length(x)
## 50
summary(x)
##   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
##  13.00   40.25   69.00   60.26   76.75   98.00

You can google such phrases as five number summary, quantile, and
descriptive statistics to learn more. (But the current Wikipedia draft on
'five number summary' gives computer code without output; perhaps it is under construction.)


text:
Q: Confusion as to in which site to post question? I think the first time users feel a bit confused as to in which stack website should they post a question? I personally feel that while a person attempts to post a question (s)he should be made aware of the other stack websites which might be relevant to the question

A: There are three good ways to find out where your question belongs.
The first and foremost way is to put research effort into your own question. In doing so, you may find that your problem becomes more well-defined, and the place to ask it becomes clearer:

*

*An internet search for your question may yield a solution. As a bonus, that solution may be on an SE site (which Google, at least, places a lot of weight on), thus giving you an idea of where to ask similar questions in the future.

*An internet search for some of your problem keywords plus "stack exchange" generally yields reasonable results, without requiring you to know what sites are actually available before hand.

*A site listing is always available at https://stackexchange.com/sites (by clicking "All Sites" at the top of the main SE site).

The second way is the current system, as mentioned in ChrisF's answer, which is primarily driven by human intelligence rather than machine intelligence (re: your comment on said answer):

*

*Readers who know where it belongs can vote or flag to migrate.

*Often a reader will leave a comment with a suggested site.

This system works well.
The third way, which can often be used in conjunction with the above, is to ask where to ask your specific question on the meta of a related site, or even here on MSE, or in one of the chat rooms (click "chat" in footer or see chat links on right). You will almost certainly receive good suggestions.

A: How would you achieve this other than by the current method of people reading the question and either voting to migrate to one of the current migration targets, flagging for a moderator to migrate or having a conversation with the OP in comments?
There are links to other sites in the footer of every page and some sites' help pages reference other sites that cover related topics.
I think these are sufficient.


text:
Q: Dynamically include a blade template depending on an input value I'm new at Laravel and PHP and I'm stuck with this. If there is any other way to do this, either with blade statements or anything else I would appreciate it, since I'd like to avoid to use javascript as much as possible, but I guess that I have no choice if I need to use onChange.
I have a blade template with some inputs that I'd like replicate depending on another input. For example: if I introduce the number 4, I should get 4 times the same set of inputs.
Inputs (inputs.blade.php)

    Name
    <input id="name" name="name" type="text" class="form-control" tabindex="1">

<legend class="col-form-label col-sm-2 pt-0 mt-3">Tags</legend>
@foreach($images as $image)

    <input class="form-check-input" type="radio" name="image" id="{{$image->name}}" value="{{$image->name}}:{{$image->version}}">
    name}}">
        {{$image->name}}:{{$image->version}}

@endforeach

  <input class="form-check-input" type="checkbox" role="switch" name="setFolder" id="setFolder">
  Use a file instead

    File directory
    <input id="dir" name="dir" type="text" class="form-control" tabindex="2">

Where I want to include and replicate them (index.blade.php)
I would like to write something like this, but since I need to use the onChange (at least using the knowledge I possess at the moment) I guess this is completely wrong:
@extends('layouts.app')

@section('content')

Create

    <form action="/activity" method="POST">
        @csrf

        <legend class="col-form-label col-sm-2 pt-0">C versions</legend>
        @foreach($versions as $v)

            <input class="form-check-input" type="radio" name="version" id="{{$v->version}}" value="{{$v->version}}:{{$v->engine}}">
            version}}">
                {{$v->version}}:{{$v->engine}}

        @endforeach

            Number of services
            <input type="number" value="2" min="2" max="999" id="nServices" name="nServices">
            @php
                $nServices = Request::input('nServices');
            @endphp

            @for ($i = 0; $i < $nServices; $i++)
                @include('inputs')
            @endfor

So instead I did this and added javascript but I can't use blade inside it (again, this is as far as my knowledge reaches)
 Number of services
            <input type="number" value="2" min="2" max="999" id="nServices" name="nServices">

scripts.js
document.getElementById('nServices').onchange = function () {
    var html = @include('inputs');
    for(var i = 0; i < this.value; i++){
       document.getElementById('replace').append(html);
    }

}

Thanks for the help


text:
Q: Embed variables in very simple javascript function Hi for some reason I can't get this function to work.
function go(type)
{
    location=document.category.example.options[document.category.example.selectedIndex].value
}

All i want to do is embed the type variable, the go function becomes undefined whenever I try to do something like
location=document.'+type+'.example.options[document.'+type+'.example.selectedIndex].value

What am I doing wrong?

A: You can use document[type].example

A: instead of document.'+type+'.example.options[document.'+type+'.example.selectedIndex].value you should write:
document[type].example.options[document[type].example.selectedIndex].value

A: You need to learn more about JavaScript syntax before you do stuff like that.
Here is a solution to your problem:
function go(type)
{
    location=document[type].example.options[document[type].example.selectedIndex].value;
}

go('category');

It takes advantage of the fact that these two are equivalent:
a.b === a['b']

But obviously in the second part, b can be replaced dynamically since it is a string.


text:
Q: Distance variation in Grid feature using MapInfo Professional I'm using MapInfo Professional version 10.5 for Digitization.
We can create Grids from "Create Grid" feature of MapInfo.
From Grid Maker(version 1.4) window i'm selecting
Object Types: Closed Regions
Object Styles: Regions
Extents: (Automatically loads value), unselected Round Extents checkbox.
Spacing Between lines: eg: 2236.06 selected meter option.
Smoothness: 0
then press ok for getting Grid.
I can view Grids on the map.
But, When i'm trying to measure length of each grid using measure tool(Ruler) in mapinfo, it is showing zig zag values. eg: one grid length will be 2240 and other will be 2230 like that..
How can i solve this problem ..
Please share your ideas here ..
Thank you..
Ramesh T.R.

A: This may be due to the way that MapInfo stores coordinates.  If the bounds of your TAB file are very large (which I'm assuming they are as your grid size is a couple of kilometers) then the below may be the root cause.

MapInfo slices the area you tell it you're interested in (the bounds of the file) into a grid and then stores coordinates as integers (see here: http://www.mapsbydesign.co.uk/pdfs/boundsclause.pdf for more detail).  The means that the bigger the area of interest, the less accurate your coordinates are.  If your grid size ended up being 10 meters, then you'd expect to see something like what you describe above, where the real-world coordinates end up getting snapped to the closest grid point.