text:
Q: Add link panel tabs in Shiny with various top level navigation bars I'm trying to create links withing navbar in a Shiny app. I found the following code at A gist of programatically changing panel tabs in Shiny. It works great for the first navigation panel, but for the second it doesn't work. Here is my ui.R:
require(shiny)

shinyUI(navbarPage("",
                   tabPanel("Foo",
                            tabsetPanel(
                              tabPanel("Foo1",
                                       sidebarLayout(
                                         sidebarPanel(
                                           tags$div(div(id="Foo2", tags$a("Foo2"))
                                           )
                                             ),
                                         mainPanel(p("hello Foo1"))
                              )),
                              tabPanel("Foo2",
                                       sidebarLayout(
                                         sidebarPanel(),
                                         mainPanel(p("hello Foo2"))),
                                         HTML("<script>$('#Foo2').click(function() {
                                                        tabs = $('.tabbable .nav.nav-tabs li')
                                                         tabs.each(function() {
                                                            $(this).removeClass('active')
                                                         })
                                                         $(tabs[1]).addClass('active')

                                                         tabsContents = $('.tabbable .tab-content .tab-pane')
                                                         tabsContents.each(function() {
                                                            $(this).removeClass('active')
                                                         })
                                                         $(tabsContents[1]).addClass('active')

                                                        $('#Foo2').trigger('change').trigger('shown');

                                                     })</script>")
                                       )
                              )
                                ),
                   tabPanel("Bar",
                            tabsetPanel(
                              tabPanel("Bar1",
                                       sidebarLayout(
                                         sidebarPanel(
                                           tags$div(div(id="Bar2", tags$a("Bar2"))
                                           )
                                         ),
                                         mainPanel(p("hello Bar1"))
                                       )),
                              tabPanel("Bar2",
                                       sidebarLayout(
                                         sidebarPanel(),
                                         mainPanel(p("hello Bar2"))),
                                       HTML("<script>$('#Bar2').click(function() {
                                                        tabs = $('.tabbable .nav.nav-tabs li')
                                                         tabs.each(function() {
                                                            $(this).removeClass('active')
                                                         })
                                                         $(tabs[1]).addClass('active')

                                                         tabsContents = $('.tabbable .tab-content .tab-pane')
                                                         tabsContents.each(function() {
                                                            $(this).removeClass('active')
                                                         })
                                                         $(tabsContents[1]).addClass('active')

                                                        $('#Bar2').trigger('change').trigger('shown');

                                                     })</script>")
                              )
                            )
                   )
                   )
)

When you click in the sidebar panel of foo1 the link to foo2 responds. But when you do the same in Bar, it goes somewhere else.

A: Here you are the solution ;) .
require(shiny)
shinyUI(navbarPage("",
            tabPanel("Foo",
               tabsetPanel(
                    tabPanel("Foo1",
                              sidebarLayout(
                                  sidebarPanel(tags$div(div(id="Foo2", tags$a("Foo2")))),
                                  mainPanel(p("hello Foo1")))
                     ),
                     tabPanel("Foo2",
                               sidebarLayout(
                                   sidebarPanel(),
                                   mainPanel(p("hello Foo2"))),
                                   HTML("<script>$('#Foo2').click(function() {
                                        tabs = $('.tabbable .nav.nav-tabs li')
                                        tabs.each(function() {
                                        $(this).removeClass('active')
                                        })
                                        $(tabs[1]).addClass('active')

                                        tabsContents = $('.tabbable .tab-content .tab-pane')
                                        tabsContents.each(function() {
                                        $(this).removeClass('active')
                                        })
                                        $(tabsContents[1]).addClass('active')

                                        $('#Foo2').trigger('change').trigger('shown');

                                        })</script>")
                                   )
                          )
                        ),
            tabPanel("Bar",
               tabsetPanel(
                     tabPanel("Bar1",
                               sidebarLayout(
                                   sidebarPanel(tags$div(div(id="Bar2",tags$a("Bar2")))),
                               mainPanel(p("hello Bar1"))
                                   )),
                     tabPanel("Bar2",
                               sidebarLayout(
                                   sidebarPanel(),
                                   mainPanel(p("hello Bar2"))),
                                   HTML("<script>$('#Bar2').click(function() {
                                        tabs = $('.tabbable .nav.nav-tabs li')
                                        tabs.each(function() {
                                        $(this).removeClass('active')
                                        })
                                        $(tabs[3]).addClass('active')

                                        tabsContents = $('.tabbable .tab-content .tab-pane')
                                        tabsContents.each(function() {
                                        $(this).removeClass('active')
                                        })
                                        $(tabsContents[3]).addClass('active')

                                        $('#Bar2').trigger('change').trigger('shown');

                                        })</script>")

                          )
                          )
                        )
                        )
                          )


text:
Q: Android: How can I add childs to my custom ViewGroup with a CursorAdapter? Please help! I tried everything! :(
I've got a schedule Class, which is simply a custom ViewGroup (with custom onMeasure() and onLayout()), which enables me to place childs(=events) with LayoutParams for column/row start and column/row end. The number of childs and their LayoutParams depend on database entries.
Now I'm trying to add childs (events) from my database. I'd have to use a Cursor Adapter, so my schedule Class has to extend ListView, right? I tried that but the newView() method of the adapter is never called. Why not??
My custom ListView doesn't ask the adapter for childs, no childs are added. I also can't add the childs by hand calling schedule.addView() if I extend from AdapterView.
I'd be really (really) happy if someone could help!
Regards,
cody
This is my custom ViewGroup:
public class Schedule extends ViewGroup {
private int columns;
private int rows;
private float preferredCellWidth;
private float preferredCellHeight;
private String[] rowTimes;
private Paint paint;

public Schedule(Context context, int columns, int rows, float preferredCellWidth, float preferredCellHeight, String[] rowTimes) {
    super(context);
    this.columns = columns;
    this.rows = rows;
    this.preferredCellWidth = preferredCellWidth;
    this.preferredCellHeight = preferredCellHeight;
    this.rowTimes = rowTimes;
    init(context);
}

private void init(Context context) {
    Log.i("Schedule", "initSchedule...");
    setPaint();
    setWillNotDraw(false);
}

private void setPaint() {
    paint = new Paint();
    paint.setTextSize(preferredCellHeight*2/3);
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(getResources().getColor(R.color.white));
}

public Schedule(Context context, AttributeSet attrs) {
    super(context, attrs);
    readAttr(context, attrs);
    init(context);
}

public Schedule(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    readAttr(context, attrs);
    init(context);
}

private void readAttr(Context c, AttributeSet attrs) {
    android.content.res.TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ScheduleLayout);
    this.columns = a.getInt(R.styleable.ScheduleLayout_columns, 1);
    this.rows = a.getInt(R.styleable.ScheduleLayout_rows, 1);
    this.preferredCellWidth = a.getDimension(R.styleable.ScheduleLayout_preferredCellWidth, 1);
    this.preferredCellHeight = a.getDimension(R.styleable.ScheduleLayout_preferredCellHeight, 1);
    a.recycle();
}

@Override
protected void onDraw(Canvas canvas) {
    //Log.i(this.toString(),"onDraw ..."+" this.getLeft()="+this.getLeft()+", this.getWidth()="+this.getWidth());
    super.onDraw(canvas);
    for (int i = 0; i < rows; i++) {
        int line = (int) Math.round(this.getTop()+ (i+1) * preferredCellHeight);
        canvas.drawText(this.rowtimes[i], this.getLeft()+5, line-3, paint);
        canvas.drawLine(this.getLeft(), line, this.getWidth(), line, paint);
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Log.i("Schedule", "onMeasure...");
    float width = (MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight()) / columns;
    float height = (MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom()) / rows;
    float cellWidth = preferredCellWidth;
    float cellHeight = preferredCellHeight;

    if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) {
        cellWidth = width;
    } else if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) {
        cellWidth = Math.min(preferredCellWidth, width);
    }

    if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
        cellHeight = height;
    } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) {
        cellHeight = Math.min(preferredCellHeight, height);
    }

    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        if (child.getVisibility() != GONE) {
            LayoutParams lp = (LayoutParams) child.getLayoutParams();
            int cwidth = (int) Math.round(cellWidth * lp.getWidth());
            int cheight = (int) Math.round(cellHeight * lp.getHeight());
            child.measure(
                    MeasureSpec.makeMeasureSpec(cwidth, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(cheight, MeasureSpec.EXACTLY)
            );
        }
    }
    setMeasuredDimension(
            (int) Math.round(cellWidth * columns + getPaddingLeft() + getPaddingRight()),
            (int) Math.round(cellHeight    * rows + getPaddingTop() + getPaddingBottom())
    );
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if (!changed)
        return;

    int cellWidth = ((r-l) - getPaddingLeft() - getPaddingRight()) / columns;
    int cellHeight = ((b-t) - getPaddingTop() - getPaddingBottom()) / rows;

    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);

        if (child.getVisibility() != GONE) {
            LayoutParams lp = (LayoutParams) child.getLayoutParams();
            int cl = (int) Math.round(getPaddingLeft() + lp.columnStart    * cellWidth);
            int cr = (int) Math.round(getPaddingLeft() + lp.columnEnd * cellWidth);
            int ct = (int) Math.round(getPaddingTop() + lp.rowStart    * cellHeight);
            int cb = (int) Math.round(getPaddingTop() + lp.rowEnd * cellHeight);
            child.layout(cl, ct, cr, cb);
        }
    }
}

protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {
    Log.i("Schedule", "checkLayoutParams...");
    if (p instanceof LayoutParams) {
        LayoutParams lp = (LayoutParams) p;
        if (lp.columnEnd > columns || lp.columnStart < 0)
            return false;
        if (lp.rowEnd > rows || lp.rowStart < 0)
            return false;
        return lp.columnEnd > lp.columnStart && lp.rowEnd > lp.rowStart;
    } else
        return false;
}

public android.widget.AbsListView.LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new android.widget.AbsListView.LayoutParams(getContext(), attrs);
}

public static class LayoutParams extends android.view.ViewGroup.LayoutParams {
    public int columnStart;
    public int columnEnd;
    public int rowStart;
    public int rowEnd;

    public LayoutParams(int columnStart, int rowStart, int columnEnd, int rowEnd) {
        super(WRAP_CONTENT, WRAP_CONTENT);
        this.columnStart = columnStart;
        this.columnEnd = columnEnd;
        this.rowStart = rowStart;
        this.rowEnd = rowEnd;
    }

