text:
Q: Black Screen with two videos using ExoPlayer2 I am trying to implement a small video gallery using ExoPlayer2, I have not trouble with the first couple of videos, but.. When I have played three or four videos, I have a black screen with the next error:
E/ExoPlayerImplInternal: Playback error.com.google.android.exoplayer2.ExoPlaybackException: com.google.android.exoplayer2.mediacodec.MediaCodecRenderer$DecoderInitializationException: Decoder init failed: OMX.Exynos.avc.dec, Format(1, null, null, video/avc, null, -1, null, [1900, 1200, -1.0], [-1, -1])
at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.maybeInitCodec(MediaCodecRenderer.java:479)
at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.reinitializeCodec(MediaCodecRenderer.java:1261)
at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.onInputFormatChanged(MediaCodecRenderer.java:1111)
at com.google.android.exoplayer2.video.MediaCodecVideoRenderer.onInputFormatChanged(MediaCodecVideoRenderer.java:552)
at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:647)
at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:536)
at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:164)
at android.os.HandlerThread.run(HandlerThread.java:65)

I found a lot of similiar issues with the same error at GitHub's project page with the solution, but no one resolve my problem. Can anyone help me? Thanks.

A: I tried to stop the ExoPlayerFactory.newSimpleInstance in all cases (onResume, onPause, onStop), and it works with me.see the way in code


text:
Q: Parsing objects of a JSON for input validation I want to use a database of valid ICAO and IATA airport codes for a discord bot input in typescript. However, I am not quite sure how to call the "icao" and "iata" contstructor of all objects, as each one is defined differently and there are thousands: e.g.:
"00AK": {
        "icao": "00AK",
        "iata": "",
        "name": "Lowell Field",
        "city": "Anchor Point",
        "state": "Alaska",
        "country": "US",
        "elevation": 450,
        "lat": 59.94919968,
        "lon": -151.695999146,
        "tz": "America\/Anchorage"
    },
"00AL": {
        "icao": "00AL",
        "iata": "",
        "name": "Epps Airpark",
        "city": "Harvest",
        "state": "Alabama",
        "country": "US",
        "elevation": 820,
        "lat": 34.8647994995,
        "lon": -86.7703018188,
        "tz": "America\/Chicago"
},

The bot uses the following to provide the METAR of a specific airport:
    name: 'metar',
    description: 'Provides the METAR report of the requested airport',
    category: CommandCategory.UTILS,
    executor: async (msg) => {
        const splitUp = msg.content.replace(/\.metar\s+/, ' ').split(' ');

         if (splitUp.length <= 1) {
             await msg.reply('please provide an ICAO airport code.');
             return Promise.resolve();
        }

        const icaoArg = splitUp[1];

         if (icaoArg.length !== 4)  {
             await msg.reply('please provide an ICAO airport code.');
             return Promise.resolve();
         }

        request({
            method: 'GET',
            url: `https://avwx.rest/api/metar/${icaoArg}`,
            headers: {
                Authorization: process.env.METAR_TOKEN },
        }, async (error, response, body) => {
            const metarReport = JSON.parse(body);å
            const metarEmbed = makeEmbed({
                title: `METAR Report | ${metarReport.station}`,
                description: makeLines([
                    '**Raw Report**',
                    metarReport.raw,
                    ,
                    '**Basic Report:**',
                    `**Time Observed:** ${metarReport.time.dt}`,
                    `**Station:** ${metarReport.station}`,
                    `**Wind:** ${metarReport.wind_direction.repr} at ${metarReport.wind_speed.repr}kts`,
                    `**Visibility:** ${metarReport.visibility.repr}${metarReport.units.visibility}`,
                    `**Temperature:** ${metarReport.temperature.repr}C`,
                    `**Dew Point:** ${metarReport.dewpoint.repr}C`,
                    `**Altimeter:** ${metarReport.altimeter.value.toString()} ${metarReport.units.altimeter}`,
                ]),

                fields: [
                    {
                        name: 'Unsure of how to read the raw report?',
                        value: 'Type \'**.metarhow**\' to learn how to read raw METARs',
                        inline: false
                    },

                ],
                footer: { text: 'This METAR report may not accurately reflect the weather in the simulator. However, it will always be similar to the current conditions present in the sim.' },
            });

            await msg.channel.send({ embeds: [metarEmbed] });

        });

    },
};

Currently, if a user provides an ICAO that's not valid the bot crashes, or if they provide a valid IATA, the discord api throws the user an error to provide a valid ICAO code. How would I go about cross referencing the user argument with the JSON so the bot does not crash when inputting an invalid ICAO? Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shiny Tabs with different groups of selection names I have a data set of multiple groups, different subject per group, and I'd like to build a shiny app to show the results of each subject in their respective groups with each group being represented as a tab within a shiny app. I feel like I am about 95% there and just can't figure out why the second tab refuses to select data (the first tab works perfectly).
Here is what my data look like:
library(tidyverse)
library(reshape2)
library(shiny)

groupID <- rep(1:2, each = 5)
Subject <- LETTERS[1:10]
var1 <- rnorm(n = length(Subject), mean = 0, sd = 1)
var2 <- rnorm(n = length(Subject), mean = 0, sd = 2)
var3 <- rnorm(n = length(Subject), mean = 0, sd = 2.5)
var4 <- rnorm(n = length(Subject), mean = 0, sd = 3)

df <- data.frame(groupID, Subject, var1, var2, var3, var4)

df_long <- df %>%
  melt(., id = c("groupID", "Subject"))

Here is my shiny approach thus far:
## UI
ui <- fluidPage(

  tabsetPanel(
    tabPanel("Grp1", fluid = T,
             selectizeInput(
               inputId = "Subject",
               label = "Select Subjects",
               choices = df_long %>% filter(groupID == 1) %>% distinct(., Subject) %>% pull(Subject),
               selected = "A",
               multiple = TRUE
             ),
             mainPanel(plotOutput(outputId = "grp1_plot"))),

    tabPanel("Grp2", fluid = T,
             selectizeInput(
               inputId = "Subject",
               label = "Select Subjects",
               choices = df_long %>% filter(groupID == 2) %>% distinct(., Subject) %>% pull(Subject),
               selected = "F",
               multiple = TRUE
             ),
             mainPanel(plotOutput(outputId = "grp2_plot")))
  )
)

## Server
server <- function(input, output){

  # get data
  grp1_dat <- reactive({
    dataset1 <- df_long %>%
      filter(Subject %in% input$Subject,
             groupID == 1)
    dataset1
  })

  grp2_dat <- reactive({
    dataset2 <- df_long %>%
      filter(Subject %in% input$Subject,
             groupID == 2)
    dataset2
  })

  # render the plots
  output$grp1_plot <- renderPlot({

    grp1 <- grp1_dat()

    grp1_plot <- ggplot(grp1, aes(x = variable, y = value, fill = Subject)) +
      geom_hline(aes(yintercept = 0), size = 1.1) +
      geom_rect(aes(ymin = -1, ymax = 1),
                xmin = 0,
                xmax = Inf,
                fill = "light grey") +
      geom_col(alpha = 0.8,
               position = position_dodge()) +
      ylim(-4, 4)

    print(grp1_plot)
  })

  output$grp2_plot <- renderPlot({

    grp2 <- grp2_dat()

    grp2_plot <- ggplot(grp2, aes(x = variable, y = value, fill = Subject)) +
      geom_hline(aes(yintercept = 0), size = 1.1) +
      geom_rect(aes(ymin = -1, ymax = 1),
                xmin = 0,
                xmax = Inf,
                fill = "light grey") +
      geom_col(alpha = 0.8,
               position = position_dodge()) +
      ylim(-4, 4)

    print(grp2_plot)
  })
}

shinyApp(ui, server)

You can see from the screenshots of my app that shiny has the two tabs but only tab1 works while tab2 produces an error and I'm not certain how to correct it?

A: You can't recycle on shiny change inputid to Subject2
library(tidyverse)
library(reshape2)
library(shiny)

groupID <- rep(1:2, each = 5)
Subject <- LETTERS[1:10]
var1 <- rnorm(n = length(Subject), mean = 0, sd = 1)
var2 <- rnorm(n = length(Subject), mean = 0, sd = 2)
var3 <- rnorm(n = length(Subject), mean = 0, sd = 2.5)
var4 <- rnorm(n = length(Subject), mean = 0, sd = 3)

df <- data.frame(groupID, Subject, var1, var2, var3, var4)

df_long <- df %>%
  melt(., id = c("groupID", "Subject"))

## UI
ui <- fluidPage(

  tabsetPanel(
    tabPanel("Grp1", fluid = T,
             selectizeInput(
               inputId = "Subject",
               label = "Select Subjects",
               choices = df_long %>% filter(groupID == 1) %>% distinct(., Subject) %>% pull(Subject),
               selected = "A",
               multiple = TRUE
             ),
             mainPanel(plotOutput(outputId = "grp1_plot"))),

    tabPanel("Grp2", fluid = T,
             selectizeInput(
               inputId = "Subject2",
               label = "Select Subjects",
               choices = df_long %>% filter(groupID == 2) %>% distinct(., Subject) %>% pull(Subject),
               selected = "F",
               multiple = TRUE
             ),
             mainPanel(plotOutput(outputId = "grp2_plot")))
  )
)

## Server
server <- function(input, output){

  # get data
  grp1_dat <- reactive({
    dataset1 <- df_long %>%
      filter(Subject %in% input$Subject,
             groupID == 1)
    dataset1
  })

  grp2_dat <- reactive({
    dataset2 <- df_long %>%
      filter(Subject %in% input$Subject2,
             groupID == 2)
    dataset2
  })

  # render the plots
  output$grp1_plot <- renderPlot({

    grp1 <- grp1_dat()

    grp1_plot <- ggplot(grp1, aes(x = variable, y = value, fill = Subject)) +
      geom_hline(aes(yintercept = 0), size = 1.1) +
      geom_rect(aes(ymin = -1, ymax = 1),
                xmin = 0,
                xmax = Inf,
                fill = "light grey") +
      geom_col(alpha = 0.8,
               position = position_dodge()) +
      ylim(-4, 4)

    print(grp1_plot)
  })

  output$grp2_plot <- renderPlot({

    grp2 <- grp2_dat()

    grp2_plot <- ggplot(grp2, aes(x = variable, y = value, fill = Subject)) +
      geom_hline(aes(yintercept = 0), size = 1.1) +
      geom_rect(aes(ymin = -1, ymax = 1),
                xmin = 0,
                xmax = Inf,
                fill = "light grey") +
      geom_col(alpha = 0.8,
               position = position_dodge()) +
      ylim(-4, 4)

    print(grp2_plot)
  })
}

shinyApp(ui, server)


text:
Q: NO_PUBKEY error in google cloud debian packages update I have a couple of Google Clouds compute instances (US, Germany, Australia)
While doing
apt-get update

