text:
Q: How to declare a Hierachic grid based on List item in parent properties? Given an object Movie with a property Actors that is a list of Actor.
How to display Actors in a colapsible hierachical grid?
Like:

RadGrid Declaration:
<telerik:RadGrid ID="RadGrid1" runat="server">
        <MasterTableView PageSize="10" DataKeyNames="Actors" GroupsDefaultExpanded="False">
            <DetailTables>
                <telerik:GridTableView >

                </telerik:GridTableView>
            </DetailTables>
        </MasterTableView>
</telerik:RadGrid>

In Code Behind:
RadGrid1.DataSource = ServiceLike.GetMovies();

public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Genres { get; set; }
    public Actor[] Actors { get; set; }
}
public class Actor
{
    public string Name { get; set; }
}

public static class ServiceLike
{

    public static Movie[] GetMovies()
    {
        return new[]{
            new Movie{
                Id =1,
                Genres ="",
                Title ="First",
                Actors= new []{
                    new Actor{ Name= "Actor1" },
                }
            },
            new Movie{Id=2, Genres="", Title="Second",
                Actors= new []{
                    new Actor{ Name= "Foo" },
                    new Actor{ Name= "Bar" },
                }
            },
            new Movie{Id=3, Genres="", Title="Third",
                Actors= new []{
                    new Actor{ Name= "Joe" },
                    new Actor{ Name= "Monika" },
                    new Actor{ Name= "Ross" },
                }
            },
        };
    }
}

The aim here is to limit the call to the GetMovies() Method in the DetailTable.

This is a simplification of my issue:
Displaying a list as a sub grid without spamming the service that provides the object containning this list. Movie and Actor are exemple class not related to the real data. The grid declaration is a clean try, As telerik can be a lot of try and fail I provided a clean try than any of the numerous try as they can be missleading.

A: DataKeyNames can only contain a Bindable Property Types. List, Array, or such will not work.
Also, the DataKeyNames are meant to provide with a value that can be used to identify the object. In this case, the Id of the Movie would be the best to use:
<telerik:RadGrid ID="RadGrid1" runat="server"
    OnNeedDataSource="RadGrid1_NeedDataSource"
    OnDetailTableDataBind="RadGrid1_DetailTableDataBind">
    <MasterTableView PageSize="10" DataKeyNames="Id" GroupsDefaultExpanded="False">
        <DetailTables>
            <telerik:GridTableView>
            </telerik:GridTableView>
        </DetailTables>
    </MasterTableView>
</telerik:RadGrid>

You could, of course use the id of a child item as the Unique identifier if it had a bindable property.
DataKeyNames="Actor.Id"

In case its an array, you'd need to access the item by it's array index. Even use multiple Actor's ID to act as Identifier for a row. That could help find the Movie by actors id.
DataKeyNames="Actors[0].Id, Actors[1].Id, Actors[3].Id"

This, however is not practical and the application would error out if it tries to access the array item by an index that does not exist.
To avoid any unexpected behavior caused by binding, use Advanced Data-binding (Using NeedDataSource Event) to bind data to RadGrid. Perhaps, you are already using it. I mention it in case.
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
    if (!e.IsFromDetailTable) RadGrid1.DataSource = ServiceLike.GetMovies();
}

For binding data to the child tables programmatically, you may use the DetailTableDataBind event. (Hierarchical data-binding using DetailTableDataBind event). This will fire as soon as you expand a Grid row, and in the event arguments, you'll have access to the Child table object.
Use that to traverse up the Object tree and access its parents. (Accessing Cells and Rows)
protected void RadGrid1_DetailTableDataBind(object sender, Telerik.Web.UI.GridDetailTableDataBindEventArgs e)
{
    GridTableView tableView = e.DetailTableView;
    GridNestedViewItem nestedViewItem = tableView.NamingContainer as GridNestedViewItem;
    GridDataItem parentItem = nestedViewItem.ParentItem;

    e.DetailTableView.DataSource = Array.Find(ServiceLike.GetMovies(), item => item.Id == (int)parentItem.GetDataKeyValue("Id")).Actors;
}

If all done correctly, the results would look like this:


text:
Q: Boxplot with ggplot2 in R - returns by month I have computed monthly returns from a price series. I then build a dataframe as follows:
    y.ret_1981    y.ret_1982    y.ret_1983   y.ret_1984   y.ret_1985
1   0.0001015229  0.0030780203 -0.0052233836  0.017128325 -0.002427308
2   0.0005678989  0.0009249838 -0.0023294622 -0.030531971  0.001831160
3  -0.0019040392 -0.0021614791  0.0022451252 -0.003345983  0.005773503
4  -0.0006015118  0.0010695681  0.0052680258  0.008592513  0.009867972
5   0.0052736054 -0.0003181347 -0.0008505673 -0.000623061 -0.012225140
6   0.0014266119 -0.0101045071 -0.0003073150 -0.016084505 -0.005883687
7  -0.0069002733 -0.0078170620  0.0070058676 -0.007870294 -0.010265335
8  -0.0041963258  0.0039905142  0.0134996961 -0.002149331 -0.007860940
9   0.0020778541 -0.0038834826  0.0052289589  0.007271409 -0.005320848
10  0.0030956487 -0.0005027686 -0.0021452210  0.002502301 -0.001890657
11 -0.0032375542  0.0063916686  0.0009331531  0.004679741  0.004338580
12  0.0014882164  0.0039578527  0.0136663415  0.000000000  0.003807668

... where columns are the monthly returns for the years 1981 to 1985 and the rows 1 to 12 are the months of the year.
I would like to plot a a boxplot similar to the one below:

So what can I go? And I would like my graph to read the months of the years instead of integer 1 to 12.
Thank you.

A: First, add new column month to your original data frame containing month.name (built-in constant in R) and use it as factor. It is import to set also levels= inside the factor() to ensure that months are arranged in chronological order not the alphabetical.
Then melt this data frame from wide format to long format. In ggplot() use month as x values and value as y.
df$month<-factor(month.name,levels=month.name)
library(reshape2)
df.long<-melt(df,id.vars="month")
ggplot(df.long,aes(month,value))+geom_boxplot()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Visual Studio debugger for SharePoint AutoHosted App I'm using VS2013 for developing SharePoint Hosted App against a 365 development site.
The VS debugger tool doesn't hit anymore my breakpoints.
It used to the day before.
I have made many tests,

*

*On the "Hello World" sample (with a breakpoint on a simple alert()).

*On two different desktops.

Can someone help me to solve that question ?
Thanks

A: Sounds like you accidentally changed the code in such a way that its not running to the line you have your break point at. If you edit the post with your code I can look at it for you.


text:
Q: Trouble passing clicked value (PHP) to ajax function I'm having trouble passing the value of the clicked element into an ajax function. Below is the ajax function.
// Get values from all three dropdown menus
        var state = $('#states').val();
        var status = $('#status').val();
        var services = $('#services').val();
// Get value from clicked element
        var pagedtest = pagednum;

function do_ajax() {
            $.ajax({
                url: ajaxurl,
                data: {
                    'action' : 'json_info2',
                    'state' : state,
                    'status' : status,
                    'services' : services,
                    'pagedtest' : pagedtest
                },
                success:function(moredata) {
                    // This outputs the result of the ajax request
                    $('#project-list').html( moredata );
                    $('#project-list').fadeIn();
                }/*,
                error: function(errorThrown){
                    var errorMsg = "No results match your criteria";
                    $('#project-list').html(errorMsg);
                }*/
            }); // end of ajax call
        } // end of function do_ajax

Then let's say I have a series of  tags that are each assigned a title dynamically, like this:
90
87
102

And I'm trying to run the following code in my php page in order to pick up the clicked value to pass to ajax.
$(".page-link").click(function() {
      var pagednum = $(".page-link").val($(this).attr('title'));
      return false;
});

When I click one of the links, nothing happens. Where am I going wrong?
How can I pass the value of the title attribute, of the clicked tag, when the ajax function runs?

A: Try this:
 $(".page-link").click(function() {
       var pagednum = $(this).attr('title');
 });

Also, ensure your anchor tags have href attributes.

A: I am not exactly sure what the relation between those two sections of javascript is, but it seems you are trying to use pagednum in the first section.
However, the pagednum you have defined in your click hander looks like this:
$(".page-link").click(function() {
      var pagednum = $(".page-link").val($(this).attr('title'));
//    ^^^ defining a variable in the local scope
      return false;
});

As you declare the variable with the var keyword inside the click handler, the scope of that variable is local to that function, the click handler.
If you need a global variable, so should declare it globally (outside of any jQuery function) like:
var pagednum;
// rest of scripts, functions, etc.

And then you use it in your click handler like:
$(".page-link").click(function() {
      pagednum = $(".page-link").val($(this).attr('title'));
//    ^^^^^^^^ use global variable
      return false;
});

For more details it would be helpful to post the complete script so we can see how everything relates.

A: This post will, hopefully, clarify what I was asking above, as well as how it was solved.
I have a php page, and on that page I have several elements that have a title attribute. I originally was using a tags for this, but I decided to switch to li's. So I have these on my php page:

Click this 87

Click this 2

Click this 34

What I wanted to do was click on of those li's, get the title value, save it as a variable, and pass it to an ajax function. I initially tried including a jquery click function (in my PHP page) to get the value. I was able to successfully get the value on click, but I was still having trouble passing it to the ajax function.
So instead, I went to my ajax function (which is located in an external js file called ajaxLoop.js). Inside that js file, I added the following:
// make pagination clickable after filter
        $( ".page-link" ).click(function() {
            var pagednumtest = $(this).attr('title');
            alert("the set number is "+pagednumtest);
            run_ajax();
        }); // end of click function for states

This was successfully grabbing the value on click, as the alert was able to output it, but I still couldn't access var pagednumtest in the actual ajax function. In fact, the ajax function wouldn't run because it didn't recognize the variable that I was trying to pass. So I modified the above function by passing the variable to the ajax function like this:
I changed
run_ajax();

to this
run_ajax(pagednumtest);

So the entire function then looked like this:
// make pagination clickable after filter
        $( ".page-link" ).click(function() {
            var pagednumtest = $(this).attr('title');
            alert("the set number is "+pagednumtest);
            // variable is passed to the ajax function
            run_ajax(pagednumtest);
        }); // end of click function for states