    public LayoutParams(Context c, AttributeSet attrs) {
        super(WRAP_CONTENT, WRAP_CONTENT);
        android.content.res.TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.EventLayout);
        this.columnStart = a.getInt(R.styleable.EventLayout_event_columnStart, 0);
        this.columnEnd = a.getInt(R.styleable.EventLayout_event_columnEnd,    this.columnStart + 1);
        this.rowStart = a.getInt(R.styleable.EventLayout_event_rowStart, 0);
        this.rowEnd = a.getInt(R.styleable.EventLayout_event_rowEnd, this.rowStart + 1);
        a.recycle();
    }

    public int getWidth() {
        return columnEnd - columnStart;
    }

    public int getHeight() {
        return rowEnd - rowStart;
    }
}

And this is the event-layout - event.xml:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
android:gravity="center" >

    <TextView android:id="@+id/text_event_name"
    style="@style/Event_TextView1" />

    <TextView android:id="@+id/text_event_name2"
    style="@style/Event_TextView2" />

</LinearLayout>

<TextView android:id="@+id/text_event_weeks"
style="@style/Event_TextView2"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />

<TextView android:id="@+id/text_event_room"
style="@style/Event_TextView2"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />

In my Activity I've got that code:
Schedule schedule = new Schedule(this, 4, rowTimes.length, 15, 15, rowTimes);

Cursor cursor = dbManager.getEvents(day);
MySimpleCurserAdapter adapter = ... ??
// schedule.setAdapter not working...
How can I add events to the schedule with the data from the cursor?

A: You should not need to be extending ListView.  You just want to add an instance of ListView to your layout.
It sounds like you might want to be using a SimpleCursorAdaptor, where you can map items in your custom view to the data model objects you want them to display.
See Binding to Data with Adapter and Hello ListView for some examples of the right ways to use adapters and ListViews.

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS Facebook SDK - Best Practices? I was wondering what the "best practice" guidelines are for using the Facebook iOS SDK.
Specifically - I have several forms that use the Facebook SDK.
My initial instinct as an OOP programmer was to create a "FacebookManager" class under my data-access-layer which handles all Facebook activity.
Unfortunately since Facebook iOS SDK uses delegates and async methods, this is not so helpful since any other module using FacebookManager would have to pass in delegates for all responses anyway.
Then I figured that each ViewController would be a FBRequestDelegate by itself and handle all Facebook responses.
So, how do you do it in your app?

A: What I've done is to create a FacebookManager as you suggested.  This manager becomes the FBRequestDelegate.  Now I prefer blocks to the delegation model so all my FacebookManager methods are block based.
Here is what my post to a user's wall method looks like
- (void)postToUserWall:(NSDictionary*)postDictionary withCompleteHandler:(void(^)(id result, NSError* error))block {

  if( [facebook_ isSessionValid] ) {
    NSMutableDictionary* params = [postDictionary mutableCopy];
    [params setObject:facebook_.accessToken forKey:@"access_token"];
    FBRequest* request = [facebook_ requestWithGraphPath:@"me/feed" andParams:[postDictionary mutableCopy] andHttpMethod:@"POST" andDelegate:self];
    [[request params] setObject:block forKey:@"result"];
  }

}

Then on a success or error I just execute the block
- (void)processRequest:(FBRequest*)request withResult:(id)result andError:(NSError*)error {
  NSDictionary* params = [request params];
  if( [request params] != nil && [params objectForKey:@"result"] != nil ) {
    void(^completeBlock)(id result,NSError* error) = [params objectForKey:@"result"];
    completeBlock(result, nil);
  }
}

- (void)request:(FBRequest *)request didLoad:(id)result {
  [self processRequest:request withResult:result andError:nil];
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
  [self processRequest:request withResult:nil andError:error];
}

I wish there was a better way to deal with the block but that's the best one I have found so far.  Is this the best way to do it? Probably not but that's what I currently use and it seems to be ok, keeping all the FB interaction away from my View Controllers.
Note all the code here assumes ARC that's why there are no releases

A: A Facebook manager, basically a wrapper over Facebook sdk is the way to go. Here are a few tips on how to manage it.
1) Modify Facebook SDK's protocol definitions and make the ones you don't need as optional so you won't have to implement them.
2) Handle all session activities, login/logout, delegates, protocols, etc in this manager class. In other words, this manager implements all protocols defined by the Facebook sdk.
3) Define your own protocol in manager class and make all protocol methods optional, so every view controller can define what it actually needs.
4) Some helpful wrappers would be useful, like,
- (void) postToFriend: (Record*) f_record withMessage: (NSString*) message;
- (void) resumeSession; // checks, resumes session, extend token, or report error

5)  It would be easy to add wrappers if you need more features for your viewControllers
A lot of open source code is available (search github) but a custom manager class is not difficult to write and can be easily ported to other projects.
Hope it helps.

A: We have built a fairly extensive library ready to use for facebook integration. See here:
https://github.com/RIKSOF/three20/tree/development/src/extThree20Facebook
Its an extension on Three20 framework. You can easily modify this library to be independent of Three20, if you like.
We basically have defined objects for each Graph API object. JSON returned from the Graph API is read in to these objects.


text:
Q: sketchup c++ api reading skp file I'd like to open a sketchup model in c++. I downloaded the sdk, compiled the example, however, when I try to run it, it doesn't read any face, model name, nothing. Could someone help me with?
SUInitialize();
// Load the model from a file
SUModelRef model = SU_INVALID;
SUResult res = SUModelCreateFromFile(&model, "model.skp");
if (res != SU_ERROR_NONE)
{
    std::cout << "error" << std::endl;
    return 1;
}
// Get the entity container of the model.
SUEntitiesRef entities = SU_INVALID;
SUModelGetEntities(model, &entities);

size_t faceCount = 0;
SUEntitiesGetNumFaces(entities, &faceCount);

// faceCount = 0..., why???!!!

A: This will return the number of faces only in the root of the model, not those inside any component or group. Does model.skp have free faces? (i.e. not inside a component)


text:
Q: showing wordpress footer on a non-wordpress website I wanted to ask a quick question. I have two websites running on the same domain. The homepage is in complete HTML and it can be accessed by going to http://xyz.com/home while as for the inner pages, I have installed wordpress on the same domain and the pages can be accessed by going to http://xyz.com/sample-page. Now I have created a footer in wordpress and it's appearing correctly on the inner pages which is running wordpress but i want to show that very same footer on my HTML page too which isn't running wordpress. To do this, I added the following code to the index.php file of my homepage:

<?php include '../wp-content/themes/metro/footer.php'; ?>

Doing so is now showing me this error on the homepage:
Fatal error: Call to undefined function get_option() in /homepages/12/d378078258/htdocs/txtimpact-main/wp-content/themes/metro/footer.php on line 1

Can anybody please let me know that how can I modify the footer.php file so that the footer starts to appear on my homepage. I read a tutorial on the internet where the guy told to add this piece of code to the footer.php file but it didn't help in my case:
require( '../my_wordpress_install_root/wp-load.php' );

This is the code why my footer.php file contains:
<?php $options = get_option('metro'); ?>

                <?php widgetized_footer(); ?>

    <h12><?php mts_copyrights_credit(); ?></h12>

Copyright © 2006-12 TXTImpact - All Rights Reserved.
Message and Data Rates may apply.
To unsubscribe, text 'STOP' to 27126 or Contact Support.
Powered by Wire2Air
Proudly Made In NYC

<?php mts_footer(); ?>
<?php wp_footer(); ?>

A: Your homepage http://xyz.com/home can't use WordPress functions (if you want them you have to include them manually). I advise you to use WordPress in showing homepage. WordPress have setting to show specific page as homepage.
Quote from the WordPress codex:

What Template is Used to Display a Particular Page?
  WordPress looks for several Page template files in your active WordPress Theme based upon the Template Hierarchy. The first one it finds will be used to display any given Page. WordPress will look for files in the following order:

The Page's selected "Page Template"
page.php
index.php
The WordPress Template Hierarchy also recognizes specific Pages or Posts automatically without the need to assign them to a specific Page template file. If the Page with ID or slug in the template file name is created by the user, the appropriate Page template file is automatically used.
page-{id}.php
page-{slug}.php
If the Page ID number is 42, the page-42.php template file is automatically used. If the Page slug is "About", the page-about.php template file is used.

A: Supposing that the following file, http://example.com/connect-wp.php is located at the same level as WordPress root files (http://example.com/):
<?php
define( 'WP_USE_THEMES', false );
require( './wp-load.php' );

// Optional, maybe necessary for logged in users
// add_filter( 'show_admin_bar', '__return_false' );

include get_stylesheet_directory() . '/footer.php';

Of course, what comes before footer.php in your custom file must match the HTML structure that the footer will create.
References:

*

*get_stylesheet_directory

*What is the constant WP_USE_THEMES for?

*Integrating WordPress with Your Website


text:
Q: Problem with reset button that I created in shiny code In the shiny code below I created a reset button, but it just deletes the graph that is generated on the screen and doesn't do anything for the chosen date and category. So I would like some help with this: ie when I press reset, I would not want any date/category to be selected ie the fields would be left empty. Is it possible to do that?
Executable code below:
library(shiny)
library(shinythemes)
library(dplyr)
library(tidyverse)
library(lubridate)
library(stringr)

function.test<-function(){

  df1 <- structure(
    list(date1= c("2021-06-28","2021-06-28","2021-06-28","2021-06-28"),
         date2 = c("2021-07-01","2021-07-01","2021-07-02","2021-07-03"),
         Category = c("FDE","ABC","FDE","FDE"),
         Week= c("Friday","Monday","Wednesday","Wednesday"),
         DR1 = c(4,1,1,6),
         DR01 = c(4,1,1,3), DR02= c(4,2,2,4),DR03= c(9,5,5,2),
         DR04 = c(5,4,3,4),DR05 = c(5,4,2,4),
         DR06 = c(2,4,2,4),DR07 = c(2,5,4,2),
         DR08 = c(3,4,2,4),DR09 = c(2,3,4,2)),
    class = "data.frame", row.names = c(NA, -4L))

  return(df1)
}