today I get:
> Get:10 http://packages.cloud.google.com/apt
> google-cloud-packages-archive-keyring-stretch InRelease [3,876 B]
> Err:6 http://packages.cloud.google.com/apt cloud-sdk-stretch InRelease
>   The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 6A030B21BA07F4FB
> Err:7 http://packages.cloud.google.com/apt google-compute-engine-stretch-stable InRelease
>   The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 6A030B21BA07F4FB
> Err:10 http://packages.cloud.google.com/apt google-cloud-packages-archive-keyring-stretch InRelease
>   The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 6A030B21BA07F4FB

On all of them.
Is there anything I need to do, or is this a corruption on Google packages?
Thanks
Yves

A: If you followed the guide here: https://cloud.google.com/sdk/docs/install#deb and used the signed-by option, then you need to provide apt-key with the --keyring option:
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -

A: Found the issue here:
https://cloud.google.com/compute/docs/troubleshooting/known-issues#keyexpired
So you just need to run this before to apt-get update:
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -

A: Modern Debian 10 uses alternative scheme for registering package signing keys, following Ansible script demonstrates it:
- name: Add GCP Apt signing keys.
  ansible.builtin.apt_key:
    id: "{{ item }}"
    url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
    keyring: /usr/share/keyrings/gcp-deb-keys.gpg
  loop:
    # Rapture Automatic Signing Key, expires: 2023-03-02
    - "7F92E05B31093BEF5A3C2D38FEEA9169307EA071"
    # gLinux Rapture Automatic Signing Key, expires: 2022-12-04
    - "59FE0256827269DC81578F928B57C5C2836F4BEB"

- name: Add GCP repo for Cloud SDK.
  apt_repository:
    filename: "gcp-google-cloud-sdk"
    repo: "deb [signed-by=/usr/share/keyrings/gcp-deb-keys.gpg] https://packages.cloud.google.com/apt cloud-sdk-buster main"
    state: present
# Contains: google-compute-engine-oslogin, google-osconfig-agent
- name: Add GCP repo for Compute Engine setup.
  apt_repository:
    filename: "gcp-compute-engine"
    repo: "deb [signed-by=/usr/share/keyrings/gcp-deb-keys.gpg] https://packages.cloud.google.com/apt google-compute-engine-buster-stable main"
    state: present


text:
Q: Как перевести текстовый файл чисел в  числовой массив? Всем привет)
Как можно перевести текстовый файл состоящий из вещественных чисел в числовой массив.
Например
Есть файл *.txt
1 3.14 2 5 6
3 4 5 6 7
2 3 4 8 1

Надо их заносить в массив числовой.
Пытался через getline только он берет одну строку и потом через функцию atoi, но он считывает пробелы еще.
for(int i = 0; i<3; i++)
{
In.getline(array[i],100);
}

Есть пример, но значения в виде кучи записывает...
ifstream in("input.txt");
int i;
while (file) {
  file >> i;
}

A: Вот так можно в вектор считать, буквально одной строчкой:
std::ifstream is(filename);
std::vector<double> a;
std::copy(std::istream_iterator<double>(s), std::istream_iterator<double>(),
    std::back_inserter(a));

A: Можно ещё так:
std::ifstream is(filename);
std::vector<double> a((istream_iterator<double>(is)),
                      istream_iterator<double>());

(проверка, недавно обсуждалось здесь)


text:
Q: Custom stop method in R I'm trying to make the error system for an R package more testable, and I have several error subclasses which I use to detail the specific problem encountered.
MyError <- function (call, message, someOtherData) {

    structure(
        class = c('condition', 'error', 'myerror'),
        list(
            message      = message,
           call          = call,
           someOtherData = someOtherData
        )
    )
}

err <- MyError(call('f'), 'this is an error message', 'this is some other data')

R doesn't properly format the call part of the error (at least for my needs), so I convert the call to text, paste it to the error message, and throw an error with the call argument disabled.
stop("f(): this is an error message", call. = FALSE)

This isn't a great solution, as I can't extract the call argument from the error message anymore. Ideally the error object that is thrown should include the messsage, call, and any other data I wish to use during testing.
Question:
Is there a (non-hacky) way to add a generic method to the stop function for specific error subclasses? I would like to write something like:
stop.myError <- function (..., call. = False, domain = NULL) {
    # -- print the error message using some custom error formatting
    # -- and then throw the error object as usual.
}

Apart from displaying the error object with different formatting it should behave identically to the default stop function.
Thanks for any help you can offer. If the question needs clarification, leave a comment below.

A: Your 'class' is in the wrong order -- c("my", "error", "condition").
f <- function()
    stop(MyError(sys.calls(), "message", list()))