The ajax function then accepted the variable value, and I was able to use it.
function run_ajax(mynumber) {
// Get values from all three dropdown menus
        var state = $('#states').val();
        var markets = $('#markets').val();
        var services = $('#services').val();
        var mytestnumber = mynumber;
            $.ajax({
                url: ajaxurl,
                data: {
                    'action' : 'json_info2',
                    // ignore state, markets, and services as they are dropdown menu values
                    'state' : state,
                    'status' : markets,
                    'services' : services,
                    // here I was able to get and use the clicked value
                    'testnum' : mytestnumber
                },
                success:function(moredata) {
                    // This outputs the result of the ajax request
                    $('#project-list').html( moredata );
                    $('#project-list').fadeIn();
                }/*,
                error: function(errorThrown){
                    var errorMsg = "No results match your criteria";
                    $('#project-list').html(errorMsg);
                }*/
            }); // end of ajax call
        } // end of function do_ajax


text:
Q: Ranking a list of numbers that may have repeating digits I am looking for a way to rank the very first change in a sequence of numbers within a list that may contain duplicates... example...
rec#  number
1     328
2     32C
3     32C
4     328
5     328

What I am looking for is to find the first 328 as #1... then the first 32C as #2... then the next occurring 328 as #3... and so on... the end result would look something like this
rec#  Number  rank
1     328     1
2     32C     2
4     328     3

I figured out a way to do it in Excel then bring it back into SQL...and was wondering if there is something like it in SQL...   I am using SQL2000 so no ranking or partition available...
Thanks