f1 <- function(df1, dmda, CategoryChosse) {

  x<-df1 %>% select(starts_with("DR0"))

  x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV")))
  PV<-select(x, date2,Week, Category, DR1, ends_with("PV"))

  med<-PV %>%
    group_by(Category,Week) %>%
    summarize(across(ends_with("PV"), median))

  SPV<-df1%>%
    inner_join(med, by = c('Category', 'Week')) %>%
    mutate(across(matches("^DR0\\d+$"), ~.x +
                    get(paste0(cur_column(), '_PV')),
                  .names = '{col}_{col}_PV')) %>%
    select(date1:Category, DR01_DR01_PV:last_col())

  SPV<-data.frame(SPV)

  mat1 <- df1 %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(starts_with("DR0")) %>%
    pivot_longer(cols = everything()) %>%
    arrange(desc(row_number())) %>%
    mutate(cs = cumsum(value)) %>%
    filter(cs == 0) %>%
    pull(name)

  (dropnames <- paste0(mat1,"_",mat1, "_PV"))

  SPV <- SPV %>%
    filter(date2 == dmda, Category == CategoryChosse) %>%
    select(-any_of(dropnames))

  datas<-SPV %>%
    filter(date2 == ymd(dmda)) %>%
    group_by(Category) %>%
    summarize(across(starts_with("DR0"), sum)) %>%
    pivot_longer(cols= -Category, names_pattern = "DR0(.+)", values_to = "val") %>%
    mutate(name = readr::parse_number(name))
  colnames(datas)[-1]<-c("Days","Numbers")

  if(as.Date(dmda) < min(as.Date(df1$date1))){
    datas <- datas %>%
      group_by(Category) %>%
      slice(1:max(Days)+1) %>%
      ungroup
  }else{
    datas <- datas %>%
      group_by(Category) %>%
      slice((as.Date(dmda) - min(as.Date(df1$date1) [
        df1$Category == first(Category)])):max(Days)+1) %>%
      ungroup
  }

  plot(Numbers ~ Days,  xlim= c(0,45), ylim= c(0,30),
       xaxs='i',data = datas,main = paste0(dmda, "-", CategoryChosse))

  model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port")

  new.data <- data.frame(Days = with(datas, seq(min(Days),max(Days),len = 45)))
  new.data <- rbind(0, new.data)
  lines(new.data$Days,predict(model,newdata = new.data),lwd=2)
  coef<-coef(model)[2]
  points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)
  text(.99,coef + 1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")

}

ui <- fluidPage(

  ui <- shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                          br(),

                          tabPanel("",
                                   sidebarLayout(
                                     sidebarPanel(

                                       uiOutput("date"),
                                       uiOutput("mycode"),
                                       actionButton("reset", "Reset"),

                                       br(),

                                     ),

                                     mainPanel(
                                       tabsetPanel(
                                         tabPanel("", plotOutput("graph",width = "100%", height = "600")
                                         )
                                       ),
                                     ))
                          )))

server <- function(input, output,session) {

  data <- reactive(function.test())

  output$date <- renderUI({
    req(data())
    all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
    disabled <- as.Date(setdiff(all_dates, as.Date(data()$date2)), origin = "1970-01-01")
    dateInput(input = "date2",
              label = h4("Data"),
              min = min(data()$date2),
              max = max(data()$date2),
              value = min(data()$date2),
              format = "dd-mm-yyyy",
              datesdisabled = disabled)

  })

  output$mycode <- renderUI({
    req(input$date2)
    df1 <- data()
    df2 <- df1[as.Date(df1$date2) %in% input$date2,]
    selectInput("code", label = h4("Category"),choices=unique(df2$Category))
  })

  output$graph <- renderPlot({
    req(input$date2,input$code)
    f1(data(),as.character(input$date2),as.character(input$code))
  })

  observeEvent(input$reset, {
    output$graph <- renderPlot(plot.new())

    output$date <- renderUI({
      req(data())
      all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
      disabled <- as.Date(setdiff(all_dates, as.Date(data()$date2)), origin = "1970-01-01")
      dateInput(input = "date2",
                label = h4("Data"),
                min = min(data()$date2),
                max = max(data()$date2),
                value = min(data()$date2),
                format = "dd-mm-yyyy",
                datesdisabled = disabled)

    })
  })

}

shinyApp(ui = ui, server = server)

I did this way, but just cleared the graph and category, the date didn't.
  observeEvent(input$reset, {
    output$graph <- renderPlot(plot.new())
    updateDateInput(session, 'date2', value = min(data()$date2))
    updateSelectInput(session, 'code', choices=character(0), selected=character(0))
    })

A: If you use the library shinyjs it could be pretty easy. This is based on an answer given by @DeanAttali.
In your server call, in the function observeEvent(), remove the ouput$graph call and replace it with reset("side-panel") (in addition to calling the library shinyjs). It doesn't reset the Category. It does reset the Data (the date field with the label Data).
  observeEvent(input$reset, {
    reset("side-panel")

    output$date <- renderUI({
      req(data())
      all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
      disabled <- as.Date(setdiff(all_dates, as.Date(data()$date2)), origin = "1970-01-01")
      dateInput(input = "date2",
                label = h4("Data"),
                min = min(data()$date2),
                max = max(data()$date2),
                value = min(data()$date2),
                format = "dd-mm-yyyy",
                datesdisabled = disabled)

    })
  })

A: The following should do it.  It requires a bit more checking...
  my <- reactiveValues(plot=NULL)
  output$graph <- renderPlot({
    if (!is.null(input$date2) & !is.null(input$code)) {
      my$plot <- f1(data(),as.character(input$date2),as.character(input$code))
    }else {
      my$plot <- NULL
    }
    my$plot
  })

  observeEvent(input$reset, {
    df1 <- data()
    my$plot <- NULL
    updateDateInput(session, 'date2', value = NA)
    updateSelectInput(session, 'code', h4("Category"),choices= unique(df1$Category), selected=character(0))
  })


text:
Q: random number generator on the basis of integer or float I have an 2D array
b=[[1,100],[0.0,0.8],[11,111],[0.8,0.999],[11,111],[16,256],[1,10]]

which contain both integer and floating point numbers. I want to select a random number. I am going through loop:
for i in range(6):
   aa=b[i][0]
   bb=b[i][1]
   a[i]=rand(aa,bb)
   print(a[i])

Now I want to select random number from range in "variable" and when its integer, it select a random from integer number and whens its float it select random float number from range in "b".
I have seen functions, either they return float or integer random number but not both.

A: This will generate a list of random numbers that are integers or floats according to the contents of the ranges in b:
[(random.randrange if isinstance(lower, int)
  else random.uniform)(lower, upper)
 for lower, upper in b]

Here we simply choose to use random.randrange if we encounter an integer, otherwise we use random.uniform

A: *

*Build a custom method which accepts the range parameter.

*If the range is integer, just generate random number in the range.

*If the range is float, convert the range into integer i.e. [0.8,0.999] becomes 800,999 with factor multiplication of 10^3 ( or you can use 10^4 for higher precision). Generate a random integer between 800-999, say 856, divide it be multiplication factor used for float --> integer conversion, which would be 10^3 in this case, so your random float is 0.856.

*The decision of how big multiplication factor to use would lie in what level of decimal precision your float range is.


text:
Q: Remplazar el contenido de varios divs con varios callbacks en PHP Estoy intentado remplazar el contenido que hay dentro de varios divs con varios callbacks. El nombre de los callbacks que quiero usar están dentro de esos divs:
function googlemaps(){
    return 'Google Maps muestra su contenido'
}

function socialicons(){
    return 'Social Icons muestra su contenido';
}

function callaction(){
    return 'Call Action hace sus cosas y muestra su contenido';
}

$builder = '

[moz_widget]googlemaps[/moz_widget]

moz_widget]videos[/moz_widget

[moz_widget]postsgrid[/moz_widget]

';

$builder = preg_replace_callback('/(
]*>)(.*?)(<\/div>)/i', function($matches) {
    $matches[0]();
}, $builder);

El resultado que recibo tras ejecutar el código es un fatal error :

Fatal error: Call to undefined function [moz_widget]googlemaps[/moz_widget]()
  in...

A: En tu código original faltaron unos brackets [] y las funciones no se llamaron bien.
Pero eso no era el problema principal, si no tu regex no funcionaba bien y la salida era:
[moz_widget]googlemaps[\/moz_widget]
Regex Demo
con lo cual no ha podido llamar las funciones correctamente y respondió con un error.
Con el nuevo regex /\[.*\](.*?)\[.*\]/ te elimina todos los brackets [] con su contenido y es entonces cuando llama correctamente tus funciones:
Demo funcionando en PHP
Ver nuevo Regex
$nuevoContenido = preg_replace_callback('/\[.*\](.*?)\[.*\]/i', function($matches) {

    return $matches[1]();

}, $builder);

echo $nuevoContenido;


text:
Q: Alfresco: Which tables do I need to query to get workflow details I am trying to generate analytics reports using high charts.
For that I need to get values from alfresco DB using Postgres query. Can any one tell me what are the tables related workflow creation and save all workflow details.

A: I got some references from the below link.
http://techogeek.blogspot.in/2015/09/how-retrieve-activiti-workflow-details.html
As Gagravarr suggests, don't hit the database directly and use always the workflowservice to get the data workflow related data.
ACT_RE_*: RE stands for repository. Tables with this prefix contain static information such as process definitions and process resources (images, rules, etc.).
ACT_RU_*: RU stands for runtime. These are the runtime tables that contain the runtime data of process instances, user tasks, variables, jobs, etc. Activiti only stores the runtime data during process instance execution, and removes the records when a process instance ends. This keeps the runtime tables small and fast.
ACT_ID_*: ID stands for identity. These tables contain identity information, such as users, groups, etc.
ACT_HI_*: HI stands for history. These are the tables that contain historic data, such as past process instances, variables, tasks, etc.
ACT_GE_*: general data, which is used in various use cases.


text:
Q: Sparql variable getting out all bounded I have a triple store whith chemicals. Each substance has has around 30-40 Parameters. Each Parameter has a Database Name and a real name. For Example chem:flBeiRT has the real name Flüssig bei Raumtemperatur (german). To break the list up to a more readable size we have created Categories. One of those Categories would be : Nomenklatur (german).
I have now a Sparql query where a get all the Parameters under Nomenklatur
   SELECT DISTINCT ?name
   WHERE{
   ?s iol:name "Nomenklatur" .
   ?x rdf:type iol:property .
   ?x iol:name ?name .
   ?x iol:propertyof ?s .
   }

It gives me the real names of all parameters under Nomenklatur as expected.
In my understanding in the ?x variable are all paramerters already bound with there Database Name so i whant to use this direktly for getting all these parameters from one chemical. So i tried to add this direktly to this query. Insted of getting each parameter individually. Since the substance has no id i use a second Query insinde mine to only get that one chemical:
SELECT ?name
WHERE{
?s iol:name "Nomenklatur" .
?x rdf:type iol:property .
?x iol:name ?name .
?x iol:propertyof ?s .
{
 SELECT ?o
 WHERE{
   ?x chem:ilAbk "[A_4mim]Al" .
 }
}
}

And it still gives me the same eleven Parameters i asked for. But how would i now get all the fitting literas of that chemical ? I tried with:
SELECT DISTINCT ?name ?o
WHERE{
  ?s iol:name "Nomenklatur" .
  ?x rdf:type iol:property .
  ?x iol:name ?name .
  ?x iol:propertyof ?s .
  {
    SELECT DISTINCT ?o
    WHERE{
      ?x chem:ilAbk "[C_2mim]Cl" .
      ?x ?p ?o
    }
  }
}