and then use tryCatch to catch your specific error.
tryCatch(f(), my=function(e) {
    msg = conditionMessage(e)
    cll = conditionCall(e)
    ## do what you want
}


text:
Q: How to insert multi language data in SQL Server using N? I know by using N'...' we can insert multi language data into SQL Server. But I don't know how to use it with parameters. Please help me..
My code is :
Alter proc proc_T_NewsAddUpdate
(
    @Id bigint,
    @Title nvarchar(500),
    @Description nvarchar(1000),
    @image nvarchar(200),
    @DateOfNews datetime,
    @CreatedBy bigint,
    @ModifiedBy bigint,
    @IsVisible int,
    @IsDeleted int
)
as
    if exists(select 1 from T_LatestNews where ID=@Id)
    begin
        Update t_LatestNews
        set Titlle = N@Title,
            DesCription = N@Description,
            Image = N@image,
            dateOfnews = @DateOfNews,
            modifiedDate = GETDATE(),
            ModifiedBy = @ModifiedBy,
            Isvisible = @IsVisible,
            isdeleted = @IsDeleted
         where
            ID=@Id

        select 1
    end
    else
    begin
        insert into t_latestnews (Titlle, Description, Image, dateofnews, CreatedDate, ModifiedDate, CreatedBy, ModifiedBy, isvisible, isdeleted)
        values(@Title, @Description, @image, @DateOfNews, GETDATE(), GETDATE(), @CreatedBy, @ModifiedBy, @IsVisible, @IsDeleted)

        select 1
    end

A: The simplest solution is to insert data in table as NVARCHAR data type, like below.
–Create Table
CREATE TABLE TBL_LANG

(

LNAME VARCHAR(50),

LTXT NVARCHAR(100)

)

–Insert "Hello World" in diffrent language
INSERT INTO TBL_LANG

VALUES ('English',N'Hello World')

INSERT INTO TBL_LANG

VALUES ('Hindi',N'हैलो दुनिया')

INSERT INTO TBL_LANG

VALUES ('Chines',N'你好世界')

INSERT INTO TBL_LANG

VALUES ('Urdu',N'ہیلو دنیا')

–View Table data
SELECT * FROM TBL_LANG

A: Modify your stored proc to look like this:
Alter proc proc_T_NewsAddUpdate
(
    @Id bigint,
    @Title nvarchar(500),
    @Description nvarchar(1000),
    @image nvarchar(200),
    @DateOfNews datetime,
    @CreatedBy bigint,
    @ModifiedBy bigint,
    @IsVisible int,
    @IsDeleted int
)
as
    if exists(select 1 from T_LatestNews where ID=@Id)
    begin
        Update t_LatestNews set Titlle=@Title,DesCription=@Description,Image=@image,dateOfnews=@DateOfNews,modifiedDate=GETDATE(),ModifiedBy=@ModifiedBy,Isvisible=@IsVisible,isdeleted=@IsDeleted where ID=@Id
        select 1
    end
    else
    begin
        insert into t_latestnews (Titlle,Description,Image,dateofnews,CreatedDate,ModifiedDate,CreatedBy,ModifiedBy,isvisible,isdeleted) values(@Title,@Description,
        @image,@DateOfNews,GETDATE(),GETDATE(),@CreatedBy,@ModifiedBy,@IsVisible,@IsDeleted)
        select 1
    end

Then call it like this:
exec proc_T_NewsAddUpdate
    @Id = 1,
    @Title = N'Sample Title',
    @Description =  N'Sample Description',
    @image =  N'Sample Image',
    @DateOfNews = '1/1/2000',
    @CreatedBy = 1,
    @ModifiedBy = 1,
    @IsVisible = 1,
    @IsDeleted = 1

A: Use nvarchar instead of varchar type.


text:
Q: How to get transaction history without certain state I try to get transaction history on corda.
I need to get the amount of the transaction for a certain period
My api for this :
@GET
@Path("transactions")
@Produces(MediaType.APPLICATION_JSON)
fun gettransatcions(): List<StateAndRef<ContractState>> {

    val TODAY = Instant.now()
    val pagingSpec = PageSpecification(DEFAULT_PAGE_NUM, 100)
    val start = TODAY.minus(1, ChronoUnit.HOURS)
    val end = TODAY.plus(1, ChronoUnit.HOURS)

    val recordedBetweenExpression = QueryCriteria.TimeCondition(
            QueryCriteria.TimeInstantType.RECORDED,
            ColumnPredicate.Between(start, end))

    val criteria = QueryCriteria.VaultQueryCriteria(timeCondition = recordedBetweenExpression,status = Vault.StateStatus.ALL)
    val results = rpcOps.vaultQueryBy<ContractState>(criteria, paging = pagingSpec)
    val size = results.states.count()

    return rpcOps.vaultQueryBy<ContractState>().states
}

where:
val rpcOps: CordaRPCOps
I can explicitly specify States  for which to receive transactions like:
val criteria = VaultQueryCriteria(contractStateTypes = setOf(Cash.State::class.java, DealState::class.java))

but, I need to get transactions across all states except for a certain.
Have corda got any mechanism for this ?

A: There is no type of query criteria that specifically excludes certain states. However, you can define a query criteria that specifically includes certain states, then combine that with your existing criteria using an AND composition:
val TODAY = Instant.now()
val pagingSpec = PageSpecification(DEFAULT_PAGE_NUM, 100)
val start = TODAY.minus(1, ChronoUnit.HOURS)
val end = TODAY.plus(1, ChronoUnit.HOURS)

val recordedBetweenExpression = QueryCriteria.TimeCondition(
        QueryCriteria.TimeInstantType.RECORDED,
        ColumnPredicate.Between(start, end))

val timeCriteria = QueryCriteria.VaultQueryCriteria(timeCondition = recordedBetweenExpression, status = Vault.StateStatus.ALL)
val typeCriteria = QueryCriteria.VaultQueryCriteria(contractStateTypes = setOf(State1::class.java, State2::class.java), status = Vault.StateStatus.ALL)
val combinedCriteria = timeCriteria.and(typeCriteria)
val results = rpcOps.vaultQueryBy<ContractState>(combinedCriteria, paging = pagingSpec)

This will retrieve all the states that meet both your time criteria and your type criteria.


text:
Q: How to set the default options on an existing plugin in a WP MU new user install When a new user signs up in WP MU install I would like to set the default options for a plugin that I have installed in the super admin account. I've read through so many posts but have not found out how to do this.

A: At the top of the api.php page before the class JSON_API line add the following code:
add_action( 'wpmu_new_blog', 'wpse_set_defaults' );

function wpse_set_defaults( $blog_id ) {
    global $json_api;

    switch_to_blog( $blog_id );

    // set the default controllers here
    $required_controllers = explode(",", "categories,posts,user,attachments");

    $id = 'json_api_controllers';

    $available_controllers = $json_api->get_controllers();
    $active_controllers = explode(',', get_option($id, 'core'));
    $action = "activate";

    foreach ($required_controllers as $controller) {
        if (in_array($controller, $available_controllers)) {
            if ($action == 'activate' && !in_array($controller, $active_controllers)) {
                $active_controllers[] = $controller;
            } else if ($action == 'deactivate') {
                $index = array_search($controller, $active_controllers);
                if ($index !== false) {
                    unset($active_controllers[$index]);
                }
            }
        }
    }

    $value = implode(',', $active_controllers);

    // get option and set it
    $option_exists = (get_option($id, null) !== null);

    if ($option_exists) {
        update_option($id, $value);
    } else {
        add_option($id, $value);
    }

    restore_current_blog();
}

You can set other options here as well.


text:
Q: Lex - recognizing ambiguant tokens All,
In my Lex file we recognize some operators as Tokens some of this operator are
":p"
and
":"

the problem is that any word witch starts with :p like ":presentation" is not recognized as
':' word             /*grammar*/

and a parse error is trigged due to the returned lex value ":p" as next Token
how can i resolve this ambiguity ?

A: You should instead define a lexer rule to match the entire "symbol" token, i.e. something like
:[a-zA-Z_][a-zA-Z0-9_]*    { yylval.symbol = strdup(yytext + 1); return SYMBOL; }

If you need to, you can do a check in this rule for :p and special-case it, e.g.:
:[a-zA-Z_][a-zA-Z0-9_]*    {
    if (strcmp(yytext, ":p") == 0) {
        return OP_P;
    }

    yylval.symbol = strdup(yytext + 1);
    return SYMBOL;
}


text:
Q: Work Problem With Pulling A Rope A uniform cable that is 2 pounds per feet and is 100 feet long hangs vertically from a pulley system at the top of a building (and the building is also 100 feet tall).
How much work is required to lift the cable until the bottom end of the cable is 20 feet below the top of the building?
$W=FD$
$F=2\Delta y$
$D=80-y$  ??
$\int_{0}^{100}2(80-y)dy$
Or am I mixing up the limits of integration and the distance? Or am I completely wrong? Thanks for the help. I appreciate it.

A: Your integral is wrong. As you know, the total work done is given by the total force exerted over a distance. In this case the force on the cable is variable. We know that the starting weight is $200$ pounds and decreases by $2$ pounds for every foot that the cable is raised. Therefore, the force is given by $$F(x)=200-2x$$ where $x$ is the distance above the ground of the bottom of the cable. From this we get that the total work is
$$\int_{0}^{80}(200-2x) dx=9600\text{ ft lb}$$

A: There are many ways you can solve this problem, let's first do it in your way. Note that i'm not bothering with units. Because of feet, pound. :( not nice. Also let me note that we must talk about the $g$ (gravitation constant) because if we don't say anything about it answer wşll be no work is required.
Mass of hanging part of rope is $2(100-y)$, force acting on this part of rope is $g.2(100-y)=gm$. Work is given by $Force.Distance$. Then the integral becomes
$$ \int_0^{80}2g(100-y)\ dy = 9600$$
Another way to solve is to use energy which can be calculated easily, initial potential energy is
$$ \int_0^{100} 2gy\ dy=10000 $$
Final potential energy
$$\int_{80}^{100} 2gy \ dy + \int_0^{80} 200g dy=3600+16000 $$


text:
Q: MySQL database backup: performance issues Folks,
I'm trying to set up a regular backup of a rather large production database (half a gig) that has both InnoDB and MyISAM tables. I've been using mysqldump so far, but I find that it's taking increasingly longer periods of time, and the server is completely unresponsive while mysqldump is running.
I wanted to ask for your advice: how do I either

*

*Make mysqldump backup non-blocking - assign low priority to the process or something like that, OR

*Find another backup mechanism that will be better/faster/non-blocking.
I know of the existence of MySQL Enterprise Backup product (http://www.mysql.com/products/enterprise/backup.html) - it's expensive and this is not an option for this project.
I've read about setting up a second server as a "replication slave", but that's not an option for me either (this requires hardware, which costs $$).
Thank you!
UPDATE: more info on my environment: Ubuntu, latest LAMPP, Amazon EC2.

A: If replication to a slave isn't an option, you could leverage the filesystem, depending on the OS you're using,

*

*Consistent backup with Linux Logical Volume Manager (LVM) snapshots.

*MySQL backups using ZFS snapshots.

*The joys of backing up MySQL with ZFS...
I've used ZFS snapshots on a quite large MySQL database (30GB+) as a backup method and it completes very quickly (never more than a few minutes) and doesn't block. You can then mount the snapshot somewhere else and back it up to tape, etc.

A: Edit: (previous answer was suggestion a slave db to back up from, then I noticed Alex ruled that out in his question.)
There's no reason your replication slave can't run on the same hardware, assuming the hardware can keep up.  Grab a source tarball, ./configure --prefix=/dbslave; make; make install; and you'll have a second mysql server living completely under /dbslave.
EDIT2: Replication has a bunch of other benefits, as well.  For instance, with replication running, you'll may be able to recover the binlog and replay it on top your last backup to recover the extra data after certain kinds of catastrophes.
EDIT3: You mention you're running on EC2.  Another, somewhat contrived idea to keep costs down is to try setting up another instance with an EBS volume.  Then use the AWS api to spin this instance up long enough for it to catch up with writes from the binary log, dump/compress/send the snapshot, and then spin it down.  Not free, and labor-intensive to set up, but considerably cheaper than running the instance 24x7.

A: Try mk-parallel-dump utility from maatkit (http://www.maatkit.org/)
regards,

A: Something you might consider is using binary logs here though a method called 'log shipping'. Just before every backup, issue out a command to flush the binary logs and then you can copy all except the current binary log out via your regular file system operations.
The advantage with this method is your not locking up the database at all, since when it opens up the next binary log in sequence, it releases all the file locks on the prior logs so processing shouldn't be affected then. Tar'em, zip'em in place, do as you please, then copy it out as one file to your backup system.
An another advantage with using binary logs is you can restore up to X point in time if the logs are available. I.e. You have last year's full backup, and every log from then to now. But you want to see what the database was on Jan 1st, 2011. You can issue a restore 'until 2011-01-01' and when it stops, your at Jan 1st, 2011 as far as the database is concerned.
I've had to use this once to reverse the damage a hacker caused.
It is definately worth checking out.
Please note... binary logs are USUALLY used for replication. Nothing says you HAVE to.

A: Adding to what Rich Adams and timdev have already suggested, write a cron job which gets triggered on low usage period to perform the slaving task as suggested to avoid high CPU utilization.
Check mysql-parallel-dump also.


text:
Q: MVVM Framework: Performance I'm currently searching what will be the Framework that we will use for our nexts applications. Currently we have applications running with winform and we plan to switch slowly to WPF(with new application, and then refactoring the GUI). We are a team of 9 people working this solution.
We have a big solution(currently, 300+ VS projects, ~1'500'000 line of code), so when choosing a framework, we are looking for something which will promote a clean code, a good infrastructure, but also a framework that will not slow(too much) the application.
Currently, I'm mainly interessted in Prism(which seems to be a little bit complex to fully understand) and Caliburn.Micro.
The Caliburn.Micro seems easier to use, but I'm a little worried that all those convention oriented stuff means that a lot of things will be done using Reflection on runtime.
Am I correct? Or is this something done at the compilation ?
Also I'm not sure I should consider MVVM Light, since it lacks of documentation/targeted application sizes.

A: First of all, Prism is not a MVVM framework. There is Prism.MVVM and it is a very lightweight MVVM library and it's independent of Prism.
Second, this <ListBox x:Name="Products" /> automatically databound to viewmodel should not be a performance problem in Caliburn.Micro, because plain Binding in WPF uses refelection anyway. Not sure if Caliburn uses reflection internally as well, but even if it does, it's hardly noticable at runtime if you dont do it in iterative scenario, e.g. inside ItemsScontrol with 1000+ items. If you experience preformance issues, nothing prevents you from writing it the standard way. However, the added value of this is questionable. IMO it brings more problems than it solves
If I may give you my advice, don't use any MVVM framework. All you need is INotifyPropertyChanged implementation and DelegateCommand (ICommand implementation). In some special cases you may need EventAggregator. Now tell me, are those three classes worth a framework? No, the aren't. Why introduce a dependency to a third party library?
If you are going to start such a large solution, the investment to write your own base class library is negligible. You can always take the source code of a class or two from Prism and use them in your own library.
The problem with those framework is that developers tend to over-engineer simple scenarios, such as using EventAggregator where plain event or even direct reference is more suitable. Or take Prism as an example, they use regions and view injection where simple ItemsControl could be used.
After 6 years experience with WPF I became a big proponent of ViewModel-First approach. MVVM then becomes much simpler. But most frameworks work better with View-First approach.
So, my vote is to not use any MVVM framework. If you have to use one, choose Prism.MVVM. And look at the source codes, they are well written.

A: I have used CM for a few years, start back when it was 1.1.  I came over from PRISM.  While I agree for some of the comments and points of view from other posters, you truly only option at this stage is to get the library/framework (which ever you choose to play with), wire it up and run with it a little bit in your off time from major projects.  Implementing it on your "paid time" might be less than beneficial since you will undoubtedly have questions while "experimenting".
Experiment first then make your decision.  Want separation of concerns? Want rapid development? Want to be able to drop a control on workspace name it and it will just work (assuming it has a built-in convention, or create your own convention for a 3rd party control), wire some viewmodel code up to a property or method that you named the control, then give Caliburn.Micro a try.  Don't want to use Caliburn's conventions then don't. Just about everything for CM is modularized in to core needs with Nuget installs.
There are many MVVM frameworks as well as libraries all have different niche areas some are multi-platform, some are laser targeted on 1 platform.  You can only use what you try and at the end of the day if you find something you like using and it works for you and your team, then it (framework/library) is the one that should be targeted.
Example of why I left PRISM
On the View
<Button x:Name="ClickMe" />
In the ViewModel
public void ClickMe()
{
}

public string FirstName
{
  get{...}
  set
{
    _firstname = value;
    NotifyOfPropertyChange();
    NotifyOfPropertyChange( () => CanClickMe); )
}

public bool CanClickMe
{
    get { return !string.IsEmptyOrNull(_firstname); }
}

A: Most WPF performance problems are not caused by the MVVM framework but how you implement your WPF application (e.g. are you using virtualized lists?). I think you should select your MVVM framework depending on your function needs (are all functionalities available, e.g. a command implementation, view model base class).
It is more important to define conventions and rules for implementing your MVVM/WPF and select the MVVM framework based on these rules. Some conventions and rules can be found in my article about recommendations and best practices for implementing MVVM and XAML/.NET applications.
There are lots of resources about choosing the right MVVM framework, for example:

*

*What framework for MVVM should I use?

*https://social.msdn.microsoft.com/Forums/vstudio/en-US/c8accd7e-69c1-48af-bf5a-4275910c2b9e/which-mvvm-framework-to-choose


text:
Q: Cloudflare 522, 525 connection timed out My website keeps giving 522 connection timeout error. we contacted the cloudflare support team and found that there are some packet loss. because of which we are getting this error.
Can you please help me how can we resolve the packet loss issue and fix  this problem asap.
below is the response received from the cloudflare support team
I have checked the network path from an example location where we saw the errors and I can see that there is some packet loss outside of our network reaching your origin server:
      HOST: ***                                 Loss%   Snt   Last   Avg  Best  Wrst StDev
  1.|-- 108.162.228.1                            0.0%    30   31.3   5.7   0.8  31.3   8.1
  2.|-- 141.101.67.64                            0.0%    30    1.3  13.2   0.4 179.9  35.5
  3.|-- 108.170.245.6                            0.0%    30    0.9   4.7   0.5  63.7  11.9
  4.|-- 209.85.248.117                           0.0%    30    1.1  44.3   1.1 1047. 190.4
  5.|-- 142.250.229.254                         20.0%    30  153.1 514.9 152.5 3253. 725.9
  6.|-- 216.239.57.136                          26.7%    30  152.9 348.4 152.2 1219. 407.3
  7.|-- 142.250.231.184                          0.0%    30  1216. 779.1 152.1 3286. 1171.2
  8.|-- 142.250.235.39                           3.3%    30  153.5 456.1 152.9 3266. 821.6
  9.|-- 209.85.247.43                            6.7%    30  158.4 431.8 158.4 3269. 667.3
 10.|-- 108.170.235.197                         26.7%    30  159.2 466.9 158.2 3211. 710.2
 11.|-- 172.253.72.135                          13.3%    30  1288. 636.1 159.2 3326. 880.8
 12.|-- 209.85.255.130                           3.3%    30  303.6 621.1 233.1 3371. 685.0
 13.|-- 209.85.245.232                          10.0%    30  300.5 315.0 290.7 387.7  22.3
 14.|-- 216.239.35.167                          10.0%    30  330.1 467.9 286.2 3409. 617.8
 15.|-- 66.249.95.23                            76.7%    30  302.5 312.4 299.5 364.3  23.0
 16.|-- ???                                     100.0    30    0.0   0.0   0.0   0.0   0.0
 17.|-- ???                                     100.0    30    0.0   0.0   0.0   0.0   0.0
 18.|-- ???                                     100.0    30    0.0   0.0   0.0   0.0   0.0
 19.|-- ???                                     100.0    30    0.0   0.0   0.0   0.0   0.0
 20.|-- ???                                     100.0    30    0.0   0.0   0.0   0.0   0.0
 21.|-- 205.177.185.35.bc.googleusercontent.com 96.7%    30  242.1 242.1 242.1 242.1   0.0


text:
Q: internal energy calculation of superheated vapor I know that steam behaves like an ideal gas. Thus, the internal energy is a function only of temperature. I also know that $U=C_{V}(T_2-T_1)$, where
$C_V$ is the specific heat at constant volume. My question is:
Since $C_V$ is a function of temperature, which value of $C_V$ should I take, or should I just use the values of internal energies on the steam tables? Thanks in advance!

A: When the specific heat varies with temperature, you need an integral to compute the change in internal energy:
$$
\Delta U = \int_{T_1}^{T_2} c_V(T) \, dT
$$
If you have a table of the specific heats at various temperatures, you can make a numerical estimate of this integral using the trapezoidal rule.  For example, suppose that we are trying to find the change in internal energy between 400 K and 600 K and we know that the specific heat is $1.901 \frac{\text{kJ}}{\text{kg} \cdot \text{K}}$ at 400 K; $1.954 \frac{\text{kJ}}{\text{kg} \cdot \text{K}}$ at 500 K; and $2.015 \frac{\text{kJ}}{\text{kg} \cdot \text{K}}$ at 600 K.  Then $\Delta U$ is approximately
\begin{align}
&\frac{1.901 \frac{\text{kJ}}{\text{kg} \cdot \text{K}} + 1.954 \frac{\text{kJ}}{\text{kg} \cdot \text{K}}}{2} \cdot (500 \,\text{K} - 400 \,\text{K}) \\
+ \,&\frac{1.954 \frac{\text{kJ}}{\text{kg} \cdot \text{K}} + 2.015 \frac{\text{kJ}}{\text{kg} \cdot \text{K}}}{2} \cdot (600 \,\text{K} - 500 \,\text{K}) \\
= \,&391.2 \,\frac{\text{kJ}}{\text{kg}}
\end{align}


text:
Q: Optimization application trying to understand the wording
This problem I encountered, and Im trying to figure out. what is the meaning of a channel?

A: A short boat that can enter the channel

A long boat that cannot enter the channel

The maximum length of a boat?
Sorry that I drew boats as lines. Too much simplified. But it will help to solve the problem.


text:
Q: Compile java to .jar file dependency Ive found an opensource java application that i want to use to generate a document however i know very little about java and even less about maven.
The project is Stencil Template Engine
My plan is to include the above as a dependency in a spring boot mvc application so i can use the Java API to render a document,  however my issues are:

*

*The above project is not listed a maven so i cant import it.

*i can see a number of .java files nested into subfolders which im assuming i need to compile to a .class file. Attempts have failed

*Ive added the dependency to the pom.xml file as instructed in the readme but it errors because it cant find the jar file

*I cant find a way to import maven dependencies listed in the pom file

*javac commands have all failed

Could someone please recommend a way of cloning and building the above into a jar file,

A: Below is the text from README file of the github link you have.
Try to add both maven repository and maven dependency in your pom.xml
For example add this in your existing pom xml:
<repositories>
    <repository>
        <id>clojars.org</id>
        <url>https://repo.clojars.org</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>io.github.erdos</groupId>
        <artifactId>stencil-core</artifactId>
        <version>0.3.29</version>
    </dependency>
</dependencies>

From README file

Latest stable version is 0.3.29
Latest snapshot version is 0.3.30-SNAPSHOT
If you are using Maven, add the followings to your pom.xml:
The dependency:
<dependency>
  <groupId>io.github.erdos</groupId>
  <artifactId>stencil-core</artifactId>
  <version>0.3.29</version>
</dependency>

And the Clojars repository:
<repository>
  <id>clojars.org</id>
  <url>https://repo.clojars.org</url>
</repository>

Alternatively, if you are using Leiningen, add the following to the :dependencies section of your project.clj file: [io.github.erdos/stencil-core "0.3.29"]
Previous versions are available on the Stencil Clojars page.


text:
Q: Symfony2 (as php-fpm, behind nginx) not Last-Modified or ETage headers sent? $response = $this->render("index.html.twig", []);

$response->setPublic();
$response->setVary("Cookie");
$response->setExpires($cache->getExpires());
$response->setLastModified($cache->getLastModified());
$response->setETag($cache->getETag());

"Expires" header passed. But not "Last-Modified" or "ETag"

A: Problem solved: disable SSI in nginx configuration


text:
Q: Erro Unit Test [Wanted but not invoked] mockito Doubt:
Good Night,
I'm doing some testing on my service and I'm having trouble performing the test in the delete method.
I wonder if anyone ever had this error and can be helping me.
The error occurs when I do the scan. What is reported is that the method was not using.
Exception:
Wanted but not invoked:
usuariosRepository.findRow(5);
-> at br.com.fortalezaserv.services.impl.tests.RepositoryUsuariosServiceTest.deveExcluirPorId(RepositoryUsuariosServiceTest.java:74)

However, there were other interactions with this mock:
-> at br.com.fortalezaserv.services.impl.RepositoryUsuariosService.excluir(RepositoryUsuariosService.java:74)

at br.com.fortalezaserv.services.impl.tests.RepositoryUsuariosServiceTest.deveExcluirPorId(RepositoryUsuariosServiceTest.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Code:
@ContextConfiguration(classes = TestContext.class)
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class RepositoryUsuariosServiceTest {

private RepositoryUsuariosService usuarioService;
private UsuariosRepository usuariosRepositoryMock;

private Usuarios usuario;
private Long ID = Long.valueOf(5l);

/**
 *
 */
@Before
public void setUp() {
    usuario = new Usuarios();
    usuario.setEmail("email@me.com");
    usuario.setHash("nuadw");
    usuario.setLogin("Login");
    usuario.setNome("Name");
    usuario.setPassword("89331n9183n193n1n9319n3189");
    usuarioService = new RepositoryUsuariosService();

    usuariosRepositoryMock = mock(UsuariosRepository.class);
    usuarioService.setUsuarioRepository(usuariosRepositoryMock);
}

/**
 * @throws QualityException
 */
@Test
public void deveExcluirPorId() throws QualityException {
    when(usuariosRepositoryMock.findRow(ID)).thenReturn(null);
    usuarioService.excluir(ID);
    verify(usuariosRepositoryMock, times(1)).findRow(ID);
    verify(usuariosRepositoryMock, times(1)).delete(ID);
    verifyNoMoreInteractions(usuariosRepositoryMock);
}
 }

A: You have not added MockitoJUnitRunner in @RunWith clause. Since you already have SpringJunitRunner you cannot add another one (link for details).
As an alternative, try MockitoAnnotations.initMocks(this); in the @Before's setUp method.
Also one more suggestion, looks like you have added setters in your RepositoryUsuariosService service for testing. Avoid that by using @Mock annotation to mock  UsuariosRepository class and then @InjectMocks in RepositoryUsuariosService which automatically inserts all the mocks.

A: I solved the problem here.
It was a failure of my logic, my delete function don't have return. That method don't performs any query to delete.
I then switched to the test:
@Test
public void deveExcluirPorId() throws QualityException {
    usuarioService.excluir(ID);
    verify(usuariosRepositoryMock, times(1)).delete(ID);
    verifyNoMoreInteractions(usuariosRepositoryMock);
}

Thanks!


text:
Q: how to use jaxb2 maven plugin with inline XSD? I am trying to generate marshalling and unmarshalling objects using maven jaxb2 plugin.
But I dont have the .xsd file for the .wsdl.
the schema definition is inline.
Please let me know how to proceed ?

A: Use the wsdl parameter in the plugin config: jaxb2-maven-plugin

A: Here is the Maven plugin to work with WSDL files:
http://jax-ws-commons.java.net/jaxws-maven-plugin/


text:
Q: Typescript Definition. Named Function Expression (NFE) I am looking at the following JS which is one of many in the project I am creating a .d.ts file for.
BatchBuffer.js
var Buffer = function(size)
 {

     this.vertices = new ArrayBuffer(size);

     /**
      * View on the vertices as a Float32Array for positions
      *
      * @member {Float32Array}
      */
     this.float32View = new Float32Array(this.vertices);

     /**
      * View on the vertices as a Uint32Array for uvs
      *
      * @member {Float32Array}
      */
     this.uint32View = new Uint32Array(this.vertices);
 };

 module.exports = Buffer;

 Buffer.prototype.destroy = function(){
   this.vertices = null;
   this.positions = null;
   this.uvs = null;
   this.colors  = null;
 };

A search on Google to here tells me that this is a Named Function Expression (NFE) but I started to get lost. The module is adding additional confusion.
How would one define this correctly? The name is a bugbear (BatchBuffer or Buffer) and does this this look accurate?
export module BatchBuffer {

    export var vertices: ArrayBuffer;
    export var float32View: number[];
    export var uint32View: number[];

    export function destroy(): void;

}

I keep hitting these similar NFE files so for my definition to be accurate, I feel I need advice or confirmation.
Thanks.
Edited.
See Ryan's Answer.
Most other classes in the project looked (similar!) to this pseudo for example:
MyClass.js
function MyClass(something)
{
    /**
     * Some property
     *
     * @member {number}
     */
    this.something = something;
}

MyClass.prototype.constructor = MyClass;
module.exports = MyClass;

MyClass.prototype.hi = function ()
{
}

I was assigning meaning to something which appears to be the same. Although the details escape me. To know it is a class suits me fine.

A: What you have here is a class -- it's intended to be instantiated with new (you can tell because it assigns a function to a property of prototype), and it has properties and a method.
Your file should look something like this:
declare class Buffer {
  constructor(size: number);

  vertices: ArrayBuffer;
  float32View: Float32Array;
  uint32View: Float32Array;

  uvs: any; // not sure of type
  colors: any; // not sure of type
  positions: any; // not sure of type

  destroy(): void;
}

// expresses "module.exports = Buffer"
export = Buffer;


text:
Q: Convert 10 nodes to 3 nodes This is a module of my project, the followin program is for 10 nodes, if i try converting it to 3 nodes i am not able to execute the program. any help is appreciated
enter code here
# Define options
set val(chan) Channel/WirelessChannel    ;# channel type
set val(prop) Propagation/TwoRayGround   ;# radio-propagation model

set val(netif)          Phy/WirelessPhy            ;# network interface type
set val(mac)            Mac/802_11                 ;# MAC type
set val(ifq)            Queue/DropTail/PriQueue    ;# interface queue type
set val(ll)             LL                         ;# link layer type
set val(ant)            Antenna/OmniAntenna        ;# antenna model
set val(ifqlen)         50                         ;# max packet in ifq
set val(nn)             10                      ;# number of mobilenodes
set val(rp)             DumbAgent                    ;# routing protocol
set val(x)              600                ;# X dimension of topography
set val(y)              600                ;# Y dimension of topography

Mac/802_11 set dataRate_ 11Mb
# Global Variables
set ns_ [new Simulator]
set tracefd [open project1.tr w]
$ns_ trace-all $tracefd
set namtrace [open project1.nam w]
$ns_ namtrace-all-wireless $namtrace $val(x) $val(y)
# set up topography object
set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
# Create God
create-god $val(nn)
# Create channel
set chan_1_ [new $val(chan)]
$ns_ node-config -adhocRouting $val(rp) \
    -llType $val(ll) \
    -macType $val(mac) \
    -ifqType $val(ifq) \
    -ifqLen $val(ifqlen) \
    -antType $val(ant) \
    -propType $val(prop) \
    -phyType $val(netif) \
    -topoInstance $topo \
    -agentTrace OFF \
    -routerTrace OFF \
    -macTrace ON \
    -movementTrace ON \
    -channel $chan_1_
for {set i 0} {$i < [expr $val(nn)]} {incr i} {
set node_($i) [$ns_ node]
$node_($i) random-motion 0;
set mac_($i) [$node_($i) getMac 0]
$mac_($i) set RTSThreshold_ 3000}
$node_(0) set X_ 200.0
$node_(0) set Y_ 360.0
$node_(0) set Z_ 0.0

$node_(1) set X_ 100.0
$node_(1) set Y_ 100.0
$node_(1) set Z_ 0.0

$node_(2) set X_ 400.0
$node_(2) set Y_ 400.0
$node_(2) set Z_ 0.0

$node_(3) set X_ 280.0
$node_(3) set Y_ 140.0
$node_(3) set Z_ 0.0

$node_(4) set X_ 100.0
$node_(4) set Y_ 320.0
$node_(4) set Z_ 0.0

$node_(5) set X_ 70.0
$node_(5) set Y_ 210.0
$node_(5) set Z_ 0.0

$node_(6) set X_ 440.0
$node_(6) set Y_ 310.0
$node_(6) set Z_ 0.0

$node_(7) set X_ 490.0
$node_(7) set Y_ 320.0
$node_(7) set Z_ 0.0

$node_(8) set X_ 520.0
$node_(8) set Y_ 280.0
$node_(8) set Z_ 0.0

$node_(9) set X_ 560.0
$node_(9) set Y_ 360.0
$node_(9) set Z_ 0.0
$ns_ at 0.0 "$node_(0) label AP1"
$ns_ at 0.0 "$node_(1) label N1"
$ns_ at 0.0 "$node_(2) label MN1"
$ns_ at 0.0 "$node_(3) label MN2"
$ns_ at 0.0 "$node_(4) label MN3"
$ns_ at 0.0 "$node_(5) label MN4"
$ns_ at 0.0 "$node_(6) label MN5"
$ns_ at 0.0 "$node_(7) label MN6"
$ns_ at 0.0 "$node_(8) label MN7"
$ns_ at 0.0 "$node_(9) label AP2"

$ns_ at 0.0 "$node_(0) add-mark m1 green circle"
$ns_ at 0.0 "$node_(1) add-mark m1 red circle"
$ns_ at 0.0 "$node_(2) add-mark m1 yellow circle"
$ns_ at 0.0 "$node_(3) add-mark m1 blue circle"
$ns_ at 0.0 "$node_(4) add-mark m1 purple circle"
$ns_ at 0.0 "$node_(5) add-mark m1 pink circle"
$ns_ at 0.0 "$node_(6) add-mark m1 red circle"
$ns_ at 0.0 "$node_(7) add-mark m1 plum circle"
$ns_ at 0.0 "$node_(8) add-mark m1 yellow circle"
$ns_ at 0.0 "$node_(9) add-mark m1 grey circle"

set AP_ADDR1 [$mac_(0) id]
$mac_(0) ap $AP_ADDR1
set AP_ADDR2 [$mac_([expr $val(nn) - 1]) id]
$mac_([expr $val(nn) - 1]) ap $AP_ADDR2
$mac_(1) ScanType ACTIVE
for {set i 3} {$i < [expr $val(nn) - 1]} {incr i} {
    $mac_($i) ScanType PASSIVE      ;
}
$ns_ at 1.0 "$mac_(2) ScanType ACTIVE"
Application/Traffic/CBR set packetSize_ 1023
Application/Traffic/CBR set rate_ 256Kb

for {set i 1} {$i < [expr $val(nn) - 1]} {incr i} {
        set udp1($i) [new Agent/UDP]
        $ns_ attach-agent $node_($i) $udp1($i)
    set cbr1($i) [new Application/Traffic/CBR]
    $cbr1($i) attach-agent $udp1($i)
}

set null0 [new Agent/Null]
$ns_ attach-agent $node_(1) $null0
$ns_ connect $udp1(2) $null0

set null1 [new Agent/Null]
$ns_ attach-agent $node_(1) $null1
$ns_ connect $udp1(3) $null1

set null2 [new Agent/Null]
$ns_ attach-agent $node_(1) $null2
$ns_ connect $udp1(4) $null2

set null3 [new Agent/Null]
$ns_ attach-agent $node_(1) $null3
$ns_ connect $udp1(5) $null3

set null4 [new Agent/Null]
$ns_ attach-agent $node_(1) $null4
    $ns_ connect $udp1(6) $null4

set null5 [new Agent/Null]
$ns_ attach-agent $node_(1) $null5
$ns_ connect $udp1(7) $null5

set null6 [new Agent/Null]
$ns_ attach-agent $node_(1) $null6
$ns_ connect $udp1(8) $null6

for {set i 0} {$i < [expr $val(nn)]} {incr i} {
$ns_ initial_node_pos $node_($i) 30
}

$ns_ at 8.0 "$cbr1(2) start"
$ns_ at 2.0 "$cbr1(3) start"
$ns_ at 3.0 "$cbr1(4) start"
$ns_ at 4.0 "$cbr1(5) start"
$ns_ at 5.0 "$cbr1(6) start"
$ns_ at 6.0 "$cbr1(7) start"
$ns_ at 7.0 "$cbr1(8) start"

$ns_ at 10.0 "$node_(4) setdest 590.0 350.0 1000.0"

$ns_ at 35.0 "$node_(5) setdest 460.0 360.0 1000.0"
$ns_ at 50.0 "$node_(3) setdest 590.0 350.0 1000.0"
$ns_ at 52.0 "$node_(3) setdest 100.0 360.0 1000.0"

$ns_ at 100.0 "stop"
$ns_ at 100.0 "puts \"NS EXITING...\" ; $ns_ halt"

proc stop {} {
global ns_ tracefd
$ns_ flush-trace
close $tracefd
exec nam project1.nam
exit 0
}
puts "Starting Simulation..."
$ns_ run

This is a module of my project, the followin program is for 10 nodes, if i try converting it to 3 nodes i am not able to execute the program. any help is appreciated

A: Just reduce all relevant lines to use nodes { 0, 1, 2 } only,
and edit the remaining lines, until you have a usable result.
( I used 5 minutes, pure guess with some lines, but it works.)
Example, your edited file, "3-DSR.tcl"
Link at 'Google Docs' https://drive.google.com/file/d/0B7S255p3kFXNRFFlaTRGaWt1V3M/view?usp=sharing
-

A: 3-DSR.tcl :  Pure experimental // sketchy.
I just did some random changes, until :
1) I got a result, that worked with no errors.
2) And did one more change, to have all three nodes visible in 'nam'.
*** Actually I don't know how ns2 simulations are working, and why.
But : Long time experience (~5 years) building ns2-[all-versions], [all additional protocols], binary ns2 packages, patches, and thousands of simulations tests : I sometimes have the luck getting new things to work.


text:
Q: How to set the cpumask of an unbound workqueue from within the kernel? I've noticed it's possible to set the cpumask of all unbound workqueues using  workqueue_set_unbound_cpumask(), however I don't see anything that will target a specific workqueue. The real thorn in my side is that struct workqueue_struct is defined within the source file, so I can't access any of its memebers.
One solution I have is to allocate a new struct workqueue_attrs and call apply_workqueue_attrs(). This would be fine if not for the fact that I can't access the aforementioned workqueue's unbound_attrs member. There seem to be some functions for copying but they are all internal. So now I'm left to reselect values for nice and no_numa, which is irritating since I have to pay attention to whether the workqueues are ordered and if they were allocated with WQ_HIGHPRI.
I know it's possible to do this is userspace with sysfs, but I don't want the user to have to track every workqueue that gets created and pin them all manually, nor have to pin every unbound workqueue.
Hopefully I'm missing something and there is an easier way. Code below for reference.
struct workqueue_struct* wq = alloc_workqueue(name, WQ_UNBOUND | WQ_HIGHPRI);
struct workqueue_attrs* attrs = alloc_workqueue_attrs(GFP_KERNEL);

/* Yuck, setting WQ_HIGHPRI is just declaring intent */
attrs->nice = MIN_NICE;
attrs->no_numa = 0;
cpumask_parse(..., attrs->cpumask);

apply_workqueue_attrs(wq, attrs);


text:
Q: omitting 'def' in Groovy declarations In Groovy, it appears that the following declarations are both legal
private final results = []
private final def results = []

Is there any difference between these two?
Thanks,
Don

A: See this question: Groovy: what's the purpose of "def" in "def x = 0" ?


text:
Q: PHP PDO mysql counting rows returned There are a lot of questions on this and I have done a lot of research. However, I am still wondering if I am doing this right.
Here is my statement (I've simplified it):
    try {
        $stmt = $pdc_db->prepare("SELECT * FROM table WHERE color = :color");
        $stmt->bindValue(':color', $selected_color);
        $stmt->execute();
        $color_query = $stmt->fetchAll();
    } catch(PDOException $e) { catchMySQLerror($e->getMessage()); }

Now, I am using the following to see if this has returned any results:
if (count($color_query) > 0) {

This works, HOWEVER... the SELECT statement will only return one result. So now to access stuff in the results, I am using $color_query[0][colorname]. I know this is because I am using fetchAll(), but I really want to be using fetch()
But if I just use fetch(), I am losing the ability to do a count(), which is pretty simple to me. I know I can do a separate query and check the results of SELECT COUNT(*), but that seems like more work (setting two separate queries up for each)
There must be a way, using PDO in PHP with mySQL, to check if fetch() has returned a result?

A: $stmt->rowCount() after the execute(), but doesn't work with all databases... try it with MySQL and see what you get.

A: You can do it with fecth, fecth will return false if no results returns.
if ($row = $stmt->fetch()) {
     //get the first row of the result.
     //....
}


text:
Q: Trying to access common Typescript enums from both Client and NodeJS server I am trying to access enums written in a Typescript file from both the server and the client. The file is called SocketEndpoints.ts and contains enum SocketMessages.
enum SocketMessages{
    CONNECTION_SUCCESSFUL
}

I am able call the enum from the client side by using typescript reference tags. However, using the reference tag alone from the server side (and not using any import/require) leads to an error:
message: endPointModule.SocketMessages.CONNECTION_SUCCESSFUL
                                                      ^
TypeError: Cannot read property 'CONNECTION_SUCCESSFUL' of undefined

As mentioned in one of the answers below, I have to use import/require statement in the server program which runs on NodeJS and "export" the enum. However, using the "export" keyword causes the enum to be inaccessible from the client. Please help me figure out a way to keep this enum commonly accessible from server and client with simplicity. I'd prefer to use only reference tags.
As shown in the answer for this question:
stackoverflow.com/questions/14659996/reference-tag-pollutes-modules-using-typescript
The typescript compiler should traverse all referenced files and include its code in the compiled javascript output. But the javascript output for server side programs don't seem to have that.

A: You can't mix and match reference tags to implementation files with import directives (think about what's going on in the JavaScript runtime - what is loading that script? Nothing.).
Put export in front of the enums and use import/require to load SocketIoEndpoints.ts.


text:
Q: create a tidy pandas dataframe from a numpy 3d array I have the following numpy 3d array:
mat.data['Sylvain_2015'].shape = (180, 12, 15)
This array is populated with a variable (muscle activation) for each participant (first dimension: 180), for each muscle (second dimension: 12), for each condition (third dimension: 15).
I want to transform this array to the following pandas dataframe:
       muscle  participant    activation  test
0           1            1    100.000000     1
1           1            1     69.322225     2
2           1            1     84.917656     3
3           1            1     80.983069     4
4           1            1     65.163384     5
5           1            1     30.528706     6

Is there a more efficient way than with three for loops:
participants, muscles, tests, relative_mvc = ([] for i in range(4))

    for iparticipant in range(mat.data[idataset].shape[0]):
            for imuscle in range(mat.data[idataset].shape[1]):
                max_mvc = np.nanmax(mat.data[idataset][iparticipant, imuscle, :])
                for itest in range(mat.data[idataset].shape[2]):
                    participants.append(iparticipant+1)
                    datasets.append(idataset)
                    muscles.append(imuscle+1)
                    tests.append(itest+1)
                    # normalize mvc (relative to max)
                    activation.append(mat.data[idataset][iparticipant, imuscle, itest]*100/max_mvc)

df = pd.DataFrame({
    'participant': participants,
    'dataset': datasets,
    'muscle': muscles,
    'test': tests,
    'relative_mvc': relative_mvc,
}).dropna()

Here is a sample of the 3d array for two participants (created with this useful post)
# Array shape: (2, 12, 15)
0.13    0.09    0.11    0.11    0.09    0.04    0.03    0.06    0.11    0.09    0.03    0.10    0.01    0.03    0.08
0.21    0.36    0.34    0.18    0.25    0.23    0.11    0.05    0.27    0.27    0.13    0.26    0.04    0.02    0.34
0.16    0.09    0.41    0.28    0.20    0.10    0.16    0.04    0.15    0.25    0.04    0.18    0.02    0.09    0.24
nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan
0.09    0.09    0.10    0.09    0.08    0.05    0.01    0.02    0.08    0.07    0.08    0.08    0.01    0.02    0.09
0.17    0.39    0.33    0.21    0.17    0.29    0.06    0.01    0.21    0.25    0.27    0.22    0.03    0.01    0.31
0.01    0.01    0.01    0.03    0.01    0.01    0.03    0.06    0.01    0.01    0.04    0.01    0.03    0.06    0.01
0.06    0.01    0.07    0.07    0.07    0.03    0.06    0.12    0.09    0.08    0.04    0.04    0.04    0.03    0.10
0.01    0.03    0.02    0.01    0.01    0.11    0.10    0.01    0.01    0.01    0.09    0.01    0.04    0.01    0.02
0.10    0.10    0.14    0.11    0.08    0.03    0.01    0.02    0.05    0.06    0.01    0.09    0.01    0.01    0.10
0.05    0.03    0.06    0.08    0.08    0.01    0.03    0.02    0.03    0.04    0.02    0.07    0.00    0.02    0.06
0.04    0.05    0.03    0.02    0.08    0.03    0.02    0.02    0.06    0.05    0.02    0.06    0.03    0.01    0.02
# New slice
0.21    0.08    0.15    0.11    0.15    0.05    0.01    0.01    0.06    0.04    0.02    0.13    0.02    0.02    0.16
0.26    0.14    0.18    0.12    0.22    0.10    0.10    0.07    0.12    0.17    0.09    0.18    0.03    0.02    0.13
0.10    0.13    0.13    0.05    0.08    0.08    0.08    0.03    0.03    0.06    0.10    0.06    0.05    0.02    0.05
nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan     nan
0.11    0.08    0.10    0.07    0.10    0.05    0.02    0.02    0.05    0.03    0.03    0.10    0.05    0.04    0.10
0.13    0.20    0.18    0.12    0.12    0.17    0.03    0.01    0.12    0.10    0.12    0.15    0.09    0.04    0.16
0.02    0.01    0.01    0.06    0.03    0.01    0.03    0.06    0.02    0.01    0.04    0.04    0.04    0.05    0.04
0.02    0.02    0.04    0.03    0.05    0.04    0.07    0.03    0.04    0.01    0.02    0.06    0.03    0.03    0.03
0.02    0.03    0.02    0.02    0.02    0.07    0.04    0.02    0.01    0.01    0.04    0.02    0.03    0.02    0.02
0.07    0.11    0.14    0.03    0.04    0.08    0.01    0.01    0.10    0.11    0.01    0.02    0.01    0.01    0.02
0.03    0.02    0.03    0.05    0.04    0.01    0.01    0.02    0.01    0.03    0.01    0.04    0.01    0.01    0.03
0.04    0.05    0.03    0.03    0.04    0.06    0.02    0.01    0.01    0.03    0.05    0.03    0.03    0.02    0.02
# New slice

A: I can think of a couple of ways. Here is one way without using loops, where make a Panel first, and then convert to dataframe.
# normalize values first
max_values = np.nanmax(mat.data[idataset], axis=2)
values = mat.data[idataset]*100/max_values.reshape(max_values.shape +(1,))

# get sizes
iparticipant, imuscle, itest = mat.data[idataset].shape

# set axes labels
items = np.arange(1, 1+iparticipant)
major_axis = np.arange(1, imuscle+1)
minor_axis = np.arange(1, itest + 1)

# make a panel (3-d dataframe)
panel = pd.Panel(values, items=iparticipant, major_axis=major_axis, minor_axis=minor_axis)

# covert to dataframe and fix column labels
df = panel.to_frame().stack().reset_index()
df.columns = ['muscle', 'test', 'participant', 'relative_mvc']
df['dataset'] = idataset


text:
Q: Vendoring a local dependency in order to build without access to that dependency Rust & cargo versions
$ rustc --version
rustc 1.60.0 (7737e0b5c 2022-04-04)
$ cargo version
cargo 1.60.0 (d1fd9fe 2022-03-01)

Context
I have:

*

*a library crate greet defined somewhere on my disk (/path/to/crate/greet)

*a binary crate hello, using this greet library crate, and defined somewhere else (/an/other/path/to/crate/hello)

Library crate greet
My library crate (greet) exports one function; /path/to/crate/greet/src/lib.rs looks like:
pub fn say_hello() {
    println!("Hello!");
}

Binary crate hello
My binary crate (hello) uses the greet library crate; /an/other/path/to/crate/hello/Cargo.toml looks like:
[package]
name = "hello"
version = "0.1.0"
edition = "2021"

[dependencies]
greet = { path = "/path/to/crate/greet" }

And hello/src/main.rs looks like:
fn main() {
    greet::say_hello();
}

All works perfectly, cargo run from hello folder prints Hello!.
Question
My use case is to build the binary crate hello in a Docker container, without having access to/mounting the /path/to/crate/greet volume:
docker run --rm -it -v /an/other/path/to/crate/hello:/app -w /app \
    rust:1.60.0-slim cargo build

If I run the previous command, I obviously got an error:
error: failed to get `greet` as a dependency of package `hello v0.1.0 (/app)`

Caused by:
  failed to load source for dependency `greet`

Caused by:
  Unable to update /path/to/crate/greet

Caused by:
  failed to read `/path/to/crate/greet/Cargo.toml`

Caused by:
  No such file or directory (os error 2)

I suppose that my question relates to vendoring my library crate. But when I run cargo vendor from my binary crate hello, I got a message:

There is no dependency to vendor in this project.

How can I vendor this library crate in hello folder, so that I can capture the contents of greet crate at one time, and so it looks like this:
.
└── hello
    ├── Cargo.toml
    ├── src
    │   └── main.rs
    └── vendor
         └── greet
              └── ...

And so I am able to build hello with docker without access to /path/to/crate/greet?


text:
Q: What is the best way to represent a chart of distribution of time intervals in Datadog? I have a server that processes packets from different devices. Devices can report in different intervals.
I would like to make a chart showing the distribution of intervals by the count of devices (how many devices are reporting within 5 sec/10 sec/60 sec ...)
Intervals for each device can vary.
Now I'm sending metric with Set using deviceId with tags that represent interval (5 sec, 10 sec, 30 sec, and more) but I'm not sure that it is correct.
What is the best way to realize it?

A: Set is almost never the right custom metric type to use. It will send a count of the number of unique items per a given tag. The underlying items details will be stripped from the metric, meaning that from one time slice to the next, you will have no idea that actual true number of items over time.
For example
3:00:07-3:00:32 | 5 second bucket:[device1,device4,device7] -> 3 values
3:00:32-3:00:47 | 5 second bucket:[device1,device3] -> 2 values

Your time series to datadog will report 3, and then 2. But because the underlying device info is stripped you have no idea how to combine that 2 and 3 if you to zoom out in time and roll up the numbers to show 1 data point per minute. It could be any number from 3 to 5, but the Datadog backend has no idea. (even though we know that across those 30 seconds there were 4 unique values total)
Plus even if it was accurate somehow, you can't create an alert of it or notify anyone, because you won't know which device is having issues if you see a spike of devices in the 60 second bucket.
So let's go through other metric options.

The only metric types that are ever worth using are usually distributions or gauges, or [counts].
A gauge metric is just a measurement of the latency at a point in time, it's usually good for things like CPU or Memory of a computer, or temperature in a room. Numbers that are impossible to actually collect all dat a points for so you just take measurements every 10 seconds, or every minute, or however often you never to get an idea of the behavior.
A count metric is more exact, it's the number of things that happened. Usually good for number of requests to a server, or number of files processed. Even something like the amount of bytes flowing through something, although that usually is treated like a gauge by most people.
Distributions are good for when you want to create a gauge metric, but you need detailed measurements for every single event that happens. For example a web server is handling hundreds of requests per second and we need to know the latency metrics of that server. It's not possible to send a latency metric for every request as a gauge. Gauges have a built in limit of 1 data point per second (in Datadog). Anything more sent in a 1 second interval gets dropped. But we need stats for every request, so a distribution will summarize the data, it keep a running count, min, max, average, and optionally several percentiles (p50, p75, p99).

I haven't seen many good use cases for metric types outside of those 3. For your scenario, it seems like you would want to be sending a distribution metric for that device interval. So device 1 sends a value of 10.14 and device 3 sends a value of 2.3 and so on.
Then you can use a distribution widget in a dashboard to show the number of devices for each interval bucket.
Of course make sure you tag each metric by the device that is generating the metric.


text:
Q: How to provide input layer to tf.layers.Conv3D? tf.layers have two classes for 3d convolution. 1) tf.layers.conv3d and 2) tf.layers.Conv3D
According to the documentation, tf.layers.conv3d is going to be deprecated. So I started using tf.layers.Conv3D.
But tf.layers.Conv3D doesn't have a parameter to specify the input layer where as tf.layers.conv3d has.
Can someone help me figure out how to give inputs to tf.layers.Conv3D layer ?

A: You could rewrite your code in the following manner:
    # Old
    output = tf.conv3d(input, *other_args)

    # New
    output = tf.keras.layers.Conv3D(*other_args)(input)


text:
Q: URL Rewriting not working? im new here.
Im trying to rewrite some urls on my site only for some reason no matter what I  try I cannot get them to work!
My directory on my server has the following...
index.php
user-profile.php
.htaccess
On my index.php there is a number of users that all have a view more details button that links through to user-profiles and posts an ID using GET method as such...
http://mysite.com/user-profile.php?userID=2&firstName=Martin&lastName=FAM
However Id like to format them as so...
http://mysite.com/people/2/Martin/FAM
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ /user-profile.php?userID=$1&firstName=$2&lastName=$3 [L]

Can anybody give me some reason as too why this isnt working?

A: The regex should be
^people/([^/]*)/([^/]*)/([^/]*)$

A: You need to make sure you have this option set in your document root directory in Apache's httpd.conf file:
AllowOverride All


text:
Q: What does calling a static methods inside the method itself mean in python I am watching a video on youtube about OOP. I encountered a type of syntax that I could not understand by my past information. The author calls the static method inside the method writing the argument at the beginning of the method's name. The method's function is to detect whether the passed number is an integer or not. The code is below:
class Dog:

    @staticmethod
    def is_integer(num):
        if isinstance(num,float):
            return num.is_integer()
        elif isinstance(num,int):
            return True
        else:
            return False

My problem is this:
What is the syntax behind num.is_integer()?

A: The method definition is using a method of float objects that has the same name, it's not calling itself. The isinstance(num, float) is making sure that it is actually used on a float, otherwise the program would throw an exception. If it would call itself, it would look more like Dog.is_integer(num).


text:
Q: Is "advance bookings only" correct? On a sign for a taxi company, which of the followings is correct:

Advance bookings only

or

Advanced bookings only

and why?

A: The correct form is advance booking, with advance used as an adjective.


text:
Q: Get number of revisions on a file with GIT I'm just starting out with Git and I'm looking for a way to get the number of revisions a file has undergone.
Right now I'm using the command:
git diff master~(arbitrary number) main.js

How do I know how high I can go with this number? I would also like to obtain the dates for each revision as well.. Thanks!

A: git-log is your friend here.
git log --pretty=oneline main.js | wc -l

git log also has some diff and patch related options.  Do try
git log -p main.js

Edit: As Iamamac pointed out in the comment below, the above gives you the number of edits done to the file.  What you truly want is the number of commits since the first check in of the file to the master.  How about
git log master --oneline `git log master --reverse --pretty=%H main.js | head -1`..master | wc -l

This should work well in any branch.  Thanks for asking this question.  I have added a git-master-diff to my bin folder that contains
#!/usr/bin/env bash
git diff master~$(git log master --oneline `git log master --reverse --pretty=%H $@ | head -1`..master | wc -l )  $@

Should come in handy.

A: Try this
git log --pretty="format:%ai | %s" main.js

for the revisions along with dates. You can pipe this through wc -l for the number of revisions. For printing different bits of information, try
git help log

and check out the format: parameter to the --pretty option.

A: In git, history is normally non-linear, that's why SHA-1 is used to represent a commit instead of revision number.
I suggest you use
git log -p filename

or
git blame filename

to view the history of the file, if that is what you want.
If you insist, this will do it:
git log --pretty=oneline `git log --reverse --pretty=%H filename | head -1`.. | wc -l


text:
Q: System.ExecutionEngineException being thrown This exception is being thrown when this line of code gets executed
retobj = Marshal.PtrToStructure( buffer, anytype );

I don't know what is causing this because, the application I am attempting to run works fine on other developers machines here.
public static object RawDeserialize(byte[] rawdatas, Type anytype)
{
    int rawsize = Marshal.SizeOf(anytype);

    if (rawsize > rawdatas.Length)
    {
        return null;
    }

    IntPtr buffer = Marshal.AllocHGlobal(rawsize);
    object retobj = null;

    try
    {
         Marshal.Copy(rawdatas, 0, buffer, rawsize);
         retobj = Marshal.PtrToStructure(buffer, anytype);
    }
    finally
    {
         Marshal.FreeHGlobal(buffer);
    }

    return retobj;
}

I've tried repairing the .NET Compact Framework multiple times and nothing seems to work, does anyone know of a solution to this?

A: If you'll debug your program you'll find out that the following line throws the exception:
 retobj = Marshal.PtrToStructure(buffer, anytype);

The main cause is that the marshalling tool does not know how to marshal your type. This has many possible causes, two of the most common I know are:

*

*Nested structures in the struct (of type anytype)

*

*solved by prefixing your struct with

[StructLayout(LayoutKind.Sequential, Pack = 1)]

*Nested arrays.

*

*solved by prefixing array with

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]

Hope it helps.


text:
Q: WARNING: Input Action on WSDL operation and @Action on its associated Web Method did not match and will cause problems in dispatching the requests Although action attribute value on SEI WebMethod matches SoapAction of WSDL Operation, I keep getting the following warning when trying to call service method from java code.
com.sun.xml.internal.ws.model.JavaMethodImpl freeze
WARNING: Input Action on WSDL operation inquirePayees and @Action on its associated Web Method inquirePayees did not match and will cause problems in dispatching the requests

Following is the WSDL Fragment
  <s0:portType name="billPayeeServicePortType">
    <s0:operation name="inquirePayees">
      <s0:input message="s1:custPayee50InqRequest" s2:Action="http://services.abc.com/billPayee50Service/Services/billPayeeService/#CustPayee50InqRequest"/>
      <s0:output message="s1:custPayee50InqResponse" s2:Action="http://services.abc.com/billPayee50Service/Services/billPayeeService/#CustPayee50InqResponse"/>
    </s0:operation>
  </s0:portType>
  <s0:binding name="billPayeeServiceSOAP" type="s1:billPayeeServicePortType">
    <s3:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <s0:operation name="inquirePayees">
      <s3:operation soapAction="http://services.abc.com/InquirePayeeService/Services/InquirePayeeService/#CustPayeeInqRequest" style="document"/>
      <s0:input>
        <s3:body parts="custPayee50InqRequest" use="literal"/>
      </s0:input>
      <s0:output>
        <s3:body parts="custPayee50InqResponse" use="literal"/>
      </s0:output>
    </s0:operation>
  </s0:binding>

and then I've a client SEI (generated by wsimport).
/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.7-b01-
 * Generated source version: 2.1
 *
 */
@WebService(name = "billPayeeServicePortType", targetNamespace = "http://emf.abc.com/emb/ws")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface BillPayeeServicePortType {
@WebMethod(action = "http://services.abc.com/InquirePayeeService/Services/InquirePayeeService/#CustPayeeInqRequest")
@WebResult(name = "CustPayee50InqResponse", targetNamespace = "http://emf.abc.com/emb/ws", partName = "custPayee50InqResponse")
public CustPayee50InqResponseType inquirePayees(
    @WebParam(name = "CustPayee50InqRequest", targetNamespace = "http://emf.abc.com/emb/ws", partName = "custPayee50InqRequest")
    CustPayee50InqRequestType custPayee50InqRequest);
}

Any idea what is wrong with this and why I see this warning? Are there ways to suppress this warning?
I tried removing Action attribute on input and output elements in the WSDL above since input element action doesn't match soapAction of the inquirePayees operation. That didn't work.
Any help is very much appreciated.

A: What is your wsimport version and parameters ?
    /**
     * This class was generated by the JAX-WS RI.
     * JAX-WS RI 2.2.9-b14002
     * Generated source version: 2.2
     *
     */

Try
    @Action(input = "http://emf.abc.com/emb/ws/BillPayeeServicePortType/custPayee50InqRequest")

or something similar in your webservice method. See Oracle documentation


text:
Q: Python Data saving performance I`ve got some bottleneck with data, and will be appreciated for senior advice.
I have an API, where i recieve financial data that looks like this GBPUSD 2020-01-01 00:00:01.001 1.30256 1.30250, my target is to write those data directly into databse as fast as it possible.
Inputs:

*

*Python 3.8

*PastgreSQL 12

*Redis Queue (Linux)

*SQLAlchemy

Incoming data structure, as showed above, comes in one dictionary {symbol: {datetime: (price1, price2)}}. All of the data comes in String datatype.
API is streaming 29 symbols, so I can recieve for example from 30 to 60+ values of different symbols just in one second.
How it works now:

*

*I recieve new value in dictionary;

*All new values of each symbol, when they come to me, is storing in one variable dict - data_dict;

*Next I'm asking those dictionary by symbol key and last value, and send those data to Redis Queue -   data_dict[symbol][last_value].enqueue(save_record, args=(datetime, price1, price2)) . Till this point everything works fine and fast.

*When it comes to Redis worker, there is save_record function:

"
def save_record(Datetime, price1, price2, Instr, adf):

# Parameters
#----------
#    Datetime    : 'string'   : Datetime value
#    price1      : 'string'   : Bid Value
#    price2      : 'string'   : Ask Value
#    Instr       : 'string'   : symbol to save
#    adf         : 'string'   : Cred to DataBase engine
#-------
#    result      :            : Execute save command to database

engine = create_engine(adf)
meta = MetaData(bind=engine,reflect=True)
table_obj = Table(Instr,meta)

insert_state = table_obj.insert().values(Datetime=Datetime,price1=price1,price2=price2)

with engine.connect() as conn:
    conn.execute(insert_state)

When i`m execute last row of function, it takes from 0.5 to 1 second to write those row into the database:
12:49:23 default: DT.save_record('2020-00-00 00:00:01.414538', 1.33085, 1.33107, 'USDCAD', 'postgresql cred') (job_id_1)
12:49:24 default: Job OK (job_id_1)
12:49:24 default: DT.save_record('2020-00-00 00:00:01.422541', 1.56182, 1.56213, 'EURCAD', 'postgresql cred') (job_id_2)
12:49:25 default: Job OK (job_id_2)
Queued jobs for inserting each row directly into database is that bottleneck, because I can insert only 1 - 2 value(s) in 1 second, and I can recieve over 60 values in 1 second. If I run this saving, it starts to create huge queue (maximum i get was 17.000 records in queue after 1 hour of API listening), and it won't stop rhose size.
I'm currently using only 1 queue, and 17 workers. This make my PC CPU run in 100%.
So question is how to optimize this process and not create huge queue. Maybe try to save for example in JSON some sequence and then insert into DB, or store incoming data in separated variables..
Sorry if something is doubted, ask - and I`ll answer.
--UPD--
So heres my little review about some experiments:

*

*Move engine meta out of function

Due to my architechture, API application located on Windows 10, and Redis Queue located on Linux. There was an issue wis moving meta and engine out of function, it returns TypeError (it is not depends on OS), a little info about it here

*Insert multiple rows in a batch:
This approach seemed to be the most simple and easy - so it is! Basically, i've just created dictionary: data_dict = {'data_pack': []}, to begin storing there incoming values. Then I ask if there is more than 20 values per symbol is written allready - i'm sending those branch to Redis Queue, and it takes 1.5 second to write down in database. Then i delete taken records from data_dict, and process continue. So thanks Mike Organek for good advice.

Those approach is quite enough for my targets to exist, at the same time I can say that this stack of tech can provide you really good flexibility!

A: Every time you call save_record you re-create the engine and (reflected) meta objects, both of which are expensive operations. Running your sample code as-is gave me a throughput of
20 rows inserted in 4.9 seconds
Simply moving the engine =  and meta =  statements outside of the save_record function (and thereby only calling them once) improved throughput to
20 rows inserted in 0.3 seconds
Additional note: It appears that you are storing the values for each symbol in a separate table, i.e. 'GBPUSD' data in a table named GBPUSD, 'EURCAD' data in a table named EURCAD, etc.. That is a "red flag" suggesting bad database design. You should be storing all of the data in a single table with a column for the symbol.


text:
Q: What is distributed caching in terms of caching persistent data for multiple applications/ multiple instances of an application I've been trying to study distributed caching for some time and have not been to clarify certain concerns listed below:

*

*Does distributed caching means that the cache should be distributed or distributed applications making use of caching of persistent data in a consistent manner.

*In case the caches too are distributed do they need to be disjoint in terms of cache entries or they can share them or the cache entries in each cache should be the same.

*Where should the cache reside. Inside the application process or externalized and if both approaches are viable then which one should be preferred in what scenario.

*In case of in process distributed caches how does the coherence communication takes place.

*In case the cache sits outside the application instances, is there a benefit of distributing the caches and maintaining coherence between them in a non disjoint manner
OR is it better to maintain one single cache(or multiple disjoints).

*In case of the cache instance(s) being externalized from the application instances how significant the network overheads could be. Or how concerned one should be about the
network overheads(process to cache communication) while the trying to build a distributed caching solution.

I am a little novice on things so certain concerns listed above might even make no sense. Solutions/ Corrections are also suggested on this.

A: My best attempt for answers:

*

*I would say both. A distributed cache means that the logical idea of a cache is spread across multiple distinct machines. For example, you might have 5 nodes in your cache, and each node is on it's on machine/VM.
Usually once you need a distributed cache, your application is also distributed. Small website = one server, maybe one cache node. Big website = many web servers, distributed cache.

*Most distributed caches distribute the cache entries evenly amongst nodes. If you write an entry to one node, it will get replicated to all other nodes. The idea is that each cache node can be taken out of the "cluster" and you don't lose any data.
The idea of having one cache entry on one machine is called sharding. It means you look at the cache key and then decide which cache node to store it on.
For existing distributed caches, you shouldn't have to manage/worry about any of this though.

*In regards to distributed caches, they should be on their own machines with no other processes running. Caches usually reside in memory, so you don't want other things competing for that precious RAM.
You could technically put a web server on the same machine as a cache node, but just be aware they will compete for physical resources.

*Don't worry about it. =) Each distributed cache behaves differently, so it's good to read up on it, but they all handle the replication of data on their own. You shouldn't have to worry about it/manage it.

*I would maintain one logical cache that is distributed across many machines. Again the reason for this is in case a node goes down. If your cache node goes down and it had values that don't exist anywhere else, then you're in big trouble. (Database might get overwhelmed serving requests that the cache was handling.)

*Good question. =) If the boxes are on the same internal network, the cost is really, really low. As long as the cache isn't on the west coast and the web servers are on the east coast, you should be fine. There is a price to pay of course, but there are creative ways to get around it.
Hope that helps!


text:
Q: alignment issue with html table I am working on jQuery application. I have a column border alignment issue when working with tables with fixed header and vertical scrollbar on.
When number of rows are more and vertical scroll bar is visible the column border is slightly misaligned to fit the scrollbar.
Please advice how to fix it. I'm going through many links but with no luck.
Please find the demo
here
Code:

                Header1
                Header2
                Header3

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

CSS code:
  * {
        box-sizing: border-box;
    }
    body {
        font: 14px/1 Arial, sans-serif;
    }
    table {
        border-collapse: collapse;
        background: white;
        table-layout: fixed;
        width: 100%;
    }
    th, td {
        padding: 8px 16px;
        border: 1px solid #ddd;
        width: 160px;
        overflow: hidden;
        white-space: nowrap;
    }
    .pane {
        background: #eee;
    }
    .pane-hScroll {
        overflow: auto;
    }
    .pane-vScroll {
        overflow-y: auto;
        overflow-x: hidden;
        height: 30%;
    }

    table { table-layout:fixed;width: 100% }
    td {
        white-space: -o-pre-wrap;
        word-wrap: break-word;
        white-space: pre-wrap;
        white-space: -moz-pre-wrap;
        white-space: -pre-wrap;

    }

How to fix and show the border without any alignment issue even when the vertical scroll is on.Any suggestions would be helpful.

A: The table alignment changes because of the scrolbar width of table is less than the fixed table.One way is to find the width of the table in scroll and set that width to the fixed table
if( $('.pane-vScroll').prop('scrollHeight') >$('.pane-vScroll').height()){
   var width = $('.pane-vScroll table').width();
   $('.pane-hScroll table:first').width( width);
}

function setTableWidth(){
    if( $('.pane-vScroll').prop('scrollHeight') >$('.pane-vScroll').height()){
       var width = $('.pane-vScroll table').width();
       $('.pane-hScroll table:first').width( width);
    }

}
$(function(){
  setTableWidth();
  $(window).resize(function () {
    setTableWidth();
  })

})
   * {
        box-sizing: border-box;
    }
    body {
        font: 14px/1 Arial, sans-serif;
    }
    table {
        border-collapse: collapse;
        background: white;
        table-layout: fixed;
        width: 100%;
    }
    th, td {
        padding: 8px 16px;
        border: 1px solid #ddd;
        width: 160px;
        overflow: hidden;
        white-space: nowrap;
    }
    .pane {
        background: #eee;
    }
    .pane-hScroll {
        overflow: auto;
    }
    .pane-vScroll {
        overflow-y: auto;
        overflow-x: hidden;
        height: 150px;
    }

    table { table-layout:fixed;width: 100% }
    td {
        white-space: -o-pre-wrap;
        word-wrap: break-word;
        white-space: pre-wrap;
        white-space: -moz-pre-wrap;
        white-space: -pre-wrap;

    }

                Header1
                Header2
                Header3

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

                        Dataaaa
                        Data
                        Data

https://jsfiddle.net/ffr991oe/1/

A:

You can force the scrollbars to be always visible on both the thead and tbody elements.
Assuming you set the columns widths the same in both sections, the columns line up perfectly. Without the scroll on the header, when the scroll is visible on the body, the columns are offset by the width of the scrollbar, and the offset gets worse towards the right hand side.


text:
Q: Get list of bases in an object How do you get a list of all the bases utilized by an object in it's creation? For instance:
class MixinA(object):
    pass

class MixinB(object):
    pass

class mixedClass(MixinB, MixinA, object):
    pass

my_object = mixedClass()
bases_used = my_object.???   # Is there a property that contains a list of [MixinA, MixinB, object]?

I'm looking to somehow extract what the bases of an object are, primarily because I'm actually building the object's class dynamically but I want to report on what mixins were used in certain error cases.

A: see inspect.getmro, or inspect.getclasstree:
>>> inspect.getmro(type(my_object))
(<class '__main__.mixedClass'>, <class '__main__.MixinB'>, <class '__main__.MixinA'>, <class 'object'>)

alternatively, __bases__
>>> type(my_object).__bases__
(<class '__main__.MixinB'>, <class '__main__.MixinA'>, <class 'object'>)

A: You can get the bases from the __class__
bases_used = my_object.__class__.__bases__

print(bases_used)
(<class '__main__.MixinB'>, <class '__main__.MixinA'>, <type 'object'>)


text: Q: Is it important to use InitializeLifetimeService for windows service members Does I have to set the InitializeLifetimeService on the members that should be running as long as my application or service is running? by example of my own experience Because I build some services with a timers but the timers stop working after a couple of days.