A: If you make the assumption that rec# is consecutive and unbroken then you can do something like the following. Let me explain:
SELECT t1.[rec#] AS rec1,
t2.[rec#] AS rec2,
t1.Number AS Num1,
t2.Number AS Num2,
CASE WHEN t2.Number IS NULL THEN 1
     WHEN t1.Number = t2.Number THEN 1
     ELSE 0
END AS MATCH
FROM Test t1
LEFT JOIN Test t2 ON t1.[rec#] = t2.[rec#] + 1

the left join with the +1 is the key bit allowing you to join the table back on itself but shifted one row. We can then compare each row with the previous to see if its matched.
Gives you:
t1.rec#  t1.number  t2.rec#  t2.number  Match
1        328        Null     Null       1
2        32C        1        328        0
3        32C        2        32C        1
4        328        3        32C        0
5        328        4        328        1

so...
You can then say
SELECT
   CASE
      WHEN x.rec2 IS NULL THEN x.rec1
      ELSE x.rec2
   END AS [rec#],
   x.Num1 AS Number,
IDENTITY(INT, 1,1) AS Rank
INTO #Ranks

FROM (
    SELECT t1.[rec#] AS rec1,
    t2.[rec#] AS rec2,
    t1.Number AS Num1,
    t2.Number AS Num2,
    CASE WHEN t2.Number IS NULL THEN 1
         WHEN t1.Number = t2.Number THEN 1
         ELSE 0
    END AS MATCH
    FROM Test t1
    LEFT JOIN Test t2 ON t1.[rec#] = t2.[rec#] + 1
) x
WHERE x.MATCH = 1

SELECT * FROM #Ranks

I've used a Temporary table as a cheap way to add on the Rank value. There are other ways of doing this but at 01:05 that's the best you are going to get.
I've done a SQL Fiddle (in 2008 but without any 2008 features so should work in 2000) here: Enjoy


text:
Q: For SAP GUI script, do you know what is the script for SAP job has been created? I have created a SAP GUI script to script the transaction code F110.
Is there a way or script to determine the SAP job has been created?
Meaning that once the job is created, my SAP macro excel able to move to next line and continue for the next command.
Can anyone help? Thanks in ton!


text:
Q: Is there such a thing as a circuit that outputs 1 if the input is high-impedance, and 0 otherwise? I am trying to design a circuit that outputs a logical 1 if the input is high-impedance, and a 0 otherwise.
Any idea how I might implement this?  I would prefer to use off-the-shelf parts (no programming).
Truth table:
I|O
---
X|1
0|0
1|0

I was thinking something along the lines of a pull up resistor with an NPN transistor.  Thoughts?

A: A simple window comparator will do what you want.
The input is tied to midvoltage by the two 1Mohm resistors.  The references are set at 1/3 and 2/3rds of the supply voltage.  LM339 is open-collector output, so can be OR'ed together to get the desired truth table.

Google for "window comparator" to get more detail about this circuit.
Please notice that this circuit will not detect a low-impedance connection to half the supply voltage, only low impedances to high or low levels.


text:
Q: Configure MSSQL 2008 to use kerberos authentication I would like to set my current mssql db (2008 and 2012) to authenticate using a linux kerberos server that I have in my environment .
The windows station is in a workgroup and I would like to avoid having to setup a domain controller and active directory .
How can I accomplish that ? what do I need to configure on the windows side and the kerberos server side (assuming it's configured already to work with other dbs running on linux based OSes) ?

A: Yes this is manageable. All you need is a trusted connection to an odbc connector and you can read about that here: http://technet.microsoft.com/en-us/library/hh568450.aspx

A: I suspect that you're going to have to "trick" windows into natively authenticating against the linux kerberos server, which might be more effort than you're looking for.  Things I found include:

*

*This O'Reilly article

*PGina is old and doesn't include Kerberos out of the box, but you
could write a plugin (yikes).

*Use SAMBA and FreeIPA to create a trust with your linux kerberos server
Or, you could use SQL Server authentication instead.


text:
Q: AJAX innerHTML PHP array and location not working? I am making a code where all comments in a database are echoed out with the help of AJAX. Right now I have two problems.

*

*Location is not working. Here is my code for opening the xmlHttpRequest.
xmlHttp.open("GET", "location.href.split('/').pop();", true);

I get the "Not Found" error when I check if the status == 200. But when I use a filename I know is in the directory it works. I must use something like the above because I have a few set variables in the url which makes unique pages.

*The comments are not echoing out. Here is my
PHP
<?php

$showcomment=mysql_query("SELECT * FROM `photosite`.`comments` WHERE `photo_id`='$photo_id'");
echo '<response>';
while($allcomments=mysql_fetch_array($showcomment)){

    echo '

';
}
echo '</response>';
?>

Javascript
function process(){
    if(xmlHttp){
        try{
            xmlHttp.open("GET", "location.href.split('/').pop();", true);
            xmlHttp.onreadystatechange = handleServerResponse;
            xmlHttp.send(null);
        }catch(e){
            alert( e.toString() );
        }
    }
}

function handleServerResponse(){
        comment = document.getElementById('comment');
        if(xmlHttp.readyState==4){
            if(xmlHttp.status==200){
                try {
                    comment.innerHTML += "'.$allcomments['firstname'].' '.$allcomments['surname'].' '.$allcomments['comment'].'
";
                }catch(e){
                    alert( e.toString() );
        } else {
            alert(xmlHttp.statusText );
            }
        }
    }
}

On the innerHTML all I did was echo out what I had echoed without AJAX. It showed up on the page but as what is is. How do I get it to recognize they are PHP variables? Once they are echoed out on the PHP page shouldn't they become variables?

A: Remove the quotes around your JavaScript expression, otherwise you just get a string. That said, are you trying to send an AJAX requiest to the current page? In that case, just location.href would work.
This is probable the source of all your problems, actually.


text:
Q: ubuntu 20.04 brightness reset to max on startup I execute the following command to bring down the brightness
xrandr --output eDP-1-1 --brightness 0.60

But the brightness jumps back to max level whenever I restart my laptop. How do I set the default brightness to a certain value?


text:
Q: Connecting using SnowSQL denied 403 error I am trying to configure JDBC but kept getting the same error I am getting using snowsql:
250001 (08001): Failed to connect to DB. Verify the account name is correct: JG3409.canada-central.azure.snowflakecomputing.com:443. 000403: 403: HTTP 403: Forbidden
If the error message is unclear, enable logging using -o log_level=DEBUG and see the log to find out the cause. Contact support for further help.
Goodbye!

I have configured the config file, and I have double checked the account, company, region, reset password to only use alphanumeric.
I have used both forms of the URL
The only possibility is that I am using a trial account, but I can't imagine that this would limit external non-browser connections?
I use a simple user/password, I have whitelisted my IP and I don't have a problem with a proxy or a firewall.  I can successfully connect using a browser.. using:
https://app.snowflake.com/canada-central.azure/jg63409
Important contents of the config file:
[connections]
accountname=JG3409
#accountname=uegxydq-pz20606
region=canada-central.azure
username=ASHSNOWFLAKE

any ideas?

A: Your account is not JG3409 but JG63409 based on this link:
https://app.snowflake.com/canada-central.azure/jg63409
Try in your browser:
https://jg63409.canada-central.azure.snowflakecomputing.com

A: I found out using snowcd that my computer could not connect via my home router.
When I used my personal hotspot on my (5G) phone, snowcd passed all the tests immediately.  The problem then arose how to adjust the network security policy to allow a CIDR block of network addresses through since my phone uses a new address every time I connect, and I can't edit the policy to allow my phone while connected via my phone (for obvious reasons)
Catch 22
123.45.0.0/16 is not accepted in the new Snowflake UI, and 0.0.0.0 doesn't work for me, but the documentation gave me a clue.. the new UI doesn't separate by commas, so I switched to the old UI and voila!
Incidentally the OLD UI uses the same URL as SnowSQL so I picked up my error in my account number there as well (although I should have seen it earlier).
Diabolical but thanks @Sergiu too!


text:
Q: How to determine which of the elements of a monoid are invertible and the inverses of these elements Let $*$ denote the binary operation on a set $\mathbb{R}^3$ of ordered triples of real numbers defined such that:
 $$(A_0,A_1,A_2) * (B_0,B_1,B_2)= (A_0B_0,A_0B_1 + A_1B_0 ,A_0B_2 + A_1B_1 + A_2B_0)$$
for all $(A_0,A_1,A_2),(B_0,B_1,B_2)\in\mathbb{R}^3$.
I have proved that the set above is a monoid and I have worked out its identity element to be $(1,0,0)$.
I am trying to determine which of its elements are invertible and that's what I just can't figure out yet. This is what I have done
$$(A_0,A_1,A_2) * (B_0,B_1,B_2)= (1,0,0)$$
where $(B_0,B_1,B_2)$ is the inverse of $(A_0,A_1,A_2)$, so:
$$(A_0B_0,A_0B_1 + A_1B_0 ,A_0B_2 + A_1B_1 + A_2B_0) = (1,0,0)$$
Then:
$$A_0B_0=1 \implies B_0=\frac{1}{A_0}$$
$$A_0B_1 + A_1B_0=0 \implies B_1 =-\frac{A_1B_0}{A_0}$$
$$A_0B_2 + A_1B_1 + A_2B_0=0 \implies B_2= \frac{-A_2B_0 -A_1B_1}{A_0}$$
I do not know what to do next. I want to find which of the elements are invertible and what their inverses are.

A: As you can see, $(A_0,A_1,A_2)$ has an inverse iff $A_0\not=0$. (Otherwise you wont be able to solve for an inverse)
Actually this monoid is ismorphic to $R[x]/<x^3>$ under multiplication

A: Suppose that $\langle a_0,a_1,a_2\rangle*\langle b_0,b_1,b_2\rangle=\langle 1,0,0\rangle$; then
$$\left\{\begin{align*}
&a_0b_0=1\\
&a_0b_1+a_1b_0=0\\
&a_0b_2+a_1b_1+a_2b_0=0\;.
\end{align*}\right.$$
This clearly implies that $a_0\ne 0$ and $b_0=\dfrac1{a_0}$, so the system becomes
$$\left\{\begin{align*}
&a_0b_1+\frac{a_1}{a_0}=0\\
&a_0b_2+a_1b_1+\frac{a_2}{a_0}=0\;.
\end{align*}\right.$$
The first of these equations implies that $b_1=-\dfrac{a_1}{a_0^2}$ and imposes no restriction on $a_1$. The second then reduces to
$$a_0b_2-\frac{a_1^2}{a_0^2}+\frac{a_2}{a_0}=0\;,$$
which can evidently be solved for $b_2$ without imposing any conditions on $a_2$. Thus, $\langle a_0,a_1,a_2\rangle$ is invertible precisely when $a_0\ne 0$, and I've computed most of the inverse above.


text:
Q: Configuring the Spartan Refactoring plug-in for Eclipse I'm using the new Spartan Refactoring plug-in (from www.spartan.org.il) for automatic refactoring of my Java code. I really like the changes the plug-in offers, however there's one change ("Rename return variable of ... to $") I'm not really comfortable with.
Is there a way to control the types of refactoring available by the plug-in?

A: Starting in version 2.3, you can configure the plug-in by going in Eclipse to Preferences->Java->Spartanization. You can change the plug-in's general settings, as well as control which refactorings will be made.
As for your question - you can simply switch off this spartanization rule by selecting "Disabled" next to the "Rename return variable to $" setting.


text:
Q: Excel Charts Hexadecimal axis values I have Hexadecimal values exported as decimal in an excel sheet (to support chart plotting).
Now, when i plot those values , in the chart's axis i get decimal values. Instead i want hexadecimal values to be shown as axis values..

How can i format the axis to show Hexadecimal values ?

A: Turn off the vertical axis labels and use data labels to make your own (step-by-step below):

Step 1. Select the bar chart data and create a new bar chart. Format the color.
Step 2. Select the horizontal axis. Under Format Axis > AXIS OPTIONS > Axis Type, select "Text axis".

Step 3. Select the vertical axis. Under Format Axis > LABELS > Label Position, select "None".
Step 4. Right-click the chart. Select "Select Data", then add a new series. Select the series values. Click "OK".
Step 5. Right-click the newly added series. Select "Change Series Chart Type".

Change the newly added series to "Scatter with Straight Lines" and check the "Secondary Axis" checkbox. Click "OK" and change the series color.

Step 6. Add a column of data that starts at 0.5 and increments by 1. Set these as the Series X values for the blue line. Add another three columns of data as shown below.

Step 7. Add a new series to the chart. Select the "x-Axis X" data for the Series X values and the "x-Axis Y" data for the Series Y values and click "OK" twice. Turn on the secondary horizontal axis.

Step 8. Select the newly created series, and add data labels to the left.

Step 9. Right-click the data labels and select "Format Data Labels". Under "LABEL OPTIONS. "Check Value From Cells" and select the x-Axis Labels data. Click "OK" then uncheck "Y Value" and "Show Leader Lines" back in "LABEL OPTIONS".

Step 10. Clean up. Select the x-Axis series and turn off the line and markers. Set the secondary horizontal and vertical axis labels to "None" (Format Axis > AXIS OPTIONS > LABELS).


text:
Q: Google Drive implementation in android i am implementing Google Drive in Android with Java code i didnt use Android formats,
i just created client id and i used in Manifest

<meta-data android:name="com.google.android.apps.drive.APP_ID" android:value="id=344123456789"/>

and my code to create folder is

credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(DriveScopes.DRIVE));
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
java.io.File fileContent = new java.io.File(path);
                    FileContent mediaContent = new FileContent("image/jpeg", fileContent);

                    File fileMetadata = new File();
                    fileMetadata.setName("Invoices");
                    fileMetadata.setMimeType("application/vnd.google-apps.folder");

                    File file = UploadPicture.service.files().create(fileMetadata)
                            .setFields("id")
                            .execute();

this is my code to create folder, but if i am using it from Activity it works but i am using fragments so i got UserRecoverableAuth exception please anyone help me.
Thanks in advance

A: @Villonava, I think you are having trouble with Google Authentication Error when using your fragments. The UserRecoverableAuth exception means:

UserRecoverableAuthExceptions signal Google authentication errors that
  can be recovered with user action, such as a user login.

In this SO question, the OP used try catch block:
...
} catch (UserRecoverableAuthIOException e) {
   startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
}
...

Doing this will trigger an intent to authorize your activity/app. Also try following the Drive quickstart for Android, it is a step-by-step guide showing how to authorize and upload a file to Drive:


text:
Q: Apache HTTPClient doesn't allow more than 1500 reusable connections I'm using Apache HTTPClient (4.2.2) / Java7 to open many reusable connections to a tomcat 7 server (to simulate many users repeatedly hitting the service). Both client and server on Ubuntu 12 (but different machines). I made sure that systctl.conf and limits.conf allow this scenario.
This works well up to about 1500 simulated users / connections. The connections get reused as expected. Somewhere between 1500 and 1600 simulated users however, connections are no longer reused and closed/ re-opend all the time. Why might this be the case?
I don't think the problem is on the server side as when I start multiple simulation clients on different machines against the same server, the server has no problems reusing the connections as long as each client doesn't go beyond 1500 connections.

A: There can be various reasons as to why connections are not longer being re-used depending on the configuration of the connection manager OR server side configuration. The easiest way to find out the reason is to run HttpClient with context logging on as described in the 'context logging for connection management / request execution' example in the Logging Guide

A: You might need to increase the number of available workers,at least check if there are workers free when you run out of connections by going to server-status


text:
Q: when $ \ v(t)=0 \ $? Let $ \ a(t) , \  v(t) \ \ and \ \ s(t) \ $ denote the acceleration , velocity and position of a particle at time $ \ t \ $. Given $ \ a(t)=3 \cos (t)-2 \sin (t) , \ \ s(0)=0 , \ v(0)=4 \ $.  Then find
(i) when $ \ v(t)=0 \ $ ?
(ii) when $ \ v(t) \ $ will be maximum in positive direction ?
(iii) when $ \ v(t) \ $ will be maximum in Negative direction ?
Answer:
(i)
$ a(t)=3 \cos t-2 \sin t \\ \Rightarrow \frac{\mathrm{d} v}{\mathrm{d} t} =3 \cos t-2 \sin t \ $
Integrating ,we get
$ v(t)= 3 \sin t+2 \cos t+c \ $  , where $ \ c \ $ is arbitrary constant.
Using $ \ v(0)=4 \ $ , we get
$ c=2 \ $
Thus,
$ v(t)=3 \sin t+2 \cos t+2 \ $
Now $ \ v(t)=0 \\ \Rightarrow 3 \sin t+2 \cos t+2 =0 \ $
But I can not solve for $ \ t \ $.
Is my process is correct?

A: Hint $$a\cos x+b\sin x=\sqrt{a^2+b^2}\left(\frac{a}{\sqrt{a^2+b^2}}\cos x+\frac{b}{\sqrt{a^2+b^2}}\sin x \right) \\ =\sqrt{a^2+b^2}\sin(x+\phi) \\ \phi =\tan^{-1}(a/b)$$
$v(t)$ is maximum in positive or negative direction when it's derivative i.e the acceleration is $0$. So you find the solutions of $$3\cos t-2\sin t=0 \\ \tan t =3/2 \\ t=\tan^{-1}(3/2), \pi+\tan^{-1}(3/2)$$
Substitute these values in velocity.

A: You can use the following substitution :
y=tan (t/2)
This would give you sin t=2y/(1+y^2) and cos t=(1-y^2)/(1+y^2)Applying this to your equation 2cos t+3sin t+2=0,you get 4+6y=0
This can be solved for y and in turn t.
You get t as x = 2 (π n - tan^(-1)(2/3)) where n is an integer. Take only positive values of t since it represents the time in your case.

The second and third parts of the question can be figured out using the second derivative tests.For part (ii) you need a maxima and for (iii) you need a minima.In case,you are not sure of how this works,you can check it here:http://mathworld.wolfram.com/SecondDerivativeTest.html

A: Here is another hint:
If we write S=sin(t), then your equation can be written as:
$$3S+2\sqrt{1-S^2}-2=0$$
This can be readily manipulated to give:
$$13S^2-12S=0$$
From this we deduce that sin(t) can be either 0 (an invalid answer) or 12/13.   The second answer is correct and so we also deduce that we will have solutions at arcsin(12/13) = 62.38... deg or 112.62... deg.  Again, only the latter is valid.
However, this method is clumsy and indirect.  I prefer the following as more direct and easier to follow.  Any expression involving a sum like this can be rewritten:
$$Asin(t)+Bcos(t)=Csin(t+\phi)$$
By using the simple compound angle formula for sin(A+B) we can readily deduce that $$C=\sqrt{(A^2+B^2)}$$ and $$tan(\phi)=B/A$$
Therefore, your equation can be written as $$\sqrt{13}.sin(t+\phi)+2=0$$ which is easy to solve for t.
As for the other parts of your question, finding maxima and minima involves setting the first derivative to zero and solving.


text:
Q: Simple regex replaces more than it should in a string I'm trying to create a regular expression that replaces an URL with a token. That's how far I got, and I don't understand why this expression replace everything after the URL as well except for the last word.
string<-"This is a website http://www.bla.com that I like very much"
gsub("https?://.*\\s|www.*\\s"," [url] ",string)

>>"this is a website  [url] much"

Appreciate your help very much!

A: The problem is the .* - it will match anything greedily, so you will match all the way up to the last space. try
gsub("https?://[^[:blank:]]*","[url]",string) instead.


text:
Q: Improving Data Transfer Rate on Amazon EC2 I've got a 1-Gig EBS Volume mounted to an EC2 instance,
I am copying 600MB of binary data from a Local Hard Drive (via RDS Connection)
and the copying process windows is showing 10 Hours remaining.
Though I have a High Speed connection (100+Mbps)
Whatever the data volume, data transfer rate is 1 Min / MB  (i.e 16Kbs / Sec)
I am hesitating between reading Moby Dick in front of my workstation or just taking a day-off.
Are there any reasonable options to speed up this transfer rate ? (Ideally 512 Kbps/Sec at the minimum)
I am very open to ANY solution to shorten up the uploading/downloading time to/from and EC2 instance.
Thanks in advance.
EDIT :
I just stumbled upon [Amazon Export/Import Service][1]
"AWS Import/Export accelerates transferring large amounts of data between the AWS cloud and portable storage devices that you mail to us" By "mail to us", they literally mean you "materially" shipping your storage device to Amazon. Don't say this is Stoneage, this is BRAND new TECHNOLOGY, Dude ! :-)
EDIT2 :
This sounded great: [Aspera for AWs][2] But unfortunately way too expensive; Tailored for Fortune 500 with big needs and big cash.

A: Sometimes, if you want something done it's better to do it yourself :-)
I did not find anything satisfying over the net so I spent the evening doing a rather Complete Bench Test of my own.
I have tested a few alternatives /scenarios and here are the results :
FTP server installed on EC2 was Filezilla Server (correct configuration is touchy)
FTP Client used for this Bench test was WinSPC  (Filezilla Client didn't work. see this other post
Legend : [HC] stands for Home Connection (100MBps)
Upload Bandwidth
RDS Upload : 15 Kb/S => Worse Ever
FTP Upload [FTP Server Installed on EC2]: 100 Kb/S
Upload to S3 from AWS Management Console from HC: 60 Kb/S
Upload to S3 using AWS Console interface from EC2 : 145 Kb/S
Upload to S3 using S3 Browser from HC: 120 Kb/S
Upload to S3 using S3 Browser from EC2 : 2000 Kb/S
Download Bandwidth
RDS Download and Upload: 15 Kb/S => Worse Ever
FTP Download [FTP Server Installed on EC2]: 360 Kb/S
Download from S3 AWS Console interface from EC2 : 350 Kb/S
Download from S3 using S3 Browser: from HC: 380 to 620 Kb/S
Download from S3 using S3 Browser: from EC2 : 3000 Kb/S
Conclusions :
So, as of now, Amazon S3 combined with S3 Browser give the best results.
(S3 Browser is just a layer over S3 I don't get it why the upload rate is better)
However, one should keep in mind that an FTP Server on an EC2 instance has the great advantage of Mapping directly a local EC2 Directory into EC2. Unlike S3, there is only one transfer involved. Indeed, S3 requires 2 Transfers : Form Local Resource to S3/and from S3 to EC2 and the other way round, while FTP Access grants immediacy by shortening transfer cycles. Besides, it spares the cost of S3 Buckets.
It is also interesting to mention that EC2 Instance's bandwidth is really strong. It is hence far more interesting -needless to say, to use protocols that really take advantage of it such as S3 or FTP, rather than RDS.
I hope this will be useful to other people facing the same issue and spare them precious time.

A: Use Aspera or Tsunami UDP and move 600 MB to your Amazon EC2 infra (jump box). Then internally copy from jumpbox to windows ec2. My benchmark shows tsunami UDP is quite faster compared to traditional modes.


text:
Q: Specify color of symbols for group levels in panels of a conditioned scatterplot matrix made with splom? How do I specify the color of group levels in panels of a conditioned scatterplot matrix generated using splom? I can do so in the key, but I find no arguments for symbols in panel.pairs.  Not only does key not match panels, colors assigned to group levels should be male=blue, female=pink.
dput(head(dfSO,20))
structure(list(MHI = c(67460L, 89033L, 61836L, 49853L, 88772L,
                       105107L, 94744L, 56061L, 49435L, 68027L, 152673L, 56408L,
                       74493L, 53048L, 62485L, 96712L, 90211L, 81249L,
                       111576L, 102231L),
               gender = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                    1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L),
                                  .Label = c("female", "male"),
                                  class = "factor"),
               happy = c(4, 4, 1, 4, 3, 3, 3, 3,
                         2, 4, 3, 4, 3, 4, 3, 1, 4, 3, 3, 2)),
          .Names = c("MHI", "gender", "happy"), row.names = c(NA, 20L),
          class = "data.frame")
library(lattice)
super.sym <- trellis.par.get("superpose.symbol") #where I can customize key
splom(dfSO, groups=dfSO$gender, subset=TRUE, panel=panel.superpose,
      key=list(title="By Gender", columns=2,
               points=list(pch=super.sym$pch[1],col=super.sym$col[1:2]),
               text=list(c("male","female"))))

A: When changing graphical parameters in lattice graphics, my favorite approach is to pass the parameters to the par.settings argument. This changes the graphics settings for the current plot but doesn't alter the global settings found with trellis.par.get().
(I would also change the key argument to auto.key.)
You were on the right track with the superpose.symbol settings! The order of the grouping variable levels (male and female) determines which color gets assigned to which level. Since the levels are generally ordered alphabetically, female will get the first color.
First, create an object with the desired graphical parameters:
myPars <- list(superpose.symbol = list(pch = super.sym$pch[1], col = c("pink", "blue")))

Then pass those to splom via the par.settings argument (notice the altered key as well).
splom(dfSO, groups = dfSO$gender, subset = TRUE, panel = panel.superpose,
    auto.key = list(title="By Gender", columns=2),
    par.settings = myPars)


text:
Q: Is it possible to have a weak enum? I'm using gcc, and I am distributing an object file which may be used in conjunction with some third party code.   I have something that looks like this:
void fn3rdParty(int bar) __attribute ((weak));

void fn(void) {
    if(fn3rdParty)
        fn3rdParty(SOME_ENUM);
}

where SOME_ENUM is an enum and is defined by the third party code if present.  I tried declaring SOME_ENUM as a weak int, but gcc complains that the type is redefined.  I'm wondering if there's a way around this?  (I'd like to avoid having one .o file for use with this software, and another to be used without).
John


text:
Q: HTTPS POST request to a multipart form that has a file type input I am trying to POST to this endpoint using nodeJS's https.request() function but I'm getting a "missing file" response, however, it is able to read when I POST the clientId, so I'm thinking that "file" type inputs in multipart forms are possibly handled differently? Am I not POSTing in the correct manner?
This is the HTML form representation on the client's end that I'm POSTing too:
<form action='https://example.com/foo/bar/test' method='POST' enctype='multipart/form-data'>
        <input type="file" name="file">
        <input type="hidden" name="clientId" value="12345">
        <input type="submit" name="submit">
</form>

And this is my backend code for POSTing to it:
const data = JSON.stringify({
    file: pathToPdf,
    clientId: 6789
})

const options = {
    hostname: 'example.com',
    path: '/foo/bar/test',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    auth: 'user:pass'
};

`const req = https.request(options, (res) => {
    console.log('STATUS: ${res.statusCode}');
    console.log('HEADERS: ${JSON.stringify(res.headers)}');
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
        console.log('BODY: ${chunk}');
    });
    res.on('end', () => {
        console.log('No more data in response.');
    });
})
req.on('error', (e) => {
    console.error('problem with request: ${e.message}');
});

req.write(data);
req.end();

Is there a reason why "clientId" would work but not "file"?


text:
Q: Ruby on Rails Sign Up Page Issues (spitting out error without an error provided) I am trying to work on a simple signup page using Ruby on Rails, however I'm running into an issue.  When a user is logging in, the validation errors I have set up are being triggered when they should not be (it is saying the password is not long enough when it is).
Here is some relevant code:
user_controller.rb:
def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

User.rb model:
class User < ActiveRecord::Base
    #attr_accessor :name, :email, :password_digest
    before_save { self.email = email.downcase }
    validates :name, presence: true, length: { maximum: 50 }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true,
                      format: { with: VALID_EMAIL_REGEX },
                      uniqueness: { case_sensitive: false }

    has_secure_password
    validates :password, length: { minimum: 6 }

    has_many :microposts
end

new.html.slim view:
- provide(:title, 'Sign up')
h1 Sign up
.row
  .col-md-6.col-md-offset-3
    = form_for(@user) do |f|
      = render 'shared/error_messages'
      = f.label :name
      = f.text_field :name, class: 'form-control'
      = f.label :email
      = f.text_field :email, class: 'form-control'
      = f.label :password
      = f.password_field :password, class: 'form-control'
      = f.label :password_confirmation, "Confirmation"
      = f.password_field :password_confirmation, class: 'form-control'
      = f.submit "Create my account", class: "btn btn-primary"

When I try to create a new user, the route changes from signup to users.  However, the user is not created, and the errors are:
The form contains 2 errors.
Password can't be blank
Password is too short (minimum is 6 characters)
However, a password was entered.  Do you see anything that would cause this?  Thank you.
EDIT:
This is the console output when trying to make a user on the signup page:
Started POST "/users" for 127.0.0.1 at 2014-11-07 15:02:51 -0800
Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"DP7+I+/MRBidFqmoav2E8bUAxt+f5kSfPaRPkcEehLE=", "user"=>{"name"=>"Joe Bob", "email"=>"bob@gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create my account"}
Unpermitted parameters: password, password_confirmation
   (0.1ms)  BEGIN
  User Exists (1.6ms)  SELECT  1 AS one FROM `users`  WHERE `users`.`email` = 'msutyak@gmail.com' LIMIT 1
   (0.1ms)  ROLLBACK
  Rendered shared/_error_messages.html.slim (1.1ms)
  Rendered users/new.html.slim within layouts/application (3.3ms)
  Rendered layouts/_header.html.erb (0.2ms)
  Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 34ms (Views: 13.3ms | ActiveRecord: 1.9ms)

I am not sure why password and password_confirmation are "unpremitted".  Any ideas?

A: Print out what you are passing into User.new(). If the password is not being passed in, check that you have explicitly allowed it in the strong parameters. ie) params.require(:user).permit(:name, :email, :password)

A: Make sure you are using Devise latest version and have a look at DeviseStrongParameters
Add to your application controller
before_filter :add_sanitized_params, if: :devise_controller?

def add_sanitized_params
  devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:password, :password_confirmation)}
end

Please let me know if it does not work ...


text:
Q: Spotify Web API - Authenticate user via native mobile app rather than browser? I am testing the following example to authenticate a user by logging in and redirecting to the auth screen - http://jsfiddle.net/JMPerez/j1sqq4g0/
This example uses a callback page with the following script:
(function() {
  var hash = {};
  window.location.hash.replace(/^#\/?/, '').split('&').forEach(function(kv) {
    var spl = kv.indexOf('=');
    if (spl != -1) {
      hash[kv.substring(0, spl)] = decodeURIComponent(kv.substring(spl+1));
    }
  });

  console.log('initial hash', hash);

  if (hash.access_token) {
    window.opener.postMessage(
      JSON.stringify({
        type:'access_token',
        access_token: hash.access_token,
        expires_in: hash.expires_in || 0
      }),
      'http://fiddle.jshell.net'
    );
    window.close();
  }
})();

When trying on mobile, it will open a new tab in Safari. Is it possible to check if the app if installed on iOS and login via that instead? Will make the process much quicker.
As seen in an issue here, it seems resolved but cannot understand what is triggering it to do so? - https://github.com/spotify/web-api/issues/718
Thanks!

A: To summarize here's an aggregated answer:

*

*iOS doesn't allow for looking what apps are installed on your device, neither does Android.

*Using universal links (both on Android and iOS), you generally speaking may generate a link that opens an app, but for this, the corresponsing App needs to register this connection on your device.

*For Spotify especially, I don't think that the Spotify-app has registered such a link. It's not usual that native Apps trigger for authentication only, so it's unlikely that Spotify does.


text:
Q: How do you find second highest number in an integer array? How do you find second highest number in an integer array?
Is this a good implementation?
Is there a better way to do this?
public class Find2ndHighest {
    public static void main(String[] args) {
        int b[] = {2,3,1,0,5};

        TreeMap<Integer,Integer> tree = new TreeMap<Integer,Integer>();
        for(int i = 0; i<b.length;i++){
            tree.put(b[i], 0);
        }
        System.out.println(tree.floorKey(tree.lastKey()-1));
    }
}

A: You can sort the array and fetch second last element which executes in O(nlogn), but this works only if you are sure that there are no duplicates in the array else this method is unreliable.
You can iterate through the array maintain counters for highest and second highest and return 2nd highest. This executes in O(n)
Example:
 int highest = Integer.MIN_VALUE+1;
 int sec_highest = Integer.MIN_VALUE;
 for(int i : b) //b is array of integers
 {
     if(i>highest)
     {
        sec_highest = highest; //make current highest to second highest
        highest = i; //make current value to highest
     }
     else if(i>sec_highest && i != highest)
     {
        sec_highest = i;
     }
 }

Another solution is:
int b[] = {1, 2, 31,22,12,12};
Arrays.sort(b);
System.out.println(b[b.length-2]);

A: The easiest solution would be:
public static void main(String[] args) {
    int b[] = {2,3,1,0,5};
    int highest = Integer.MIN_VALUE;
    int highest2nd = Integer.MIN_VALUE;
    for(int i :b )
        if (i>=highest) {
            highest2nd = highest;
            highest = i;
        } else if (i>= highest2nd)
            highest2nd = i;
    System.out.println(highest2nd);
}

Then you walk through the list only once, which is the best you can do from a 'Big O' standpoint.
PS: depending on whether you want the second highest unique value, or the value that is stricly lower than the highest value, you could choose to put i>highest in the if-statement, instead of i>=highest.

A: There are multiple ways to find the second highest element in an unsorted array:

*

*You can sort the array and take the second last element - runs in O(n log n).

*You can store the elements in a TreeSet instead of an array, which is what you are doing - runs in O(n log n) as well.

*Suppose for a while you want to get the highest element - all you have to do is to iterate over the whole aray once, while keeping the maximum in a variable.
This way you can achieve O(n) performance.
You can do the same thing for the second highest element, but instead of keeping the highest element, you will keep the two highest elements.
This way you can easily achieve O(n) performance.

*The only problem with the last solution is that it does not scale well with the increasng k.
There is however a linear time algorithm to find the k-th highest element in an unsorted array - runs in O(n) for any k (http://en.wikipedia.org/wiki/Selection_algorithm)


text:
Q: submit values using jquery .I have this code1:
<form method="GET" action="picture.php">

.usually the value of i1 will be sent if i use this code2:
<input type="submit">

.Is there a way to trigger the "submit" function by using a jquery instead of code2? help pls!

A: <form method="GET" action="picture.php" id="picture-form">

... followed by the following call in javascript, wherever it might be required ...
$('form#picture-form').submit();

Note that an ID has been added to the form for an accurate jQuery reference.  just doing $('form').submit(); could be very evil.
Fully fledged example follows.

<form method="GET" action="picture.php" id="picture-form">
    Submit me!
</form>

A: take a look at this link : http://api.jquery.com/submit/ -
Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.

A: There's even no need for jQuery, you can do it in vanilla JavaScript:
<form method="GET" action="picture.php" id="picture-form">
 Click me!
...
</form>


text:
Q: INSERT INTO Table and using uniqueid of Entry, INSERT into 2nd table, and using uniqueid of 2nd table finally a 3rd., each references the one prior Example; 3 Tables.
Table1 = Forms - (key) FormID int, FormName nvchar(30), Required bit, IsActive bit, IsDeleted bit
Table2 = FormLabel - (key) FormLabelId int, FormID int, LabelName nvhcar(30), IsActive bit, isDeleted bit, CustomeField nvchar(30), DisplayOrder int
Table3 = FormEntry - (key) EntryID int, FormID int, FormLabelID int, EntryName nvchar(max), IsActive bit, IsDeleted bit, DisplayOrder int

I need to create a Form, Then use that Form's FormID then be used as a Reference to Create a Label, and then using the created FormLabelId create X entries referencing both FormID + FormLabelId
There will likely be multiple FormEntry(s) to be inserted per Label per Form.
Example;
Create a new Form that with have 5 Labels, each with 5 Entries.
Form1 -> Label1 -> Entry1-5.
Form2 -> Label2 -> Entry1-5 etc.

A: I guess your looking for a nested relationship among three (3) tables: Forms, FormLabel and FormEntry. Each one has a unique primary key and the relationship could be depicted as:

*

*Forms is the parent entity.

*FormLabel seeks Label registers from Forms table.

*FormEntry checks registers from FormLabel table and, also from Forms table.

In  this way, a SQL script may be used with above mentioned entities as follows, supposing if you have a database called MYAPP in plain SQL ANSI already in a SQL Server on Premise or in a SQL Azure database engine:
    create Table Forms (
        FormID     int not null,
        FormName   nvarchar(30),
        IsRequired bit,
        IsActive   bit,
        IsDeleted  bit
        CONSTRAINT PK_FormID PRIMARY KEY CLUSTERED (FormID)
    ) on [PRIMARY];

    create Table FormLabel (
         FormLabelId    int not null,
         FormID         int,
         LabelName      nvarchar(30),
         IsActive       bit,
         isDeleted      bit,
         CustomeField   nvarchar(30),
         DisplayOrder   int,
         CONSTRAINT PK_FormLabelId PRIMARY KEY CLUSTERED (FormLabelId)
    ) on [PRIMARY];

    create Table FormEntry (
        EntryID         int not null,
        FormID          int,
        FormLabelID     int,
        EntryName       nvarchar(max),
        IsActive        bit,
        IsDeleted       bit,
        DisplayOrder    int
        CONSTRAINT PK_EntryID PRIMARY KEY CLUSTERED (EntryID)
    )  on [PRIMARY];

So, the approach for Foreign Keys on

FormLabelId create X (or n) entries referencing both FormID + FormLabelId

that are you wrote could be generated with a set of Foreign Keys for FormID and for FormLabelId specified in the table FormEntry:
  /* FormEntry */
  alter table FormEntry
  add constraint fk_FormLabelID foreign key (FormLabelID)
  references FormLabel (FormLabelId)

  constraint fk_FormEntry_FormID foreign key (FormID)
  references Forms (FormID)
  ;

This looks like:

However, in the example

Create a new Form that with have 5 Labels, each with 5 Entries. Form1 -> Label1 -> Entry1-5. Form2 -> Label2 -> Entry1-5

You specify to create 5 Labels, thus, they're 5 registers on table FormLabel with 5 registers on FormEntry table, but no integrity rules are cleared here. The insight is used as follows with the same script with a light modification:
 /* FormLabel */
 alter table FormLabel
  add constraint fk_FormID foreign key (FormID)
  references Forms (FormID)
  ON UPDATE CASCADE
 ;

Where the keyword CASCADE is corresponding rows are updated in the referencing table (in this case, FormLabel) when that row is updated in the parent table (Forms).
So, I hope for your feedback is this worth.


text:
Q: Converting flv file into swf using c# I have been trying to convert a flv file into swf file. How can I convert the flv video into swf file using C#?

A: If you are asking for the algorithm for how to do the conversion in C# then that is far outside the scope of a simple SO-question.
But instead of doing that I would recommend you use one of many existing command-line tools for doing the conversion. The tools can be called from your C# code using the Process class. When the conversion tool finishes you can read out the converted file and do whatever you want with it.


text:
Q: Accessing user input I am trying to create an e-commerce application and now I am at the part where I have to create the account management logic.I am trying to take advantage of the Membership API but I can't seem to find a way on how to proceed.
My application has two databases is the one containing all the tables for the e-commerce application and the second is the one generated by asp.net for using it with the Membership API.
I do not know how I can retrieve the data the user inputs.
This is what I am planning to do:
    [HttpPost]
    public ActionResult LogIn()
    {
        if(ModelState.IsValid)
        {
            if(Membership.ValidateUser(username , password))
            {

            }
        }
    }

Can anyone please give me an idea on how I can retrieve the user's input?

A: You're going to need to pass a model in. Let's say for example I've got a view with a form on it and it has the following fields:
<input type="textbox" id="username" name="username"/>
<input type="password" id="password" name="password"/>

Now I'm going to need a model to serialize this into:
public class LoginModel
{
    public string username { get; set; }
    public string password { get; set; }
}

Now I'm going to want to receive that model into the action method:
[HttpPost]
public ActionResult LogIn(LoginModel model)

When the POST occurs, ASP.NET MVC will build the model for you out of the input fields inside the form.


text:
Q: Laravel Task Scheduling Error: Invalid CRON field value 10,40 at position I was trying to schedule a job to run on 10th and 40th minute of every hour. So wrote the expression as follows:
$schedule->job(new \App\Jobs\ExcuteJob())->cron('0 10,40 * * *');

And getting error:

Invalid CRON field value 10,40 at position 1 {"exception":"[object]
  (InvalidArgumentException(code: 0): Invalid CRON field value 10,40 at
  position 1 at
  /var/www/html/school-management-system/vendor/dragonmantank/cron-expression/src/Cron/CronExpression.php:154)

A: There is a mistake in your command try this:
$schedule->job(new \App\Jobs\ExcuteJob())->cron('*/10,*/40 */1 * * *');

This command should call the cronjob every 10th and 40th minutes of an hour.
This page may help you.


text:
Q: WSL-Docker: curl: (60) unable to get local issuer certificate After a PC reconfiguration I am unable to use Docker properly, since some curl commands are rejected due to SSL/TLS issues.
In just one example curl -vfsSL https://apt.releases.hashicorp.com/gpg returns the following error:
*   Trying 52.222.214.125:443...
* TCP_NODELAY set
* Connected to apt.releases.hashicorp.com (52.222.214.125) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (OUT), TLS alert, unknown CA (560):
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

After some digging, I now now know that this issue also occurs within my WSL image, but not on host Windows OS. Hence, I believe this must be an issue that originates with my WSL setup, and not caused by Docker itself (?).
There are quite a few related questions on serverfault/stackoverflow but no solutions I found really apply to this case:

*

*Curl: unable to get local issuer certificate. How to debug?

*curl: (60) SSL certificate : unable to get local issuer certificate - ubuntu

*Curl SSL Certificate: unable to get local issuer certificate
FWIW I work at an enterprise, with IT-issued OS. Obviously that could be a source of error, but they are unable to help me debug this issue. One a colleague's PC, however, it works flawlessly.
Any ideas?

PC Setup:

*

*Windows 10 Enterprise

*

*Version: 21H1

*OS build: 19043.1645

*Windows Feature Experience Pack: 120.2212.4170.0

*WSL 2 with Ubuntu-20.04

*Docker Desktop 4.7.1 (77678) with WSL 2 based engine

Update 1
As suggested by @Martin, I tried downloading https://www.amazontrust.com/repository/AmazonRootCA1.pem, put it inside /tmp in WSL Ubuntu, and reran the command curl --cacert /tmp/AmazonRootCA1.pem -vfsSL https://apt.releases.hashicorp.com/gpg to no avail:
curl --cacert /tmp/AmazonRootCA1.pem -vfsSL https://apt.releases.hashicorp.com/gpg
*   Trying 52.222.214.72:443...
* TCP_NODELAY set
* Connected to apt.releases.hashicorp.com (52.222.214.72) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /tmp/AmazonRootCA1.pem
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (OUT), TLS alert, unknown CA (560):
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

A: We have finally figured it out. The issue here was that the IT department installed a firewall which intercepts SSL connections (many firewalls do this to be able to block "bad" traffic which would go through undetected because of the encryption).
To be able to intercept a SSL connection, The firewall puts its own certificate on the link, and acts as a proxy. That is where the issue is coming from: The docker container does not trust the CA used by your firewall, and therefore rejects establishing the connection. Obviously, for your windows machine the CA has been added to the trust store already - this needs to be done for your docker container as well - or you need to add the --insecure switch to your curl command to ignore those certificates error.
Note that curl correctly throws an error, since the https - certificate mechanism was invented to be able to detect a "Man in the Middle" attack - and this is exactly what is happens here. (I will just skip my opinion here about firewalls breaking SSL security to be able to inspect packet contents...)
To fix this, you need the CA file from your gateway which "signs" all those certificates, and add this CA to the trusted list.
Just for completeness, this is the certificate you see:
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            6a:7b:6c:fd:70:b2:68:1a:56:e3:11:3c:43:ed:ae:29
        Signature Algorithm: sha1WithRSAEncryption
        Issuer: C = US, ST = California, L = Sunnyvale, O = Bad Server Certificate [invalid server certificate], CN = Bad Server Certificate
        Validity
            Not Before: Jan 26 07:08:23 2011 GMT
            Not After : Nov 11 07:08:23 2284 GMT
        Subject: CN = apt.releases.hashicorp.com
[cut]

this is the original one:
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            03:57:ef:0e:70:b2:68:1a:56:e3:11:3c:43:ed:ae:29
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = US, O = Amazon, OU = Server CA 1B, CN = Amazon
        Validity
            Not Before: Apr 27 00:00:00 2022 GMT
            Not After : May 26 23:59:59 2023 GMT
        Subject: CN = apt.releases.hashicorp.com


text:
Q: Display JSON data in a ComboBox using java I used the code below to retrieve json data and put it in a table. That worked. But I want to display the data in a combobox now. Right now, it is displaying the items in the dropdown in this format: ljava.lang.string @5c647e05
Can someone please tell me what I'm doing wrong? Thank you.
                        Hashtable response = parser.parse(reader);

                        java.util.List allResult = (java.util.List) response.get("AllResult");
                        System.out.println(allResult);
                        try {

                            String[][] data = new String[allResult.size()][4];
                            for (int i = 0; i < allResult.size(); i++) {

                                Object obj = allResult.get(i);
                                String result = (String) ((Hashtable) obj).get("Status");

                                String investorName = (String) ((Hashtable) obj).get("investorName");
                                if (result.equalsIgnoreCase("ok")) {
                                    for (int j = 0; j < 4; j++) {

                                        if (j == 0) {
                                            data[i][j] = investorName;                          }
                                                                            }

                                }
                            }

                            ComboBox investorNames = new ComboBox(data);
                            details.addComponent(investorNames);
                            System.out.println("Data here: " + data);

                            String[] columnNames = { "Seller's Name", "Stock Name", "Unit", "Price" };
                            TableModel model = new DefaultTableModel(columnNames, data, false);
                            Table table = new Table(model);
                            table.setScrollable(true);

                            details.addComponent(table);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }

A: Try to paste in Combobox only vector of invector names not whole array of arrays. As Combobox just invokes toString() on every array (row) of matrix, that's why you got Ljava.lang.String@5c647e05 and not investor names. Something like this:
String[] comboData = new String[allResult.size()];
for (int i = 0; i < allResult.size(); i++){

    ...

    String investorName = (String) ((Hashtable) obj).get("investorName");

    comboData[i] = investorName

    ...

}

ComboBox investorNames = new ComboBox(comboData);
details.addComponent(investorNames);

....

A: ComboBox expects an array of string but you are passing to it an array of array of strings.
So those ljava.lang.string @5c647e05 that you are seeing are the 'toString' representation of an array of strings.
You need to somehow (depending on what you need to do) flatten your 'data' so that it becomes an array of strings.


text:
Q: ошибка при установке pip eel понадобился плагин eel, во время установки была ошибка с visual studio, все установил, теперь новая ошибка. Вот ее текст:
ERROR: Command errored out with exit status 1:
     command: 'c:\users\владимир\appdata\local\programs\python\python39\python.exe' 'c:
users\владимир\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\pep
17\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\18EE~1\AppData\Local\Temp
tmpcrgize8y'
         cwd: C:\Users\Владимир\AppData\Local\Temp\pip-install-gegor226\gevent_3ecc2ee7
be04dadaed632c5622bd7a4
    Complete output (77 lines):
    Error in sitecustomize; set PYTHONVERBOSE for traceback:
    SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xe2 in position 0: in
alid continuation byte (sitecustomize.py, line 7)
    WARNING: The wheel package is not available.
    Error in sitecustomize; set PYTHONVERBOSE for traceback:
    SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xe2 in position 0: in
alid continuation byte (sitecustomize.py, line 7)
    WARNING: The wheel package is not available.
    Error in sitecustomize; set PYTHONVERBOSE for traceback:
    SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xe2 in position 0: in
alid continuation byte (sitecustomize.py, line 7)
    running dist_info
    creating C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadata-3ql5shei\gevent.e
g-info
    writing C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadata-3ql5shei\gevent.eg
-info\PKG-INFO
    writing dependency_links to C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadat
-3ql5shei\gevent.egg-info\dependency_links.txt
    writing entry points to C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadata-3q
5shei\gevent.egg-info\entry_points.txt
    writing requirements to C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadata-3q
5shei\gevent.egg-info\requires.txt
    writing top-level names to C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadata
3ql5shei\gevent.egg-info\top_level.txt
    writing manifest file 'C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadata-3ql
shei\gevent.egg-info\SOURCES.txt'
    reading manifest file 'C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadata-3ql
shei\gevent.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    warning: no files found matching 'changelog.rst'
    warning: no files found matching 'Makefile.ext'
    warning: no files found matching 'known_failures.py'
    warning: no files found matching '.pep8'
    no previously-included directories found matching '*\__pycache__'
    warning: no previously-included files matching '*.so' found anywhere in distributio
    warning: no previously-included files matching '*.o' found anywhere in distribution
    warning: no previously-included files matching '*.lo' found anywhere in distributio
    warning: no previously-included files matching '*.la' found anywhere in distributio
    warning: no previously-included files matching '.dirstamp' found anywhere in distri
ution
    warning: no previously-included files matching 'config.log' found anywhere in distr
bution
    warning: no previously-included files matching 'config.status' found anywhere in di
tribution
    warning: no previously-included files matching 'config.cache' found anywhere in dis
ribution
    no previously-included directories found matching 'docs\_build'
    warning: no previously-included files matching '*.pyc' found anywhere in distributi
n
    warning: no previously-included files matching '.coverage' found under directory 's
c\greentest'
    no previously-included directories found matching 'src\greentest\htmlcov'
    warning: no previously-included files matching 'stamp-h?' found under directory 'de
s\c-ares'
    warning: no previously-included files matching 'ares_build.h.orig' found under dire
tory 'deps\c-ares'
    warning: no previously-included files matching '_corecffi.c' found under directory
src\gevent'
    warning: no previously-included files found matching 'configure-output'
    warning: no previously-included files found matching 'configure-output.txt'
    warning: no previously-included files found matching 'deps\TAGS'
    warning: no previously-included files found matching 'deps\c-ares\ares_build.h'
    warning: no previously-included files found matching 'deps\c-ares\ares_config.h'
    warning: no previously-included files found matching 'deps\c-ares\libcares.pc'
    warning: no previously-included files found matching 'deps\c-ares\libtool'
    warning: no previously-included files found matching 'deps\c-ares\Makefile'
    no previously-included directories found matching 'deps\c-ares\.deps'
    no previously-included directories found matching 'deps\c-ares\.libs'
    no previously-included directories found matching 'deps\libev\.deps'
    no previously-included directories found matching 'deps\libev\.libs'
    warning: no previously-included files matching 'Makefile' found under directory 'de
s\libev'
    warning: no previously-included files matching 'libtool' found under directory 'dep
\libev'
    warning: no previously-included files matching 'stamp-h?' found under directory 'de
s\libev'
    warning: no previously-included files matching 'config.h' found under directory 'de
s\libev'
    no previously-included directories found matching 'deps\libuv\.deps'
    no previously-included directories found matching 'deps\libuv\.libs'
    no previously-included directories found matching 'deps\libuv\src\.deps'
    no previously-included directories found matching 'deps\libuv\src\unix\.deps'
    no previously-included directories found matching 'deps\libuv\src\win\.deps'
    no previously-included directories found matching 'deps\libuv\test\.deps'
    no previously-included directories found matching 'deps\libuv\autom4te.cache'
    no previously-included directories found matching 'deps\libuv\m4'
    warning: no previously-included files matching 'Makefile' found under directory 'de
s\libuv'
    warning: no previously-included files matching 'Makefile.in' found under directory
deps\libuv'
    warning: no previously-included files matching 'ar-lib' found under directory 'deps
libuv'
    warning: no previously-included files matching 'aclocal.m4' found under directory '
eps\libuv'
    warning: no previously-included files matching 'compile' found under directory 'dep
\libuv'
    warning: no previously-included files matching 'configure' found under directory 'd
ps\libuv'
    warning: no previously-included files matching 'depcomp' found under directory 'dep
\libuv'
    warning: no previously-included files matching 'install-sh' found under directory '
eps\libuv'
    warning: no previously-included files matching 'libtool' found under directory 'dep
\libuv'
    warning: no previously-included files matching 'libuv.pc' found under directory 'de
s\libuv'
    warning: no previously-included files matching 'ltmain.sh' found under directory 'd
ps\libuv'
    warning: no previously-included files matching 'missing' found under directory 'dep
\libuv'
    writing manifest file 'C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadata-3ql
shei\gevent.egg-info\SOURCES.txt'
    creating 'C:\Users\Владимир\AppData\Local\Temp\pip-modern-metadata-3ql5shei\gevent.
ist-info'
    error: invalid command 'bdist_wheel'
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\владимир\appdata\local\program
\python\python39\python.exe' 'c:\users\владимир\appdata\local\programs\python\python39\
ib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C
\Users\18EE~1\AppData\Local\Temp\tmpcrgize8y' Check the logs for full command output.

Помогите, 2 час уже долбаюсь.

A: Вам нужно установить wheel -
pip install wheel

И далее -
python setup.py bdist_wheel

Референс -
https://stackoverflow.com/a/44862371/14230861


text:
Q: spring security - authorize pre-flighted request without oAuth token I am trying to authorize all preflight request in (/secure/**) without an authorization header(oauth token in my case). The JwkFilter is used to validate the oauth token passed in the authorization header.  Any suggestion, where I am going wrong here.
@Override
protected void configure(HttpSecurity http) throws Exception {

    JwtAuthFilter jwtAuthTokenFilter = new JwtAuthFilter(oauthConfig);
    jwtAuthTokenFilter.setAuthenticationManager(getAuthManager());

    http.cors().and().authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/secure/**")
            .permitAll();

    http.requiresChannel().anyRequest().requiresSecure().and()
            .addFilterBefore(requireProtocolFilter, ChannelProcessingFilter.class).sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().anonymous().disable().csrf().disable()
            .antMatcher("/**").authorizeRequests().anyRequest().permitAll().and()
            .antMatcher(/secure/**")
            .addFilterBefore(jwtAuthTokenFilter, BasicAuthenticationFilter.class).exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint()).and().authorizeRequests().anyRequest()
            .authenticated();

}

public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                .allowedMethods("*")
                .allowedOrigins("*");
        }
    };
}

A: For preflight request with CORS, according to spring, they will execute before your jwtAuthTokenFilter (registered before BasicAuthenticationFilter filter) -> correct
The order was specified here (in spring code):
FilterComparator() {
        Step order = new Step(INITIAL_ORDER, ORDER_STEP);
        ...
        put(CorsFilter.class, order.next());
        ...
        put(BasicAuthenticationFilter.class, order.next());
        ...
    }

In CORS, for complex request (like using custom header Authorization header in your case), browser will send preflight request first to know whether the server allow client to access their resource or not before sending actual request.
The CORSFilter will execute like this (in spring code):
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
        boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
        if (!isValid || CorsUtils.isPreFlightRequest(request)) {
            return;
        }
        filterChain.doFilter(request, response);
    }
}

They will check whether for every preflight request (extends OncePerRequestFilter) comes to server, if processRequest is valid or is preflight request to terminate the chain.
Here is the default processor to check preflight request (in spring code):
public class DefaultCorsProcessor implements CorsProcessor {

    @Override
    public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request,
            HttpServletResponse response) throws IOException {

        ...
        boolean preFlightRequest = CorsUtils.isPreFlightRequest(request);
        if (config == null) {
            if (preFlightRequest) {
                rejectRequest(new ServletServerHttpResponse(response));
                return false;
            }
            else {
                return true;
            }
        }
        return handleInternal(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response), config, preFlightRequest);
    }

In your case, I think you are missing configuring for enabling CORS.
So the server reject the client request (by sending HttpStatus.FORBIDDEN code), so that the browser don't send actual request to the server.
And your JwtAuthTokenFilter has no chance to execute.
You can refer to this post for configuring cors. Hope it helps

A: Adding the below snippet in to the jwkAuthFilter did the trick.
     if (CorsUtils.isPreFlightRequest(request)) {
        response.setStatus(HttpServletResponse.SC_OK);
        return;
    }


text:
Q: C# separation to tab separation How do I change the space separation to tab separation.
Because [ LD Port 02 CSTID F7SC67: Sorts Complete. ] has a lot of space separation.
So I can't split through Split !
List<string> add_list = new List<string>();
List<string> ok_list = new List<string>();
IEnumerable<String> lines = File.ReadLines("C:\\Users\\USER\\Downloads\\1231231231.log");

foreach (string line in lines)
{
    add_list.Add(line);
}

foreach (string row in add_list)
{
    var data = row.Split(' ');
    Console.WriteLine(data);
}

Edit (by @chase): OP does not want to split by just spaces - this is why their code is wrong. Their final outcome should be the one mentioned in What I want: - where each item is separated by a comma and each item is clearly distinct. The input to reach this outcome is mentioned in Data:

A: Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
         static void Main(string[] args)
        {
            List<List<string>> data = GetFixedWidth(FILENAME);
        }
         static List<List<string>> GetFixedWidth(string filename)
         {
             int[] startPosition = { 0, 6, 15, 24 };
             StreamReader reader = new StreamReader(filename);
             string line = "";
             int length = 0;
             List<List<string>> data = new List<List<string>>();
             while ((line = reader.ReadLine()) != null)
             {
                 line = line.Trim();
                 if(line.Length > 0)
                 {
                     List<string> rowList = new List<string>();
                     data.Add(rowList);
                     for (int i = 0; i < startPosition.Length; i++)
                     {
                         if (line.Length > startPosition[i])
                         {
                             if (i == startPosition.Length - 1)
                             {
                                 string lastColumn = line.Substring(startPosition[i]);
                                 if (lastColumn.Contains(":"))
                                 {
                                     string[] splitData = line.Substring(startPosition[i]).Split(new char[] { ':' });
                                     foreach (string split in splitData)
                                     {
                                         rowList.Add(split.Trim());
                                     }
                                 }
                                 else
                                 {
                                     rowList.Add(lastColumn);
                                 }
                             }
                             else
                             {
                                 length = startPosition[i + 1] - startPosition[i];
                                 rowList.Add(line.Substring(startPosition[i], length).Trim());
                             }
                         }
                     }
                 }
             }

             return data;
         }
    }

}


text:
Q: What do the options after a specific command mean? How do I understand what the various options/flags mean?
For example:
1) uname -a - What does -a denote here?
2) pyang -f - What does -f denote here?
I just want to understand if there is some reference/doc that tells the usage of these? Please clarify.

A: In UNIX/Linux Shells, there are four different types of commands:
1. executables: compiled binaries or scripts
2. shell builtin commands
3. shell functions
4. aliases

If you encounter an unknown command, the first thing is to check its type. Let's examine a few examples for each type:
type <command>  # indicates the commands type
--------------
type find       # find is /usr/bin/find   --> executables
type cd         # cd is a shell builtin
type dequote    # dequote is a function
type ls         # ls is aliased to 'ls --color=auto'

Having the information of the command type, you can get help, description and usage of the command and it's options:
<command> --help   # help for executables     -->  find --help
help <command>     # help for shell builtins  -->  help cd

man <command>      # manual page for the specific command

Following commands are useful for information gathering as well.
whatis <command>   # display a very brief description of the command
which <command>    # display an executables location

In the example above, ls is aliased, but what is ls really?
whatis ls
help ls      # doesn't work --> ls is not a shell builtin command
ls --help    # works        --> ls is an executable / compiled binary
which ls     # /bin/ls      --> ls is an executable / compiled binary

There are thousands of commands to explore:
ls /bin       # list a few executables
ls /usr/bin   # list more executables
enable -p     # list all available shell builtin commands
declare -f    # list all defined functions
alias         # list all defined aliases

Now let's examine the uname command:
type uname    # uname is /bin/uname   --> executable
whatis uname
which uname
uname --help  # see the meanings of the options, e.g. -a
man uname     # read the manual page for uname

Do the same for the pyang command...

A: With almost all Linux commands, I think the fastest and easiest first course of action is to append "--help" to the command.  This gives you a good summary, which is often enough.
If you need more details, the man command is a good second choice.
For example:
$ uname --help
Usage: uname [OPTION]...
Print certain system information.  With no OPTION, same as -s.

  -a, --all                print all information, in the following order,
                             except omit -p and -i if unknown:
  -s, --kernel-name        print the kernel name
  -n, --nodename           print the network node hostname
  -r, --kernel-release     print the kernel release
  -v, --kernel-version     print the kernel version
  -m, --machine            print the machine hardware name
  -p, --processor          print the processor type (non-portable)
  -i, --hardware-platform  print the hardware platform (non-portable)
  -o, --operating-system   print the operating system
      --help     display this help and exit
      --version  output version information and exit


text:
Q: Is there an way of implementing an minimum deceleration speed in an UIScrollView? I have an UIScrollView that contains some UIImageViews which are animated. It really only looks cool if there's a minimum scrolling speed happening. But when the user slowly scrolls and lifts the finger, the UIScrollView decelerates very slowly.
The problem is, that the scrollViewDidScroll method doesn't get called upon every offset change. It get's called by a kind of time interval as long as the offset is changing. The interval is always the same, regardless of how fast the user scrolls.

A: If we were allowed to talk about iPhone OS 3.0, somebody might be able to tell you that UIScrollView might have a new property called decelerationRate. But unfortunately we are not allowed to talk about iPhone OS 3.0 :(


text:
Q: Retrieve image for SharePoint - 401 error I get the 401 message when I try to get an image from a local SharePoint site.
Tried a number of credentials settings but they all return the same 401 error.
var SharePointURL = "http://SharePointServer/Site/ImageFolder/image1.jpg";
System.Net.WebRequest req = System.Net.WebRequest.Create(SharePointURL);
req.Credentials = System.Net.CredentialCache.DefaultCredentials;
req.UseDefaultCredentials = true;
System.Net.WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
stream.Close();

Any help would be appreciated.

A: I don't know why this is happening, but I can tell you what you can do to find out for yourself:
Assuming you are running your code on a different machine to the one you are running SharePoint on, you need to have Fiddler installed on your machine. Get that to intercept the request from your code and the same request from your browser. You should be able to see a difference between the requests, which will be useful to guide you as to what the cause of the problem is. You can also use Fiddler to try changing parameters so you can see which headers cause problems by their presence or absence.
If your code makes exactly the same request that your browser does, you will get exactly the same response.
If you find yourself still baffled after all of that, did you know that SharePoint has its own Stack Exchange.


text:
Q: Graduate-level reference on temporal point processes I am looking for a modern, graduate level, rigorous book on temporal point processes which also treats self-correcting point processes, and self-exciting point processes.
It would be even more interesting if the book was also pointing me to some research questions in the field.

A: You can briefly read a short introduction to decide whether you are interested in the theoretic side or application side of the research subject. Say Rasmussen's Notes.
If you are more interested in the theory, there is a two-volume standard text on theory of point processes. It includes a panoramic discussion on temporal/spatial process in Chap 14,15.

Daley, Daryl J., and David Vere-Jones. An introduction to the theory
  of point processes: volume I&II, 2ed, Springer, 2007.

If you are more interested in the application, there is a very popular book ABG discusses a variety of applications of point processes in survival analysis.

Aalen, Odd, Ornulf Borgan, and Hakon Gjessing. Survival and event
  history analysis: a process point of view. Springer Science & Business
  Media, 2008.


text:
Q: Why is jetpack compose animateDpAsState not working? I have a box, and I want to animate its width by using animateDpAsState.

Box(modifier = modifier)
{
     val animatedDpState by animateDpAsState(
     targetValue = vm.animateWidthTargetState,
     tween(3000))

     // box with animated width
     Box(
     modifier = Modifier
     .fillMaxHeight()
     .width(animatedDpState)
     .background(Color.Red))

}

In my viewModel, I have this animateWidthTargetState:
var animateWidthTargetState by mutableStateOf(0.dp)

And somewhere else I changed the value of animateWidthTargetState to that of my screenWidth by clicking a button:
vm.animateWidthTargetState = screenWidth // let's say screenWith = 360.dp

The problem is that the value of animatedDpState becomes 360.dp the instant I clicked on my button, causing the width of my box to become 360.dp instantly. It seemed that no calculation even happened and animateDpAsState was not working.
What should I do to fix it?


text:
Q: Change Laravel Session Driver from Cookie to Database I would like to change the Laravel Session Driver. The application is already up and running.  There is a helper class with getters and setters and modifiers that accesses the session.
My question
How do I change the driver from cookie to database? What is the correct procedure to change the session driver from cookie to database?

A: According to question comments you have to follow the steps in documentation, then change the SESSION_DRIVER in .env file to the database


text:
Q: To what extent does rust compiler auto match generic constraint? Consider the following code for binary tree
#[derive(Debug)]
struct Binary_Tree_Node<T: PartialOrd + Clone> {
    left: Binary_Tree<T>,
    value: T,
    right: Binary_Tree<T>
}

#[derive(Debug)]
struct Binary_Tree<T: PartialOrd + Clone> {
    node: Option<Box<Binary_Tree_Node<T>>>
}

impl <T: PartialOrd + Clone>Binary_Tree<T> {
    fn new(value_to_insert: T) -> Binary_Tree<T> {
        Binary_Tree{node:
            Some(
                Box::new(
                    Binary_Tree_Node{
                        left: Binary_Tree{node: None},
                        value: value_to_insert,
                        right: Binary_Tree{node: None}
                    }
                )
            )
        }
    }

    fn map<F, U>(&self, f: F) -> Option<U>
    where F: FnOnce(&Binary_Tree_Node<T>) -> U {
        self.node.as_ref().map(|node| f(&**node))
        // equivalent
        //self.node.as_ref().map(|node| f(node))
    }
}
let mut test1 = Binary_Tree::new(10);
println!("{:#?}", test1.map(|node| node.value < 2));

This line confuses me
self.node.as_ref().map(|node| f(node))

as I expect rust to throw compiler error
self.node is of type Option<Box<Binary_Tree_Node<T>>>
self.node.as_ref() is of type Option<&Box<Binary_Tree_Node<T>>>
node in self.node.as_ref().map(|node| f(node)) is of type &Box<Binary_Tree_Node<T>>
&Box<Binary_Tree_Node<T>> is not equivalent to the generic constraint &Binary_Tree_Node<T>
The question is why both self.node.as_ref().map(|node| f(&**node)) and self.node.as_ref().map(|node| f(node)) work?

A: This is a "Deref coercion", see nomicon Coercions:

Coercion is allowed between the following types:

*

*[...]

*Deref coercion: Expression &x of type &T to &*x of type &U if T derefs to U (i.e. T: Deref<Target=U>)

Box<T> implements Deref<Target=T>, so &Box<T> coerces automatically to &T like you'd have written &*node.
(I'm not sure what the & in "Expression &x" part is for, because we don't have a & at coercion site and it still works - could be a typo or a bug)
Also works from &String to &str: Playground
fn foo<T>(_v: T) {}

fn main() {
    {
        let v: &Box<i32> = &Box::new(5i32);
        foo::<&i32>(v);
        foo::<&i32>(&*v);
    }

    {
        let v: &String = &String::from("abc");
        foo::<&str>(v);
        foo::<&str>(&*v);
    }
}


text:
Q: Why is one div higher than the other? I have these two divs floated to the left but for some reason one is coming out higher than the other What's causing this?

CheckoutSummary

        Shipping To:

@Model.ShippingAddress.Street

@Model.ShippingAddress.City, @Model.ShippingAddress.State @Model.ShippingAddress.Zip

@Html.DisplayFor(m => m.ShippingAddress.Phone1)

        Billing To:

@Model.BillingAddress.Street

@Model.BillingAddress.City, @Model.BillingAddress.State @Model.BillingAddress.Zip

@Model.BillingAddress.Phone1

A: You have a margin around .address-summary that's pushing the div down.

A: this
 .address-summary {
        float: left;
        margin: 10px;  <<<<<
    }

It's adding a margin of 10px on all edges of the div (including the top).
The way margin and padding are written is:
margin: top right down left;

e.g.
/* Div has 10px margin all around: */
margin: 10px;

/* Applies 10px to top and bottom margin, and 15px to left and right margins: */
margin: 10px 15px;

/* Applies 10px margin to top, 15px to both left and right, and 12px to bottom: */
margin: 10px 15px 12px;

/* Apples 10px to top, 15px to right, 12px to bottom, and 13px to left: */
margin: 10px 15px 12px 13px;

A: because your margin: 10px;
with margin you do in all front your div
use this
margin-left: 10px;
margin-right: 10px;


text:
Q: Converge in distribution with unbounded moment I guess that convergence in distribution does not mean that the moments must be bounded. I need to find a toy example that confirm the above idea.
Mathematically, I want to find a sequence $\{X_n\}$ that each $X_n \xrightarrow{d} N(0,1) $ as $n \rightarrow \infty$  but $E\{ |X| \} = \infty$. (Here, $N(,)$ is normal distribution and $\xrightarrow{d}$ is convergence in distribution).


text:
Q: Как поменять шрифт кроме иконок? На сайте используется несколько шрифтов, нужно установить один, к примеру Montserrat, кроме иконок (на сайте так же есть inline стили, которые имеют различные значения для font-family).
Если добавить это правило:
body * {
    font-family: Montserrat, sans-serif !important;
}

то шрифт поменяет также и FontAwesome иконки. Как сделать чтобы поменялся шрифт только для текста, кроме иконок?
Пытался сделать так:
body *:not(::before) {
    font-family: Montserrat, sans-serif !important;
}

но это не работает.

A: Используйте селектор, который позволит не применять правило к элементам, в которых объявлен либо класс .fa, либо предполагаемо содержится какой-либо класс, содержащий fa-
Однако будьте осторожны: к примеру, класс .2fa-input будет соответствовать селектору [class*="fa-"]).
/* для тех элементов, у которых не объявлен класс `.fa`,
   но объявлен какой-нибудь другой: к примеру, .fa-camera-retro */
body :not(.fa):not([class*="fa-"]) {
    font-family: "Montserrat", sans-serif !important;
}

Изменено: font-awesome.css содержит класс .fa, в котором определяется шрифт. Без него остальные классы, связанные с иконками, не имеют смысла, поэтому селектор можно сократить.
body :not(.fa) {
    font-family: "Montserrat", sans-serif !important;
}


text:
Q: Display all parameters of an estimator including defaults I am using Watson Studio and using a markdown notebook.  In the notebook, I write the code:
from sklearn.tree import DecisionTreeClassifier
Tree_Loan= DecisionTreeClassifier(criterion="entropy", max_depth = 4)
Tree_Loan

and it displays
DecisionTreeClassifier(criterion='entropy', max_depth=4)

However, it should display something in the form of (this is from a different lab I've done using Skills Network Labs):
DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=4,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='best')

The best I can tell is that it is not importing the decision tree classifier.  I have the same problem with svm from sklearn.  Other functions in scikit-learn like train test split and k nearest neighbors work fine.  A classmate says the rest of my code is correct and there is no reason for the error.  What might be causing it?

A: It is importing the DecisionTreeClassifier, no problem there. But by default, sklearn prints only the parameters that were given to estimator with non-default values, from this function.
But if you want to see the "full" output, you can set the configuration of print_changed_only to False via sklearn._config.set_config like so:
>>> from sklearn.tree import DecisionTreeClassifier
>>> tree = DecisionTreeClassifier(criterion="entropy", max_depth=4)

>>> # only displays the changed parameters
>>> tree
DecisionTreeClassifier(criterion='entropy', max_depth=4)

>>> from sklearn._config import get_config, set_config

>>> # default setting
>>> get_config()["print_changed_only"]
True

>>> # now changing it
>>> set_config(print_changed_only=False)

# now we get the default values, too
>>> tree

DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='entropy',
                       max_depth=4, max_features=None, max_leaf_nodes=None,
                       min_impurity_decrease=0.0, min_impurity_split=None,
                       min_samples_leaf=1, min_samples_split=2,
                       min_weight_fraction_leaf=0.0, presort='deprecated',
                       random_state=None, splitter='best')