But here i get over 312 results what seams to me like each parameter with each literal plus all the uri ? Could somebody please tell me how to acive that ? And Thank you for your time.
Or do i have to get every parameter alone ? Maybe it helps to see the data or a pice of it :
screen from Turtle file

A: Your sub-SELECT returns a variable ?o, but this isn't used in the outer SELECT query. SPARQL evaluates the inner sub-SELECT queries first, not the other way around. So the values of your given substance [C_2mim]Cl are computed first, then you have to restrict those in the outer SELECT.
I didn't understand your schema, i.e. it's not totally clear to me. Your predicates denote parameters of chemical substances, right? If yes, you would have to restrict the ?ps to those that do belong to the category.


text:
Q: JQuery UI 1.12.1 Autocomplete Not Working I have some issues in getting JQuery UI to work.
The version of query UI which I am using is the latest 1.12.1. I downloaded the autocomplete (and all the other required widgets).
In my project I have include jquery-ui.js, jquery-ui-min.js and jquery.js into the "Scripts" folder. I have also included "images" folder, jquery-ui.css and jquery-ui-min.css into "Content" folder.
Layout view
...
<head>
    ...
    <link href="~/Content/jquery-ui.css" rel="stylesheet" />
    <link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
</head>
<body>
    ...
    <script src="~/Scripts/jquery-ui.js"></script>
    <script src="~/Scripts/jquery-ui.min.js"></script>
    <script src="~/Scripts/jquery.js"></script>
</body>

Home view
<script type="text/javascript">
    $(document).ready(function () {
        $("#tbxTest").autocomplete({
            source: '@Url.Action("SearchElement", "Home")'
        });
    });
</script>

@using (Html.BeginForm())
{
    @Html.TextBox("searchText", null, new { id = "tbxTest" })
    <input type="submit" value="Search" />
}

Controller
...
public JsonResult SearchElement(string term)
{
    List<string> testingElement = new List<string>() { "Alpha", "Beta", "Charlie", "Delta" };

    List<string> searchResult = testingElement.Where(x => (string.Compare(x, term, true) == 0)).ToList();

    return Json(searchResult, JsonRequestBehavior.AllowGet);
}

I tried placing breakpoint on the first line in the controller method but it didn't got triggered. Please help.
Thanks in advance.

A: Try to update your jquery

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

It works for me.


text:
Q: It takes nearly 10 seconds before audio from remote URL starts playing I am able to play the sound from one URL. But takes nearly 10 seconds to play the audio.
@IBAction func playBtnTap(_ sender: Any) {
    let url = URL(string: muscUrl!)!
    let playerItem = AVPlayerItem(url: url)
    self.player = AVPlayer(playerItem: playerItem)
    self.player!.play()
}

I am new to iOS. I am not sure, how can I download the URL audio and then play that audio? I don't want that 10 sec delay to play audio.
Update, I tried :
override func viewDidLoad() {
    super.viewDidLoad()
    let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3"
    let url = NSURL(string: urlstring)
    print("the url = \(url!)")
    downloadFileFromURL(url: url!)
}

func downloadFileFromURL(url:NSURL){
    var downloadTask:URLSessionDownloadTask
    var request = URLRequest(url:url as URL)
    downloadTask = URLSession.shared.downloadTask(with: request, completionHandler: { (URL, response, error) -> Void in
        self.play(url: URL as! NSURL)
    })

    downloadTask.resume()
}

func play(url:NSURL) {
    print("Playing \(url)")

    do {
        self.player = try AVAudioPlayer(contentsOf: url as URL)
        player!.prepareToPlay()
        player!.volume = 1.0
        player!.play()
    } catch let error as NSError {
        //self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }
}

getting error in console :

The operation couldn't be completed. (OSStatus error 1954115647.)

in line self.player = try AVAudioPlayer(contentsOf: url as URL)

A: Your first code is correct. I don't experience any significant delay when I run it on my device. Naturally it can take some time on a slow Internet connection to fill the buffer before playback can start; but your second code, downloading and then playing, would therefore be even slower.
If you want to know what's happening with the AVPlayer's buffer, use KVO to track changes in its timeControlStatus.


text:
Q: Is it possible to install a 64 bit OS on 32 bit PC? I asked this in Unix and there suggested to ask it here.
I was answering a question on a Linux Facebook group where somebody asked if it was possible to install a 32 bit OS on 64 bit PC. My answer was:

It is absolutely possible to install a 32 bit OS on 64 bit PC. But it is impossible to install a 64 bit OS on 32 bit PC.

Well, then somebody replied to my comment:

It is not impossible, but it is not correct to do it.

So... is it really possible to install a 64 bit OS on a 32 bit PC?

A: The answer is really, really simple.
Technically, a "32-bits" PC, as you call it, would be a PC whose CPU supports 32-bit computing but does not support 64-bit computing.
For example, a PC with an Intel CPU that supports IA-32 but does not support EM64T or IA-64 would be a "32 bits" PC. Indeed you would not be able to install a 64-bit OS on such a PC.

A: It isn't and will fail to get past to the installer - least from the small sample of OSes I've tried. These were done in virtualbox for ease of pretty screenshots.
I tried it with a few common 64 bit OSes - Windows 10 (I had build 1511 lying around)

Booting into an existing install throws a very similar failure, asking for a PAE enabled processor.
And Windows 7

Maybe its not just Windows.
Lets try a Ubuntu 16.04 livecd

Pretty sure for any pure 64 bit OS, you wouldn't get past the initial stages of install disk booting. While I didn't test it extensively switching a installed 64 bit system to a 32 bit host is also likely to end badly.

A: You can manage to install it (with some hacking), but it would be useless, because it would not boot. So you can technically, but I wouldn't recommend doing it, because most people like to have a computer that can boot.
If your computer came with a 32-bit OS, and the 64-bit OS runs fine, then you should check your actual computer, because sometimes 64-bit computers come with 32-bit OS's.

A: It is possible that the person who replied to your original comment has encountered a 64-bit OS (presumably meaning one that uses either memory beyond that is addressable beyond 32-bit protected mode or uses 64-bit registers) that installs and boots on processors restricted to 32-bits of memory or uses wider hardware registers. The last section gives a real example of installation of 64-bit OS on 32-bit hardware. The intermediate sections explain why not only can such an OS be installed, it can even be used (in theory).
Technical details
There are two main things that one might expect in a 64-bit OS. The first is memory addressable beyond 4GiB. Since BIOS-based 64-bit machines boot into 16-bit (AKA real) mode, one can write an OS that jumps in and out of long, 64-bit memory mode for certain operations (see, for example, https://www.codeproject.com/articles/45788/the-real-protected-long-mode-assembly-tutorial-for how one can leave 64-bit mode). Or, in a mono tasking environment, jump into long mode for certain programs. It was common for 32-bit DOS programs to enter and leave 32-bit mode via a DOS extender in order to run. A scientific computing platform may also do something similar to reap the performance benefits of running 32-bit code (yes! 32-bit code can be faster than 64-bit code!) except where necessary.
The second thing that one might expect in a 64-bit OS is 64-bit registers. But one can easily stay in a low bit mode and switch to higher-bit modes as necessary. One can have a single program that contains a mixture of 16-, 32-, and 64-bit register code. To switch register sizes, one uses the operand size override prefix (opcode prefixes 0x66 and 0x67), although this last detail is usually taken care of by a compiler and invisible to most programmers.
Theoretical example
One could write an OS that only uses 64-bits in some parts of the OS.  Such an OS is easily within the realm of imagination. A 32-bit OS being ported to 64-bits may start by only making certain parts of the OS 64-bits (thus making it a 64-bit OS). Suppose the audio driver is the first thing ported; such an OS could run normally until one plays an audio file. I'm guessing this happens in the hobbyist OS scene with some regularity as someone wants to do a bit of experimentation with 64-bits or wishes to enhance the speed of a particular set of operations on the OS.
Real example of installing 64-bit OS on 32-bit machine
A real world example of a mixture of 64-bit and 32-bit code is MacOS (versions ~10.5-10.7). On a 64-bit Intel Mac, these versions of MacOS can boot to the 32-bit mode kernel and run 64-bit applications 64-bit userspace OS code. On a 32-bit machine, the computer still boots. However, instead of crashing the computer when trying to run 64-bit-only applications, MacOS simply refuses to run the application.
Note that the same disk OS is installed on both 32-bit and 64-bit Macs. You can install MacOS on a 32-bit Mac, remove the disk and place it into a 64-bit Mac and boot the 64-bit kernel. And, of course, the Hackintosh scene proves that you can install MacOS on a generic 32-bit machine.

A: A 32 bit CPU can't run 64 bit code "by design". Consequently, it can't boot a 64 bit OS which by definition contains a 64 bit kernel.
OS installers are well aware of this fact so refuse to install a 64 bit OS on 32 bit hardware in the first place.


text:
Q: Scala - modifying nested elements in xml I'm learning scala, and I'm looking to update a nested node in some xml. I've got something working but i'm wondering if its the most elegant way.
I have some xml:
val InputXml : Node =
<root>
    <subnode>
        <version>1</version>
    </subnode>
    <contents>
        <version>1</version>
    </contents>
</root>

And i want to update the version node in subnode, but not the one in contents.
Here is my function:
def updateVersion( node : Node ) : Node =
 {
   def updateElements( seq : Seq[Node]) : Seq[Node] =
   {
        var subElements = for( subNode <- seq ) yield
        {
            updateVersion( subNode )
        }
        subElements
   }

   node match
   {
     case <root>{ ch @ _* }</root> =>
     {
        <root>{ updateElements( ch ) }</root>
     }
     case <subnode>{ ch @ _* }</subnode> =>
     {
         <subnode>{ updateElements( ch ) }</subnode>
     }
     case <version>{ contents }</version> =>
     {
        <version>2</version>
     }
     case other @ _ =>
     {
         other
     }
   }
 }

Is there a more succint way of writing this function?

A: I have since learned more and presented what I deem to be a superior solution in another answer. I have also fixed this one, as I noticed I was failing to account for the subnode restriction.
Thanks for the question! I just learned some cool stuff when dealing with XML. Here is what you want:
def updateVersion(node: Node): Node = {
  def updateNodes(ns: Seq[Node], mayChange: Boolean): Seq[Node] =
    for(subnode <- ns) yield subnode match {
      case <version>{ _ }</version> if mayChange => <version>2</version>
      case Elem(prefix, "subnode", attribs, scope, children @ _*) =>
        Elem(prefix, "subnode", attribs, scope, updateNodes(children, true) : _*)
      case Elem(prefix, label, attribs, scope, children @ _*) =>
        Elem(prefix, label, attribs, scope, updateNodes(children, mayChange) : _*)
      case other => other  // preserve text
    }

  updateNodes(node.theSeq, false)(0)
}

Now, explanation. First and last case statements should be obvious. The last one exists to catch those parts of an XML which are not elements. Or, in other words, text. Note in the first statement, though, the test against the flag to indicate whether version may be changed or not.
The second and third case statements will use a pattern matcher against the object Elem. This will break an element into all its component parts. The last parameter, "children @ _*", will match children to a list of anything. Or, more specifically, a Seq[Node]. Then we reconstruct the element, with the parts we extracted, but pass the Seq[Node] to updateNodes, doing the recursion step. If we are matching against the element subnode, then we change the flag mayChange to true, enabling the change of the version.
In the last line, we use node.theSeq to generate a Seq[Node] from Node, and (0) to get the first element of the Seq[Node] returned as result. Since updateNodes is essentially a map function (for ... yield is translated into map), we know the result will only have one element. We pass a false flag to ensure that no version will be changed unless a subnode element is an ancestor.
There is a slightly different way of doing it, that's more powerful but a bit more verbose and obscure:
def updateVersion(node: Node): Node = {
  def updateNodes(ns: Seq[Node], mayChange: Boolean): Seq[Node] =
    for(subnode <- ns) yield subnode match {
      case Elem(prefix, "version", attribs, scope, Text(_)) if mayChange =>
        Elem(prefix, "version", attribs, scope, Text("2"))
      case Elem(prefix, "subnode", attribs, scope, children @ _*) =>
        Elem(prefix, "subnode", attribs, scope, updateNodes(children, true) : _*)
      case Elem(prefix, label, attribs, scope, children @ _*) =>
        Elem(prefix, label, attribs, scope, updateNodes(children, mayChange) : _*)
      case other => other  // preserve text
    }

  updateNodes(node.theSeq, false)(0)
}

This version allows you to change any "version" tag, whatever it's prefix, attribs and scope.

A: All this time, and no one actually gave the most appropriate answer! Now that I have learned of it, though, here's my new take on it:
import scala.xml._
import scala.xml.transform._

object t1 extends RewriteRule {
  override def transform(n: Node): Seq[Node] = n match {
    case Elem(prefix, "version", attribs, scope, _*)  =>
      Elem(prefix, "version", attribs, scope, Text("2"))
    case other => other
  }
}

object rt1 extends RuleTransformer(t1)

object t2 extends RewriteRule {
  override def transform(n: Node): Seq[Node] = n match {
    case sn @ Elem(_, "subnode", _, _, _*) => rt1(sn)
    case other => other
  }
}

object rt2 extends RuleTransformer(t2)

rt2(InputXml)

Now, for a few explanations. The class RewriteRule is abstract. It defines two methods, both called transform. One of them takes a single Node, the other a Sequence of Node. It's an abstract class, so we can't instantiate it directly. By adding a definition, in this case override one of the transformmethods, we are creating an anonymous subclass of it. Each RewriteRule needs concern itself with a single task, though it can do many.
Next, class RuleTransformer takes as parameters a variable number of RewriteRule. It's transform method takes a Node and return a Sequence of Node, by applying each and every RewriteRule used to instantiate it.
Both classes derive from BasicTransformer, which defines a few methods with which one need not concern oneself at a higher level. It's apply method calls transform, though, so both RuleTransformer and RewriteRule can use the syntactic sugar associated with it. In the example, the former does and the later does not.
Here we use two levels of RuleTransformer, as the first applies a filter to higher level nodes, and the second apply the change to whatever passes the filter.
The extractor Elem is also used, so that there is no need to concern oneself with details such as namespace or whether there are attributes or not. Not that the content of the element version is completely discarded and replaced with 2. It can be matched against too, if needed.
Note also that the last parameter of the extractor is _*, and not _. That means these elements can have multiple children. If you forget the *, the match may fail. In the example, the match would not fail if there were no whitespaces. Because whitespaces are translated into Text elements, a single whitespace under subnode would case the match to fail.
This code is bigger than the other suggestions presented, but it has the advantage of having much less knowledge of the structure of the XML than the others. It changes any element called version that is below -- no matter how many levels -- an element called subnode, no matter namespaces, attributes, etc.
Furthermore... well, if you have many transformations to do, recursive pattern matching becomes quickly unyielding. Using RewriteRule and RuleTransformer, you can effectively replace xslt files with Scala code.

A: Scales Xml provides tools for "in place" edits.  Of course its all immutable but here's the solution in Scales:
val subnodes = top(xml).\*("subnode"l).\*("version"l)
val folded = foldPositions( subnodes )( p =>
  Replace( p.tree ~> "2"))

The XPath like syntax is a Scales signature feature, the l after the string specifies it should have no namespace (local name only).
foldPositions iterates over the resulting elements and transforms them, joining the results back together.

A: You can use Lift's CSS Selector Transforms and write:
"subnode" #> ("version *" #> 2)

See http://stable.simply.liftweb.net/#sec:CSS-Selector-Transforms

A: I think the original logic is good.
This is the same code with (shall I dare to say?) a more Scala-ish flavor:
def updateVersion( node : Node ) : Node = {
   def updateElements( seq : Seq[Node]) : Seq[Node] =
     for( subNode <- seq ) yield updateVersion( subNode )

   node match {
     case <root>{ ch @ _* }</root> => <root>{ updateElements( ch ) }</root>
     case <subnode>{ ch @ _* }</subnode> => <subnode>{ updateElements( ch ) }</subnode>
     case <version>{ contents }</version> => <version>2</version>
     case other @ _ => other
   }
 }

It looks more compact (but is actually the same :) )

*

*I got rid of all the unnecessary
brackets

*If a bracket is needed, it starts in
the same line

*updateElements just defines a var
and returns it, so I got rid of that
and returned the result directly

if you want, you can get rid of the updateElements too. You want to apply the updateVersion to all the elements of the sequence. That's the map method. With that, you can rewrite the line
case <subnode>{ ch @ _* }</subnode> => <subnode>{ updateElements( ch ) }</subnode>

with
case <subnode>{ ch @ _* }</subnode> => <subnode>{ ch.map(updateVersion (_)) }</subnode>

As update version takes only 1 parameter I'm 99% sure you can omit it and write:
case <subnode>{ ch @ _* }</subnode> => <subnode>{ ch.map(updateVersion) }</subnode>

And end with:
def updateVersion( node : Node ) : Node = node match {
         case <root>{ ch @ _* }</root> => <root>{ ch.map(updateVersion )}</root>
         case <subnode>{ ch @ _* }</subnode> => <subnode>{ ch.map(updateVersion ) }</subnode>
         case <version>{ contents }</version> => <version>2</version>
         case other @ _ => other
       }

What do you think?

A: One approach would be lenses (e.g. scalaz's). See http://arosien.github.io/scalaz-base-talk-201208/#slide35 for a very clear presentation.

A: If any poor souls still have to deal with XML in 2021 with Scala, here's one more library-based solution that I find particularly nice:
import scala.xml._
import jstengel.ezxml.core.SimpleWrapper.ElemWrapper
import jstengel.ezxml.core.XmlPath.\~

val InputXml: Elem = <root>
    <subnode>
        <version>1</version>
    </subnode>
    <contents>
        <version>1</version>
    </contents>
</root>

(InputXml \~ "subnode" \~ "version").transformTarget(_ => <version>2</version>)

Library in question: https://github.com/JulienSt/ezXML (thank you, Mr. JulienSt!)
Try it at https://scastie.scala-lang.org/EYJG5B91Q3KiVD7h9940JA

A: I really don't know how this could be done elegantly. FWIW, I would go for a different approach: use a custom model class for the info you're handling, and have conversion to and from Xml for it. You're probably going to find it's a better way to handle the data, and it's even more succint.
However there is a nice way to do it with Xml directly, I'd like to see it.


text:
Q: My PC seems to be slow although I'm using an SSD I have an SSD with NTFS format.
My question is, does the NTFS format affect the performance of a Linux system, or is it unrelated?

A: The results of this Phoronix benchmarking test show that performance on NTFS filesystem is slower than on ext4,

File system type
Copy 655MB (1)
Copy 655MB (2)
tar gzip 655MB
unzip untar 655MB
Del 2.5GB

REISER4 gzip
213
148
68
83
48

REISER4 lzo
278
138
56
80
34

REISER4 tails
673
148
63
78
33

REISER4
692
148
55
67
25

NTFS3g
772
1333
1426
585
767

NTFS
779
781
173
X
X

REISER3
793
184
98
85
63

XFS
799
220
173
119
90

JFS
806
228
202
95
97

EXT4 extents
806
162
55
69
36

EXT4 default
816
174
70
74
42

EXT3
816
182
74
73
43

EXT2
816
201
82
73
39

FAT32
988
253
158
118
81

The raw data (without filesystem meta-data, block alignment wastage, etc.) was 655MB.
It comprised 3 different copies of the Linux kernel sources.
Disk Usage: the amount of disk used to store the data
Copy 655MB (1): time taken to copy the data over a partition boundary
Copy 655MB (2): time taken to copy the data within a partition
tar gzip 655MB: time taken to tar and gzip the data
unzip untar 655MB: time taken to ungzip and untar the data
Del 2.5 Gig: time taken to delete everything just written (about 2.5 Gig)
Each test was preformed 5 times and the average value recorded. source

The main advantage of the NTFS filesystem over ext4 is that it is recognized natively by Windows. NTFS suffers from file fragmentation. This adds wear and tear to your hardware as well as slowing the system down. ext4 is immune to this as long as you are not running really low on disk space.


text:
Q: Set the Resource String in javascript How can I set the resource string in javascript?
I have a resource file called, for example,
myResourceFile.resx

in my code and using the literal control I can use:
lblName.Text = Resources.myResourceFile.ajaxRetrievingInformation;

<asp:Literal id="lit" runat="server"
             Text="<%$ Resources:myResourceFile, ajaxRetrievingInformation%>" />

but if I try this in javascript, like:
<asp:Button ID="btnImportCompaniesAndEmployees"
            runat="server"
            CssClass="myButtonCssClass"
            OnClick="btnImportCompaniesAndEmployees_Click"
            OnClientClick="strLoadingText='<%$ Resources:myResourceFile, ajaxRetrievingInformation%>';return true;"
            ...
/>

or
<script type="text/javascript">
    var strLoadingText = '<%$ Resources:myResourceFile, ajaxRetrievingInformation%>';
</script>

I get errors...
Does anyone know how to manage this?
Something like:
var strLoadingText = Resources.GetString(myResourceFile, ajaxRetrievingInformation);

Thanks

A: You should be able to use:
<script type="text/javascript">
    var strLoadingText = "<%= Resources.myResourceFile.ajaxRetrievingInformation %>";
</script>


text:
Q: Regex on Java: avoiding unnecessary "greedy" strategy by Matcher class I'm trying to develop a regex to look for a sequence of tags inside a string. For example, I can have the tag (NP .*) at least one time (can be multiple times), followed by a punctuation symbol (in this case a ./.). If there's another tag between de (NP) and the ./. (like the VP in the example below), the Matcher must not find anything. The problem is that even if I use the question mark after the .* it will keep looking for a ) that makes the expression match something in the string. Here is my method:
public void myMethod() {
    String input = "(NP first tag) (VP second tag) ./.";
    String regex = "(\\(NP .*?\\)( )?)+" + "\\./\\.";

    Pattern pattern = Pattern.compile("(" + regex + ")");
    Matcher matcher = pattern.matcher(input);

    if (matcher.find()) {
        System.out.println("<S "+matcher.group(0)+">");
    } else {
        System.out.println("sem grupos.");
    }
}

The method will still match the regex, but it shouldn't.  I need it to tell me that no group was found, since the "VP" tag shouldn't be there. I believe the problem relies on the greedy strategy adopted by the Regex in Java. It tries to find some combination of characters that attend to the pattern described by the regex. I have no idea on how to rewrite this expression.
Any Help?
EDITED:
1) I noticed that my question was a bit confusing, so I changed a bit the example to make it clearer.
2) Thanks Aan Moore. I Agree that I was using more groups than necessary, but this happened because of the operators like +. I tried to cut away the unnecessary groups. Also your simple idea of replacing the .*? by a [^)]*? was great! The only thing that I adjusted was that I escaped the ) symbol by using [^\\)]*?. Below I show the final REGEX used.
String regex = "(\\(NP [^\\)]*?\\) ?)+\\./\\.";

Thanks a lot! :)

A: ((\(NP .*?\)( )?)+\./\.) is the compiled pattern.
Simplify:
\(NP .*?\) ?+\./\. removing unused capturing groups.
Now, lets look at the example strings you have:
In (NP first tag) (VP second tag) ./., the .*? matches first tag) (VP second tag.
In (NP first tag) (VP second tag) (MISC tag that must not be catch) ./., .*? matches first tag) (VP second tag) (MISC tag that must not be catch.
Why?  I mean, it's non-greedy right? Right, but...
.*?\) starts off matching first tag), what you want.  However, the rest of the regex fails the match and the regex engine throws that out as a possible answer and keeps looking.
If you don't have tags in tags like (NP (tag)), you can change the pattern: \(NP [^)]*?\)
To match the string you described in your question: \(NP [^)]*?\)  ?\(VP [^)]*?\) \./\.
With Java escaping it becomes \\(NP [^)]*?\\)  ?\\(VP [^)]*?\\) \./\..
For further reading, there is a great Stack Overflow question covering more of the theory and practice around this.


text:
Q: How can I disable transactions for a Hive table? I have a Hive table that was originally created as transactional, but I want to disable transactions on the table because they are not actually needed.
I tried to disable them using ALTER TABLE, but I got an error:
hive> ALTER TABLE foo SET TBLPROPERTIES('transactional'='false');
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter table. TBLPROPERTIES with 'transactional'='true' cannot be unset

I am using Hive 2.3.2

A: According to the documentation changing TBLPROPERTIES ("transactional"="false") is not allowed.
You can re-create the table.
Do table backup first:
create table bkp_table as
select * from your_table;

Then drop table and create again without transactional property. Reload data from backup.
Or make a new table, load data from old one, delete old, rename new.

A: You have to re-create the table.
First backup table if you want. then, DROP TABLE
Create Table with TBLPROPERTIES ( 'transactional'='false' )
CREATE TABLE your_table(
  `col` string,
  `col2` string)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
TBLPROPERTIES (
  'transactional'='false'
)

You can Choose Input and Output format


text:
Q: targeting element within an element stored in a fragment I'm not sure how to target the element I want in this case:
  var $div = $(".row-container").filter(function() {
        return $(this).data("i") == product_id;
        // where value == product id to find
      });

Now, within $div is an element that has the class 'price-row' which is what I want. $div.hasClass('price-row') only returns true or false value.

A: Use .find if it's a child element:
var $div = $(".row-container").filter(function() {
    return $(this).data("i") == product_id; // where value == product id to find
}).find('.price-row');
If you meant that the matching element will be within that set, include it in the criteria to begin with:
var $div = $(".row-container.price-row").filter(function() {
    return $(this).data("i") == product_id; // where value == product id to find
});


text:
Q: javascript pubnub messaging system I am currently using PubNub SDK for chatting in website and iPhone. Now i want to implement functionality like i want to send message from iPhone to web-end once user sends a message from iPhone to web-end ( user will be notified ).
Now the issue is when initially user1 sends message from iPhone to webend i am not getting notification.
on first message i am not getting notification.
code is somewhat like this
var socket = new WebSocket("Pubnub + channel1id";
var chat_socket = new WebSocket("Pubnub + channel2id";
socket.onmessage = function (evt)
 {
    //Here i implemeted our notification functionality.
 }

 chat_socket.onmessage = function (evt)
 {
    //Here i implemeted our notification functionality.
 }

on second message i am getting object on .onmessage but not for first.


text:
Q: SyntaxError: unicodeescape I am trying to build a bot which gives a random answer from CSV file.
Piece of code I have problem with:
def get_data(lounaslista):
    with open('C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv', 'r') as f:
        r = csv.reader(f)
        data = [row for row in r]
    return data

Error I'm getting:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
I tried solutions from following post.

A: Use double slash instead of simple slash in path.
def get_data(lounaslista):
    with open('C:\\Users\\p7l1n\\Desktop\\lounasbotti\\lounaslista.csv', 'r') as f:
        r = csv.reader(f)
        data = [row for row in r]
    return data

Example with simple variable:
a = 'C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv'
# SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

# With double slash:
a = 'C:\\Users\\p7l1n\\Desktop\\lounasbotti\\lounaslista.csv'
print(a)  # C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv

# Or use raw string:
a = r'C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv'
print(a)  # C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv

A: The backslash character in strings is used as an escape character. For example \n is a newline, \" and \' can be used to insert " and ' into string literals without terminating those literals. You can also write \U00000000 to insert a character with that code point (instead of 00000000 you can have any hexadecimal number).
To insert a literal backslash, you have to escape the backslash, like so: \\
For Windows file paths, this gets a bit tedious, so there is an alternative: raw string literals, like so: r'C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv'. This disables escape sequences.
A third option is to use forward slashes instead: 'C:/Users/p7l1n/Desktop/lounasbotti/lounaslista.csv'. Windows generally accepts forward slashes as an alternative path separator.

A: This error occurs because you are using a normal string as a path. You can use one of the these following to fix your problem:
try to put r before your string. It will convert it to a raw string:
 def get_data(lounaslista):
    with open(r"C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv") as f:
        r = csv.reader(f)
        data = [row for row in r]
    return data

or like this:
def get_data(lounaslista):
with open("C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv", 'r') as f:
    r = csv.reader(f)
    data = [row for row in r]
return data

or:
def get_data(lounaslista):
with open("C:\\Users\\p7l1n\\Desktop\\lounasbotti\\lounaslista.csv", 'r') as f:
    r = csv.reader(f)
    data = [row for row in r]
return data

or:
def get_data(lounaslista):
with open("C:/Users/p7l1n/Desktop/lounasbotti/lounaslista.csv", 'r') as f:
    r = csv.reader(f)
    data = [row for row in r]
return data


text:
Q: How to save a tensor I have a dataset of 1000 items. I normalize the data before I train the model against it.
I would now like to use the model to make predictions. However, from what I understand, I need to normalize the inputs that I will feed to the model for which I need the predictions for. In order to carry this out, I would need the mean and std calculated at the time of training.
While I am able to print it to the console, how does one "save" it - to be used later? I am trying to understand the procedure here on how to save the mean and std used at the time of normalization of the training data - so that I can use it again at the time of making predictions.

A: I determined that we could first get the array representation of the tensor through:
// tensor here is the tensor variable that contains the tensor
const tensorAsArray = tensor.arraySync()

and then, we save it to a file like any other string
fs.writeFile(myFilePath, JSON.stringify(tensorAsArray), 'utf-8')

To read it back and use it as a tensor, we would do the opposite:
const tensorAsArray = JSON.parse(fs.readFile(myFilePath, 'utf-8'))
const tensor = tf.tensor(tensorAsArray)

This allowed me to save the mean and std for use later.


text:
Q: ios 6 - canperformaction not getting called on UITableViewController I am working on adding custom shared menu. I followed this stackoverflow post to implement this also seen some other posts.
It is working as it should be. But I am getting problem to get called canPerformAction when coming on this UITableView Controller by UITabBar item action which navigate me back to this view.
I tried to sovle this problem by using one of the answer on stackoverflow. But still canPerformAction not getting called in this case
Any help in this case is appritiated. Thanks
EDIT: My code looks like:
On viewDidLoad, i am doing following
UIMenuItem *sendByEmailMenuItem = [[UIMenuItem alloc] initWithTitle:@"Send e-mail" action:@selector(sendEmail:)];
[[UIMenuController sharedMenuController] setMenuItems: @[sendEmailMenuItem]];
[[UIMenuController sharedMenuController] update];

These are delegate methods i have used
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return NO;
}
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {

}

- (BOOL) canPerformAction:(SEL)action withSender:(id)sender {
    return (action == @selector(sendEmail:));
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void) sendEmail: (id) sender {
       //do stuff
}

A: Fixed this issue. Posting it if some one needs it.
I have added a call to become fist respoder on shouldShowMenuForRowAtIndexPath action
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
    [self becomeFirstResponder];
    return YES;
}

This fixed my issue. Thanks


text:
Q: in ASP.NET MVC HttpPostedFileBase collection has only null items This is my code:
@using (Html.BeginForm("UploadImages", "Administration", new { _id = Model.Album.AlbumID, enctype = "multipart/form-data" }, FormMethod.Post))
{
    <input type="file" name="fileUpload" id="file1" />

    <input type="file" name="fileUpload" id="file2" />

    <input type="file" name="fileUpload" id="file3" />

    <input name="addPhoto" type="submit" value="Добавить фото" />
}

 [Authorize]
   [HttpPost]
   public ActionResult UploadImages(int _id, IEnumerable<HttpPostedFileBase> fileUpload)
        {
            gb_albumdbEntities1 entityes = new gb_albumdbEntities1();
            foreach (var file in fileUpload)
            {
                if (file == null) continue; // **<---fileUpload items is always null!**
                string path = AppDomain.CurrentDomain.BaseDirectory + "Photos/";
                if (Path.GetFileName(file.FileName) != null)
                {
                    string filename = file.GetHashCode().ToString();
                    string fullpath = Path.Combine(path, filename);
                    file.SaveAs(fullpath);
                    entityes.Photos.AddObject(new Photo() { AlbumID = _id, PhotoUrl = @"http://site.ru/Photos/" + filename });
                }
            }
            entityes.SaveChanges();
            return RedirectToAction("AlbumEdit", new { id = _id });
        }

fileUpload items is always null. Where is the problem?Oo
UPD: calculated result post url:
http://localhost:56193/Administration/UploadImages?_id=4&enctype=multipart%2Fform-data

A: your list if file inputs need to be numbered for model binding to work. In the simplest form your view should look something like this:

    <title>Index</title>

        @using (Html.BeginForm("Index", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            for (int i = 0; i < 3; i++)
            {
                @Html.TextBox(string.Format("fileUpload[{0}]", i), null, new { type="file" })

            }
            <input name="submit" type="submit" value="Go" />
        }

and your controller:
    public class UploadController : Controller
    {
        //
        // GET: /Upload/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload)
        {

            return View();
        }

    }

A: Try the following post which I've used myself before. Worked for me.
http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx


text:
Q: My first simple angular app. Objects aren't displaying My first angular homework and I can't get the objects I make in my typescript file to appear when I try to call them into my html page.  I've got to have a little typo somewhere or something, but I've been playing for an hour and I can't find it.  Any help is greatly appreciated.
typescript:
namespace myApp{
    angular.module("myApp", []);

    class MainController {

        public animal;

        constructor() {

            this.animal = [
                { id: 1, breed: "spaniel", foods: ["alpo", "bones", "cats"] },
                { id: 2, breed: "lab", foods: ["fish", "chicken", "cats"] },]
        }
         }
angular.module("myApp").controller("MainController", MainController);

And _Layout.cshtml
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

        @RenderBody()

{{animal}}

ng-repeat= "food in animal.foods"

            {{foods}}

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

A: Try this one,

And your html should be,

Animals

{{animal.id}}

Please feel free to ask any doubt in this one.


text:
Q: How can I make my nav bar display properly when being zoomed in mobile device? I have made a nav bar by using a nav element, which contains a large div element. The div element then contains three smaller div elements.
I made the nav element position: fixed; min-width: 100vw.
The large div element has position: relative; height: 10vw.
All three small divs has display: inline-block and some width and margins, and the third one has position: absolute; right: 0.
The settings work perfectly well when I test them in the latest Chrome version for OSX, but when I view the page through my iPad (both Safari and Chrome for iOS) and zoom in using two fingers, a part of the nav bar was out of the screen.
I tried not to use the min-width: 100vw style, but only got the result that the third div drops out from the nav bar into a new line when being zoomed in.
Can any tell me how to fix the problem to make bar display properly when being zoomed?
Here is the nav bar I work on.

A: Add the code: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> in your head section. This will disable zooming entirely though...
Also try defining both the height and width of the nav.


text:
Q: Need help optimizing query counts on distinct columns based on other columns Essentially I have a table comprised of the following columns:
|Time|CompanyID|ProductType|ApplicationType|CustomerNumber|SessionId
Essentially I want to have the
1) total distinct counts of customerNumber for each product type for each company
Right now I have about ~4000 companies with about 3 products each and a total of about 130,000 records. My code is really inefficient and takes forever to run
Below is my current code:
companies = list(final_table.select(final_table.CompanyId).distinct().rdd.flatMap(lambda x: x).collect())
  for c in companies:

  company_detail = final_table.filter(final_table.CompanyId == c)

  products = list(company_detail.select(company_detail.OriginalModule).distinct().rdd.flatMap(lambda x: x).collect())

  for p in products:

      unique_user_count = company_detail.filter(company_detail.Product == p).select(company_detail.CustomerNumber).distinct().count()
      total_views = company_detail.filter(company_detail.ProductType == p).count()

It runs but it's incredibly slow and inefficient, any suggestions?

A: Try use groupby and agg for DataFrame:
from pyspark.sql import functions as F
company_detail.groupBy(["CompanyId", "ProductType"]).agg(F.countDistinct(company_detail['customerNumber']))

A:
you can do this way.

just use distinct, groupBy and count and optional orderBy if you want
df.select("CompanyId","ProductType","customerNumber").distinct().groupBy("CompanyId","ProductType","customerNumber").count().orderBy("CompanyId").show()

Details

Raw data

df.select('DOB','last_name','First_name').show(20, False)

+----------+---------+----------+
|DOB       |last_name|First_name|
+----------+---------+----------+
|1986-02-09|mon      |Jo        |
|1976-02-09|boss     |hugo      |
|1986-02-09|mon      |Jose      |
|1976-02-09|boss     |hugo      |
|1976-02-09|boss     |hugo      |
|1986-02-09|mon      |Jo        |
|1976-02-09|boss     |hugo      |
|1986-02-09|mon      |Jose      |
|1976-02-09|boss     |hugo      |
|1986-02-09|mon      |Jo        |
|1976-02-09|boss     |hugo      |
|1986-02-09|mon      |Jose      |
|1976-02-09|boss     |hugo      |
|1976-09-09|battle   |chris     |
|1976-09-09|battle   |chris     |
|1986-02-09|mon      |Jo        |
|1976-02-09|boss     |hugo      |
|1986-02-09|mon      |Jo        |
|1976-02-09|boss     |hugo      |
+----------+---------+----------+

group by counts with duplicates

df.groupBy('DOB','last_name','First_name').count().orderBy('DOB').show()

+----------+---------+----------+-----+
|       DOB|last_name|First_name|count|
+----------+---------+----------+-----+
|1976-02-09|     boss|      hugo|    9|
|1976-09-09|   battle|     chris|    2|
|1986-02-09|      mon|      Jose|    3|
|1986-02-09|      mon|        Jo|    5|
+----------+---------+----------+-----+

group by count with out duplicate

df.select('DOB','last_name','First_name').distinct().groupBy('DOB','last_name','First_name').count().orderBy("DOB").show()

+----------+---------+----------+-----+
|       DOB|last_name|First_name|count|
+----------+---------+----------+-----+
|1976-02-09|     boss|      hugo|    1|
|1976-09-09|   battle|     chris|    1|
|1986-02-09|      mon|      Jose|    1|
|1986-02-09|      mon|        Jo|    1|
+----------+---------+----------+-----+


text:
Q: Customer account creation, save boolean value in attribute So, as the title says, i've added some new attributes in my customer entity, one of which is a boolean, as you can see from the code in setup/InstallData.php
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'azienda', [
        'type' => 'int',
        'label' => 'Azienda',
        'input' => 'boolean',
        'source' => '',
        'required' => false,
        'visible' => true,
        'position' => 333,
        'system' => false,
        'backend' => ''
    ]);

and i've also created the frontend layout override for "customer_account_create", everything works fine, other text fields i've added  are saved correctly but i can't get it to save in my database this "azienda" attribute which is a boolean. I've tried checkboxes, radiobuttons, textfields with "yes", "true" and "1", whatever i put in that field the boolean attribute will be always unchecked (false) after registration.
Hope i've explained my issue well enough, thank you for your help :)

A: I have managed to fix it, in the end it wasn't something hard or impossible to find.
I did what i should have done from the beginning, check how the "subscribe to newsletter" was being saved and i've noticed that the <input type="checkbox">  had the value="1" property, so i've put it in my checkbox and now it works. Leaving here the code if someone has my same problem.

        <input type="checkbox" name="azienda" title="<?= $block->escapeHtmlAttr(__('Azienda')) ?>" value="1" id="azienda" class="checkbox">
        <?= $block->escapeHtml(__('Azienda')) ?>

From what i understand this works because the checkboxes will be added to the post request ONLY if they are checked with the on value but if we add the value="1" property that gets sent instead and when Magento2 receives azienda -> 1 it saves it correctly in my user entity


text:
Q: "dig cloudapp.net" (the main MS Azure domain) returns nothing, is this allowed in DNS? The domain "cloudapp.net" is used by Microsoft's Azure service. I ran a dig cloudapp.net command and to my surprise this yielded nothing (no ANSWER section came back in the response). "cloudapp.net" is a main domain in use by Microsoft's Azure service and Azure customers leverage it by having a subdomain off it such as "yourwebsite.cloudapp.net" and using a CNAME to link their branded domain to their sire hosted on the Azure service.
How can you have a domain name "cloudapp.net" that points to nothing basically? It is not required in DNS for a second-level domain to have an IP address linked to it? What would be some reasons for configuring your domain name in such a way? Why not have "cloudapp.net" by default point to the main MS site? Just wanting to understand why this is allowed in DNS and why from a technical perspective a company would choose to do this.

A: it doesn't actually return 'nothing', if you run dig cloudapp.net IN ANY, you'll see you've been given a list of nameservers, which a recursive dns resolver will follow for more details, or so can you:
dig sub.cloudapp.net IN ANY @prd1.azuredns-cloud.net
thus, cloudapp.net doesn't need to have a host address record (and isn't required one), a request for a subdomain will still query the main nameservers, which will return a host record for a valid subdomain, or NXDOMAIN if not.
its possible there is an internal or security reason they don't want to point cloudapp.net to a website; perhaps ensure customer flow through one portal. just a hypothesis


text:
Q: BATCH files: dynamic variable depending on the parameters I have a simple batch file
@echo off
set a1=application 1
set a2=application 2
set a3=application 3

set app = %%1%
ECHO %app%

What I would like to achieve is when I call my batch file (test.bat) with a parameter it would echo the desired string
so if I call:
test a1
-> application 1
test a3
-> application 3
DISCLAIMER: This is a simplified example.

A: CALL set app=%%%1%%

note that batch is sensitive to spaces on each side of the =. You attempted to set a variable named appSpace

A: @echo off
set a1=application 1
set a2=application 2
set a3=application 3
CALL SET app=%%%1%%
ECHO %app%

The call performs sonething similar to evalin eg. Perl, the %1 gets replaced and then the statement SET app=%a1%gets executed.#
Without the CALL you end up with %a1% as value of app, instead of application 1.


text:
Q: Finding the highest value in a range How can I find the highest price among the prices with same contiguous label ?
For instance, in the picture below the result of the formula in D6 should be 5 because the formula should consider the lines 4, 5 and 6 only (contiguous lines with label 'a'). Therefore, the prices to be considered should be 3, 4 and 5 and the relevant MAX is 5.

I started building the formula in steps and the first one is to get the row n# where the max price is and I made this formula {=MAX(IF($A$2:A5<>A6,ROW()))} but I cannot even make this to work.
EDIT
The solution from Tom Sharpe in this thread is almost perfect.
What I didn't mention in the initial question is I want to see the MAX in each line.
Here below is the screenshot with an extra column with what I want to achieve.

A: Should look something like this (max of a range from the previous row which does not contain the same letter in column A as the current row, plus one, to the current row):
=IF(A3=A2,"",MAX(INDEX(B:B,AGGREGATE(14,6,ROW(A$1:A1)/(A$1:A1<>A2)+1,1)):B2))

A: I have amended Tom's formula in =IF(A3=A2,D3,MAX(INDEX(B:B,AGGREGATE(14,6,ROW(A$1:A1)/(A$1:A1<>A2)+1,1)):B2)) and now I have the column "E" correctly populated.


text:
Q: SQL Injection attack - the use of mysqli_multi_query() I am learning mysql now and one of the subjects it touches is the security issue when dealing with user input - one concern is the injection attack. I tried to duplicate the attack the book demonstrated like add a query $query = "select * from temp_table; drop table temp_table, which I used mysqli_query($connection,$query). Nothing happen. I changed to use mysqli_multi_query() and found it executed both statements. Finally I found that mysqli_query only runs one query each time.
my question is, if I use mysqli_query, theoretically speaking, the system shouldn't be worried on additional statement injection attack? Or, there is still any other way that the users can run additional statement even the server is using mysqli_query?

A: It's true that the basic mysqli_query() will only run one statement. So you don't have to worry that an SQL injection attack will trick your application into running multiple statements.
But one statement can include a subquery, or a SELECT... UNION SELECT....
One statement can read data it isn't intended to read. Or cause a huge sort that is intended to overwhelm your server as a denial-of-service attack.
Or it can simply be an error, not a malicious attack at all.
SELECT * FROM Users WHERE last_name = 'O'Reilly'; -- woops!

The solutions to SQL injection are pretty simple, and easy to follow. I don't understand why so many developers look for excuses not to write safe code.


text:
Q: $A_n \subset (X, \tau)$ whit $A_{n+1} \subset A_n$ y $\cap \overline{A_n}=\emptyset$ then $\{A_n\}_{n \in \mathbb{N}} $ is locally finite Lef $(X,\tau)$ a topological space:
Show that if $\{A_n: n \in \mathbb{N}\}$ is a family of subsets of  $ X $ such that $ A_{n+1} \subset A_n $ $ \forall n \in \mathbb{N}$ , y $\bigcap_{n \in \mathbb{N}} \ \overline{A_n} =\emptyset$, then $\{A_n: \ n \in \mathbb{N}\}$ is locally finite.
Seeing that $\{A_n : n \in \mathbb{N}\} $ is locally finite, is equivalent to seeing that given a point $x \in X$ there exists a neighborhood $ U $ such that the set $\{n \in \mathbb{N}: U \cap A_n \neq \emptyset\}$ is finite.
For this I remembered the property of Cantor:
Given any countable family of closed $\{F_n \ : n \in \mathbb{N}\}$, non-empty and fitted sets ${F_n}$ ($F_ {n + 1} \subset F_n$) then $ \bigcap_{n \in \mathbb{N}} F_n \neq \emptyset$, but in the hypothesis it says that this does not happen.

A: The Cantor Intersection Theorem is for decreasing nests of compact sets, so it doesn't apply here. We don't need anything that fancy anyway. Let $x\in X$. Then $x\notin\bigcap_{n\in\Bbb N}\operatorname{cl}A_n$, so there is an $n\in\Bbb N$ such that $x\notin\operatorname{cl}A_n$, and therefore $x$ has an open nbhd $V$ such that $V\cap A_n=\varnothing$. Now use the fact that the sets $A_k$ are a decreasing nest to conclude that $\{k\in\Bbb N:V\cap A_k\ne\varnothing\}$ is finite.


text:
Q: JAudio feature exxtractor not extracting features for specific files I am using jAudio software for feature extraction of audio files. Im using filws in aiff,au,wav etc. file formats. It extracts features of file with frame rate of 16000 frmaes per second, channel:stereo, frame size: 16bit etc.
Though I have converters which convert file to wav, au, aiff formats but I donot have any converter which asks me frame rate etc. while converting. So I have files which have higher feature values and it gives error while converting.
Kindly guide is this software error or songs should be converted in this frame rate etc. only.
Kindly also suggest a software which converts audio file format asking these feature values while converting.

A: If you are using jAudio GUI, you can change the sample rate.
Here it is.. http://jmir.sourceforge.net/jAudio.html
Select Analysis->Sample Rate->

A: Issue of Sample Rate does not cause error. Only thing you just follow is of that it must be in .wav format also the file size should be less than 35 MB.

A: You are absolutely right - jAudio will throw exceptions if the sample rate or other audio file properties are not uniform in the input set. May I recommend SoX or gstreamer to preprocess your audio files to a single standard. That should eliminate the errors you are experiencing.


text:
Q: C++ atomic on iOS I have the next isolated test fragment inside an iOS project:
/// ...
std::atomic_bool ab;
ab.store(true);
bool expected = false;
while (!ab.compare_exchange_weak(expected, true));
assert(0);
// ...

Provided that ab is not modified by other threads, I expected, that the loop would be infinite, but after executing I found out that the assert is failing. Why is that happening?

A: compare_exchange_weak changes the first parameter to what was actually there. So after the first iteration of the loop expected has been changed to true. This then is fed back into the loop where the compare_exchange_weak succeeds and proceeds to fail the assertion.

A: If nothing is touching ab and nothing is touching expected, (and no other threads are running that could hit this area's memory,) then that assert should not fire off...
unless the compiler is helping you by eliminating dead code i.e. the while loop does nothing so don't include it and therefore you hit the assert.  Check your assembler output to be sure or add a global varaible counter to the loop so that the compiler won't kill this dead code for you.


text:
Q: SVN for classification with NA column on test data Its the follow I have two files one with the training data other with the test data without the class I want to predict and I am trying to execute the follow code:
full  <- bind_rows(train, test)

full$Survived <- factor(full$Survived)

train <- full[1:n,]
test <- full[n+1:total,]

model.svm <- svm(Survived~.,train)
predictions <- predict(model.svm,test)

But when I tried to predict give me the follow error:
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :contrasts can be applied only to factors with 2 or more levels

As I understand is because the class column is all NA's but don't know what to do about this, I already try to fill it with dummy values only to get the predictions and I get this:
Error in newdata[, object$scaled, drop = FALSE] : (subscript) logical subscript too long

Someone can tell me what I am doing wrong and how to correct?
Edit:
Note I am doing binary classification if it help.
Thanks in the advance.
EDIT:
The dataset is the titanic survived people, that I am using for learn how to use some models( I am begging to learn this kind of things).
str(full):
'data.frame':   1309 obs. of  12 variables:
 $ PassengerId: int  1 2 3 4 5 6 7 8 9 10 ...
 $ Survived   : Factor w/ 2 levels "0","1": 1 2 2 2 1 1 1 1 2 2 ...
 $ Pclass     : int  3 1 3 1 3 3 1 3 3 2 ...
 $ Name       : chr  "Braund, Mr. Owen Harris" "Cumings, Mrs. John Bradley (Florence Briggs Thayer)" "Heikkinen, Miss. Laina" "Futrelle, Mrs. Jacques Heath (Lily May Peel)" ...
 $ Sex        : chr  "male" "female" "female" "female" ...
 $ Age        : num  22 38 26 35 35 NA 54 2 27 14 ...
 $ SibSp      : int  1 1 0 1 0 0 0 3 0 1 ...
 $ Parch      : int  0 0 0 0 0 0 0 1 2 0 ...
 $ Ticket     : chr  "A/5 21171" "PC 17599" "STON/O2. 3101282" "113803" ...
 $ Fare       : num  7.25 71.28 7.92 53.1 8.05 ...
 $ Cabin      : chr  "" "C85" "" "C123" ...
 $ Embarked   : chr  "S" "C" "S" "S" ...

dput is to long to put it here.
I think I have some NA's in age is it a problem?


text:
Q: Calling Kotlin extension function from Java from kotlin.text package I'm trying to use toRegex() extension function from the kotlin.text package from my Java code. Here is the code of that file:
/*
 * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the license/LICENSE.txt file.
 */

@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("StringsKt")

package kotlin.text

/**
 * Converts the string into a regular expression [Regex] with the default options.
 */
@kotlin.internal.InlineOnly
public inline fun String.toRegex(): Regex = Regex(this)

/**
 * Converts the string into a regular expression [Regex] with the specified single [option].
 */
@kotlin.internal.InlineOnly
public inline fun String.toRegex(option: RegexOption): Regex = Regex(this, option)

/**
 * Converts the string into a regular expression [Regex] with the specified set of [options].
 */
@kotlin.internal.InlineOnly
public inline fun String.toRegex(options: Set<RegexOption>): Regex = Regex(this, options)

Unfortunately I had no success calling the function from Java code. I think I'm missing something. Here is my attempt:
import kotlin.text.StringsKt;
...

StringsKt.toRegex("some_string"); // Doesn't compile.

Doesn't compile.

A: This is caused by the @InlineOnly annotation on that function.

InlineOnly means that the Java method corresponding to this Kotlin function is marked private so that Java code can not access it (which is the only way to call an inline function without actually inlining it).

*

*From Andrey Breslav on the Kotlin forums.

Also, this is a potential duplicate of this question, although it doesn't directly ask about @InlineOnly.


text:
Q: How does this C++ template member function declaration work? Here is a snippet from the documentation of the Boost.Reflect library:
template<typename T>
struct xml_printer {
    xml_printer( const T& c ):self(c){}

    template<typename Type>
    static xml_printer<Type> make( const Type& t ) {
        return xml_printer<Type>(t);
    }

    template<typename Member, typename Class, Member Class::*p>
    void operator()( const char* name )const {
        std::cerr<<"<"<<name<<">"<<(self.*p)<<"</"<<name<<">\n";
    }
    const T& self;
};

The part I'm confused about is the declaration of operator() in the visitor:
template<typename Member, typename Class, Member Class::*p>
void operator()( const char* name )const

Particularly the Member Class::*p part. If I understand correctly, this type parameter is in place in order for the visitor to be able to resolve the member, and this is the type information which the library stores somehow for the member. However, it looks very unusual to me with two types written after each other. Could you explain to me how this works or perhaps provide an example that would call a function with such declaration?

A: Member Class::*p it's pointer to member of class Class with type Member.
So, something like this will call it's true
auto printer = xml_printer<T>();
printer.template operator()<int, T, &T::x>("x");

where x is member variable of type T with type int.
From docs, that you link
#define BOOST_REFLECT_VISIT_MEMBER( r, visitor, elem ) \
visitor.template operator()
<BOOST_TYPEOF(type::elem),type,&type::elem>( BOOST_PP_STRINGIZE(elem) );

A: Member Class::*p means that p is a pointer to Class member of type Member.
It's unrelated to template declarations, it's just a C++ syntax for pointer-to-member declaration.

A: Pointer to members are valid template arguments (see C++11 standard 14.1/4).
You'd call it like this:
xml_printer<foo> printer;
printer.operator()<some_type, foo, &foo::bar>("some string literal");