text:
Q: Unable to deploy azure function app using pipeline.yml file I have multiple .net mvc apps and 1 .net azure function app in our solution. I have a azure-pipeline.yml file for deployment. Mvc apps goes to app services and Function app goes to azure function.
Now when I run the pipeline on azure devops, it deploys webapps to respective app service but it fails to deploy the azure function with the error:

##[error]Error: No package found with specified pattern: D:\a\1\a**\FunctionApp.zipCheck if the package
mentioned in the task is published as an artifact in the build or a
previous stage and downloaded in the current job. Finishing:
AzureFunctionApp

But I can see FunctionApp.zip in build artifacts.
Here is my yml:
trigger:
- master
- feature/*
- hotfix/*

pool:
  vmImage: 'windows-2019'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'
  isMaster: $[eq(variables['Build.SourceBranch'], 'refs/heads/master')]
  isDeployableBranch: $[eq(variables.isMaster, true)]

stages:
- stage: Build
  displayName: Build and Test Package
  jobs:
  - job: Build_Test_Publish
    displayName: Build_Test_Publish
    steps:
    - task: NuGetToolInstaller@1

    - task: VisualStudioTestPlatformInstaller@1
      displayName: 'Install Visual Studio Test Platform'
      inputs:
        packageFeedSelector: 'nugetOrg'
        versionSelector: 'latestStable'

    - task: NuGetCommand@2
      displayName: 'Restore NuGet packages'
      inputs:
        command: 'restore'
        restoreSolution: '$(solution)'
        feedsToUse: 'config'
        nugetConfigPath: './'
        externalFeedCredentials: 'Telerik NuGet'

    - task: VSBuild@1
      displayName: 'Build Solution'
      inputs:
        solution: '$(solution)'
        msbuildArgs: '/p:DeployOnBuild=$(isDeployableBranch) /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: VSTest@2
      displayName: 'Run Unit Tests'
      inputs:
        platform: '$(buildPlatform)'
        configuration: '$(buildConfiguration)'

    - task: PublishBuildArtifacts@1
      condition: and(succeeded(), eq(variables.isDeployableBranch, true))
      inputs:
        PathtoPublish: '$(Build.ArtifactStagingDirectory)'
        ArtifactName: 'drop'
        publishLocation: 'Container'

- stage: Deploy
  displayName: Deploy
  condition: and(succeeded(), eq(variables.isDeployableBranch, true))
  jobs:
  - deployment: DeployWebApp1
    displayName: Deploy Web App 1
    environment: 'PROD'
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: none
          - task: DownloadBuildArtifacts@0
            inputs:
              buildType: 'current'
              downloadType: 'single'
              artifactName: 'drop'
              downloadPath: '$(System.ArtifactsDirectory)'

          - task: AzureRmWebAppDeployment@4
            inputs:
              ConnectionType: 'AzureRM'
              azureSubscription: 'MyResourcegroup'
              appType: 'webApp'
              WebAppName: 'webapp1'
              packageForLinux: '$(System.ArtifactsDirectory)/**/WebApp1.zip'

  - deployment: DeployWebApp2
    displayName: Deploy Web App 2
    environment: 'PROD'
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: none
          - task: DownloadBuildArtifacts@0
            inputs:
              buildType: 'current'
              downloadType: 'single'
              artifactName: 'drop'
              downloadPath: '$(System.ArtifactsDirectory)'

          - task: AzureRmWebAppDeployment@4
            inputs:
              ConnectionType: 'AzureRM'
              azureSubscription: 'MyResourceGroup'
              appType: 'webApp'
              WebAppName: 'webapp2-motionkinetic'
              packageForLinux: '$(System.ArtifactsDirectory)/**/WebApp2.zip'

  - deployment: DeployFunction
    displayName: Deploy Function
    environment: 'PROD'
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: none
          - task: DownloadBuildArtifacts@0
            inputs:
              buildType: 'current'
              downloadType: 'single'
              artifactName: 'drop'
              downloadPath: '$(System.ArtifactsDirectory)'

          - task: AzureFunctionApp@1
            inputs:
               azureSubscription: 'MyResourceGroup'
               appType: functionApp
               appName: 'MyFunction'
               package: '$(System.ArtifactsDirectory)/**/FunctionApp.zip'

I think the issue is in the yml file itself. What am I doing wrong?

A: Update:
trigger:
- main

pool:
  vmImage: 'windows-latest'

stages:
  - stage: C
    displayName: C
    jobs:
    - job: xxx
      displayName: xxxOfC
      steps:
      - task: VSBuild@1
        inputs:
          solution: '**\*.sln'
      - task: CmdLine@2
        inputs:
          script: |
            mkdir AF
            mkdir MVC1
            mkdir MVC2
      - task: CopyFiles@2
        inputs:
          SourceFolder: '$(System.DefaultWorkingDirectory)/FunctionAppAndMVC/bin/Debug/netcoreapp3.1'
          Contents: '**'
          TargetFolder: '$(System.DefaultWorkingDirectory)/AF'
        displayName: Copy Files to AF
      - task: CopyFiles@2
        inputs:
          SourceFolder: '$(System.DefaultWorkingDirectory)/MVC1/bin/Debug/netcoreapp3.1'
          Contents: '**'
          TargetFolder: '$(System.DefaultWorkingDirectory)/MVC1'
        displayName: Copy Files to MVC1(1)
      - task: CopyFiles@2
        inputs:
          SourceFolder: '$(System.DefaultWorkingDirectory)/MVC1/wwwroot'
          Contents: '**'
          TargetFolder: '$(System.DefaultWorkingDirectory)/MVC1'
        displayName: Copy Files to MVC1(2)
      - task: CopyFiles@2
        inputs:
          SourceFolder: '$(System.DefaultWorkingDirectory)/MVC2/bin/Debug/netcoreapp3.1'
          Contents: '**'
          TargetFolder: '$(System.DefaultWorkingDirectory)/MVC2'
        displayName: Copy Files to MVC2(1)
      - task: CopyFiles@2
        inputs:
          SourceFolder: '$(System.DefaultWorkingDirectory)/MVC2/wwwroot'
          Contents: '**'
          TargetFolder: '$(System.DefaultWorkingDirectory)/MVC2'
        displayName: Copy Files to MVC2(2)

      - task: ArchiveFiles@2
        inputs:
          rootFolderOrFile: '$(System.DefaultWorkingDirectory)/AF'
          includeRootFolder: true
          archiveType: 'zip'
          archiveFile: '$(Build.ArtifactStagingDirectory)/FunctionApp.zip'
          replaceExistingArchive: true
        displayName: Archive Azure Function Files
      - task: ArchiveFiles@2
        inputs:
          rootFolderOrFile: '$(System.DefaultWorkingDirectory)/MVC1'
          includeRootFolder: true
          archiveType: 'zip'
          archiveFile: '$(Build.ArtifactStagingDirectory)/MVC1.zip'
          replaceExistingArchive: true
        displayName: Archive MVC1 Files
      - task: ArchiveFiles@2
        inputs:
          rootFolderOrFile: '$(System.DefaultWorkingDirectory)/MVC2'
          includeRootFolder: true
          archiveType: 'zip'
          archiveFile: '$(Build.ArtifactStagingDirectory)/MVC2.zip'
          replaceExistingArchive: true
        displayName: Archive MVC2 Files

      - task: PublishBuildArtifacts@1
        inputs:
          PathtoPublish: '$(Build.ArtifactStagingDirectory)'
          ArtifactName: 'drop'
          publishLocation: 'Container'
        displayName: Publish Artifact
  - stage: D
    displayName: Deploy
    jobs:
    - job: xxx
      displayName: xxxOfD
      steps:
      - task: DownloadBuildArtifacts@1
        inputs:
          buildType: 'current'
          downloadType: 'single'
          artifactName: 'drop'
          downloadPath: '$(System.ArtifactsDirectory)'
      - task: AzureFunctionApp@1
        inputs:
          azureSubscription: 'testbowman_in_AAD'
          appType: 'functionApp'
          appName: 'testbowman'
          package: '$(System.ArtifactsDirectory)/drop/AF.zip'
          deploymentMethod: 'auto'
      - task: AzureWebApp@1
        inputs:
          azureSubscription: 'xxx'
          appType: 'webApp'
          appName: 'xxx'
          package: '$(System.ArtifactsDirectory)/drop/MVC1.zip'
          deploymentMethod: 'auto'
      - task: AzureWebApp@1
        inputs:
          azureSubscription: 'xxx'
          appType: 'webApp'
          appName: 'xxx'
          package: '$(System.ArtifactsDirectory)/drop/MVC2.zip'
          deploymentMethod: 'auto'

Original Answer:
I don't see the FunctionApp.zip before the deploy stage.
Seems no one archived files as 'FunctionApp.zip'(From your YAML I can't see it).
Below YAML will work:
trigger:
- main

pool:
  vmImage: 'windows-latest'

stages:
  - stage: C
    displayName: C
    jobs:
    - job: xxx
      displayName: xxxOfC
      steps:
      - task: ArchiveFiles@2
        inputs:
          rootFolderOrFile: '$(System.DefaultWorkingDirectory)'
          includeRootFolder: true
          archiveType: 'zip'
          archiveFile: '$(Build.ArtifactStagingDirectory)/FunctionApp.zip'
          replaceExistingArchive: true
      - task: PublishBuildArtifacts@1
        inputs:
          PathtoPublish: '$(Build.ArtifactStagingDirectory)'
          ArtifactName: 'drop'
          publishLocation: 'Container'
  - stage: D
    displayName: Deploy
    jobs:
    - job: xxx
      displayName: xxxOfD
      steps:
      - task: DownloadBuildArtifacts@1
        inputs:
          buildType: 'current'
          downloadType: 'single'
          artifactName: 'drop'
          downloadPath: '$(System.ArtifactsDirectory)'
      - task: AzureFunctionApp@1
        inputs:
          azureSubscription: 'testbowman_in_AAD'
          appType: 'functionApp'
          appName: 'testbowman'
          package: '$(System.ArtifactsDirectory)/**/*.zip'
          deploymentMethod: 'auto'


text:
Q: TeamCity BuildRunner Plugin I am trying to create a new buildstep into TeamCity and since you need the create a buildrunner to do so I am currently trying to create one myself.
I have created a new Mavenproject >https://confluence.jetbrains.com/display/TCD10/Developing+Plugins+Using+Maven< with the Server and Agentside command.  Now to my problem: I want to create a new buildstep and for that I did look into sample plugins from TeamCity e.g. the FxCop runner and tried to understand how it works.
I created a editParams.jsp and a viewParams.jsp in the server package. I also created a CustomRunType.java and a CustomRunTypePropertieProcessor.java.
 The good thing is that the name of the buildstep is displayed in TC, but the bad thing is, when I select the custom buildstep nothing happens, I mean there ain't no textfield displayed.
editParams.jsp:
<%@ taglib prefix="props" tagdir="/WEB-INF/tags/props" %>

<%@ taglib prefix="forms" tagdir="/WEB-INF/tags/forms" %>

<%@ taglib prefix="l" tagdir="/WEB-INF/tags/layout" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<jsp:useBean id="propertiesBean" scope="request" type="jetbrains.buildServer.controllers.BasePropertiesBean"/>

<l:settingsGroup title="myTitle">

        Name: *

                <props:textProperty name="Name" className="longField"  />

                Enter the Name.

</l:settingsGroup>

viewParams.jsp:

<jsp:useBean id="propertiesBean" scope="request" type="jetbrains.buildServer.controllers.BasePropertiesBean"/>

CustomRunTypeProppertyProcessor.java:
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.util.PropertiesUtil;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Vector;

public class CustomRunTypePropertiesProcessor implements PropertiesProcessor {
    @Override
    public Collection<InvalidProperty> process(Map<String, String> map) {
        List<InvalidProperty> result = new Vector();
        String name = (String)map.get("Name");

        if (PropertiesUtil.isEmptyOrNull(name)) {
            result.add(new InvalidProperty("Name", "Name must be specified."));
        }
        return result;
    }
}

CustomRunType.java:
import java.util.Map;
import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.serverSide.RunType;
import jetbrains.buildServer.serverSide.RunTypeRegistry;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class CustomRunType extends RunType {
    public CustomRunType(RunTypeRegistry runTypeRegistry, PluginDescriptor pluginDescriptor) {
        runTypeRegistry.registerRunType(this);
    }

    @NotNull
    @Override
    public String getType() {
        return "CustomPlugin";
    }

    @NotNull
    @Override
    public String getDisplayName() {
        return "CustomPlugin";
    }

    @NotNull
    @Override
    public String getDescription() {
        return "CustomPlugin";
    }

    @Nullable
    @Override
    public PropertiesProcessor getRunnerPropertiesProcessor() {
        return new CustomRunTypePropertiesProcessor();
    }

    @Nullable
    @Override
    public String getEditRunnerParamsJspFilePath() {
        return "editParams.jsp";
    }

    @Nullable
    @Override
    public String getViewRunnerParamsJspFilePath() {
        return "viewParams.jsp";
    }

    @Nullable
    @Override
    public Map<String, String> getDefaultRunnerProperties() {
        return null;
    }
}

I was wondering if someone has any idea what I did wrong, or what I forgot, or in the best case how to fix it or a simple sample for this.
Thanks for reading!

A: Normally that just happens when the path to the editParams.jsp and viewParams.jsp is not correct.
Try it like this:
private final PluginDescriptor myPluginDescriptor;

public CostumRunType(final RunTypeRegistry runTypeRegistry, final
PluginDescriptor pluginDescriptor) {
    myPluginDescriptor = pluginDescriptor;
    runTypeRegistry.registerRunType(this);
}

@Override
public String getEditRunnerParamsJspFilePath() {
  return myPluginDescriptor.getPluginResourcesPath("editRunParams.jsp");
}

@Override
public String getViewRunnerParamsJspFilePath() {
  return myPluginDescriptor.getPluginResourcesPath("viewRunParams.jsp");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Square-list "Compare Constructor" Implementation For a homework assignment, I've to implement a square-list (already done) and pass all the unit tests provided. I've passed all but one and this specific unit test tests for the implementation of a "compare constructor."
Here are the boost unit tests involved:
#include "ut_square_list.hpp"
#include <boost\test\auto_unit_test.hpp>
#include <vector>
using std::vector;

template <class T>
class RuntimeCmp
{
public:
    enum cmp_mode { normal, reverse };
private:
    cmp_mode mode;
public:
    RuntimeCmp( cmp_mode m = normal ) : mode(m) { } // constructor
    bool operator()(T const& t1, T const& t2) const { return mode == normal ? t1 < t2 : t2 < t1; } // function call operator -
    bool operator==( RuntimeCmp const& rc ) { return mode == rc.mode; }
};

/** Test square_list<T>::square_list() */
BOOST_AUTO_TEST_CASE( ut_ctor_compare_def ) {
    square_list<double,RuntimeCmp<double>> s;
    vector<double> data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    for (auto x : data)
        s.insert(x);

    BOOST_CHECK( std::equal( s.begin(), s.end(), data.begin() ) );
}

BOOST_AUTO_TEST_CASE( ut_ctor_compare_passed ) {
    RuntimeCmp<double> rc(RuntimeCmp<double>::reverse);
    square_list<double,RuntimeCmp<double>> s(rc);
    vector<double> data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    for (auto x : data)
        s.insert(x);

    BOOST_CHECK( std::equal( s.begin(), s.end(), data.rbegin() ) );
}

BOOST_AUTO_TEST_CASE( ut_ctor_compare_iterator_passed ) {
    vector<double> data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    RuntimeCmp<double> rc(RuntimeCmp<double>::reverse);
    square_list<double,RuntimeCmp<double>> s(data.begin(),data.end(),rc);

    BOOST_CHECK( std::equal( s.begin(), s.end(), data.rbegin() ) );
}

What is a "compare constructor" based on the above? I can't figure it out.

A: From the context you have given I think "compare constructor" refers to a constructor that takes a compare object as a parameter.
While terms like "default constructor" or "copy constructor" are language specific, "compare constructor" is not. It is specific for this homework assignment.


text:
Q: why doesn't this update part of this plugin work? it take me to nothing here page Below is my plugin. Everything works except the update part. It will show the little table with the existing values and when I click on the update button in that little table, it takes me to Nothing Here page, instead of calling the page again.
The url doesn't update to the page url, it still has the parameter on the end of the url too. Thanks in advanced for your time.
Dean-O
<?php
/*
Plugin Name: deano CRUD Operations
Plugin URI:
Description: A simple plugin that allows you to perform CRUD operations on custom database table
Version: 1.0.0
Author: Dean-O
Author URI:
License: GPL2
*/

function deanocrud() {
  global $wpdb;
  //$table_name = $wpdb->prefix . 'books';
  $table_name = 'books';

  // get current user ID, with default value, if empty
  $current_user_id = get_current_user_id();
  error_log('current_user_id '.$current_user_id);

  if (isset($_POST['newsubmit'])) {

    error_log('newsubmit here');
    $wp_id = $_POST['wp_id'];
    $title = $_POST['title'];
    $author = $_POST['author'];
    $wpdb->query("INSERT INTO $table_name(wp_id,title,author) VALUES('$wp_id','$title','$author')");
    //echo "";
    //wp_redirect( "http://localhost/tadpolewp/deano-plugin-successful/" );
    //wp_redirect( "http://localhost/tadpolewp/deano-crud/" );
        ?>

  <?php

  }
  if (isset($_POST['uptsubmit'])) {
    error_log('uptsubmit here');
    $id = $_POST['uptid'];
    $title = $_POST['title'];
    $author = $_POST['author'];
    error_log('upt_id = '.$id);
    error_log('title = '.$title);
    error_log('author = '.$author);
    $wpdb->query("UPDATE $table_name SET title='$title',author='$author' WHERE id='$id'");
    //echo "";
    //echo "";
          ?>

  <?php

  }
  if (isset($_GET['del'])) {
    $del_id = $_GET['del'];
    $wpdb->query("DELETE FROM $table_name WHERE user_id='$del_id'");
    //echo "";
    echo "";
  }
  ?>

CRUD Operations

          USER_ID1
          __
          Title
          Author
          Actions

        <form action="" method="post">

            <input type="text" value="AUTO_GENERATED" disabled>
            <input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" >

            <input type="text" id="title" name="title">
            <input type="text" id="author" name="author">
            <button id="newsubmit" name="newsubmit" type="submit">INSERT</button>

        </form>
        <?php

          $result = $wpdb->get_results("SELECT * FROM $table_name where wp_id='$current_user_id'");
          foreach ($result as $print) {
            echo "

                $print->wp_id

                $print->title
                $print->author
                id'><button type='button'>UPDATE</button> id'><button type='button'>DELETE</button>

           ";
          }
        ?>

    <?php
      if (isset($_GET['upt'])) {
        $upt_id = $_GET['upt'];
        error_log('upt_id = '.$upt_id);
        $result = $wpdb->get_results("SELECT * FROM $table_name WHERE id='$upt_id'");
        foreach($result as $print) {
          $title = $print->title;
          $author = $print->author;
           error_log('title = '.$title);
           error_log('author = '.$author);
           error_log('id = '.$print->id);
        }
        echo "

              ID
              Title
              Author
              Actions

            <form action='' method='post'>

                $print->id <input type='hidden' id='uptid' name='uptid' value='$print->id'>
                <input type='text' id='title' name='title' value='$print->title'>
                <input type='text' id='author' name='author' value='$print->author'>
                <button id='uptsubmit' name='uptsubmit' type='submit'>UPDATE</button> <button type='button'>CANCEL</button>

            </form>

";
      }
    ?>

  <?php
}
add_shortcode('deanocrud_sc','deanocrud');


text:
Q: 404 error page showing HTTP Status 200 instead of 404 I have the following code for performing redirection. If my $includeFile does not exist it will redirect to a 404 page. This is a snippet from my index.php
if ( !file_exists($includeFile) )
     Header( "HTTP/1.1 404 Page Not Found" );
     Header( "Location: http://legascy.com/404_error/");

But http://legascy.com/404_error/ is showing HTTP Status 200 OK instead of 404.
How to solve this?

A: You need to place the header function for 404 on the "404_error" page instead of the page that redirects. This because the browser is sent to 404_error which has the default 200 status code.
if ( !file_exists($includeFile) ) {
     header("Location: http://legascy.com/404_error/");
}

And on 404_error/index.php:
header("HTTP/1.1 404 Page Not Found");

A: Your previous header for sending 404 error code is discarded by the Location header and the browser takes the user to new page. The page you redirected to is available, so it will always show 200.


text:
Q: Restore fails on ovirt whether engine is on or off - how to get around Wondering whether this is an issue;
I had an engine where i created a backup and stored elsewhere. This engine was reinstalled
and the backup file (called file_name) used to restore below. However i get 2 different
errors based on whether engine is on....
[root@dub-mgrfarm113 ~]# service ovirt-engine status
Redirecting to /bin/systemctl status ovirt-engine.service
● ovirt-engine.service - oVirt Engine
Loaded: loaded (/usr/lib/systemd/system/ovirt-engine.service; disabled; vendor preset:
disabled)
Active: active (running) since Thu 2020-01-16 16:13:41 GMT; 2h 5min ago
Main PID: 5621 (ovirt-engine.py)
CGroup: /system.slice/ovirt-engine.service
├─5621 /usr/bin/python
/usr/share/ovirt-engine/services/ovirt-engine/ovirt-engine.py --redirect-output
--systemd=notify st...
└─5661 ovirt-engine -server -XX:+TieredCompilation -Xms1991M -Xmx1991M -Xss1M
-Djava.awt.headless=true -Dsun.rmi.dgc.clien...

Jan 16 16:13:40 dub-mgrfarm113.ie.oracle.com systemd[1]: Starting oVirt Engine...
Jan 16 16:13:40 dub-mgrfarm113.ie.oracle.com ovirt-engine.py[5621]: 2020-01-16
16:13:40,816+0000 ovirt-engine: INFO _detectJBossV...l=36
Jan 16 16:13:41 dub-mgrfarm113.ie.oracle.com ovirt-engine.py[5621]: 2020-01-16
16:13:41,795+0000 ovirt-engine: INFO _detectJBossV...'[]'
Jan 16 16:13:41 dub-mgrfarm113.ie.oracle.com systemd[1]: Started oVirt Engine.
Hint: Some lines were ellipsized, use -l to show in full.
[root@dub-mgrfarm113 ~]# engine-backup --mode=restore --file=file_name
--restore-permissions
Start of engine-backup with mode 'restore'
scope: all
archive file: file_name
log file: /var/log/ovirt-engine-backup/ovirt-engine-restore-20200116181932.log
Preparing to restore:
FATAL: Engine service is active - can not restore backup

or off.......
[root@dub-mgrfarm113 ~]# service ovirt-engine stop
Redirecting to /bin/systemctl stop ovirt-engine.service
[root@dub-mgrfarm113 ~]# engine-backup --mode=restore --file=file_name
--restore-permissions
Start of engine-backup with mode 'restore'
scope: all
archive file: file_name
log file: /var/log/ovirt-engine-backup/ovirt-engine-restore-20200116181952.log
Preparing to restore:
- Unpacking file 'file_name'
Restoring:
- Files
FATAL: Can't connect to database 'engine'. Please see
'/usr/bin/engine-backup --help'.

In addition, possibly related, the web page for the server will no longer launch even when
ovirt-engine and httpd services are running while.
Any troubleshooting tips or has anyone seen same before?


text:
Q: Problema con .json como respuesta de una peticion Post NodeJS Estoy desarrollando un backend con una base de datos en mongoDB, al definir un endpoint de tipo post y probarlo en postman me envía un error en la consola y en postman no obtengo el objeto que definí como respuesta al post, sin embargo, si realiza la inserción correctamente en la base de datos.
mi versión de node es la v14.5.0
esta es la ruta definida para el endpoint
/*
    /api/hospitales
*/
const { Router } = require('express');
const { check } = require('express-validator');

const {
    getHospitales,
    crearHospital,
    actualizarHospital,
    eliminarHospital
} = require('../controller/hospitales_controller');

const { validarCampos } = require('../middlewares/validarCampos_middleware');
const { validarJWT } = require('../middlewares/validarJWT_middleware');

const router = Router();

router.get('/', [], getHospitales);

router.post('/', [
    validarJWT,
    check('nombre', 'El nombre del hospital es necesario').not().isEmpty(),
    validarCampos
], crearHospital);

router.put('/:id', [], actualizarHospital);

router.delete('/:id', [], eliminarHospital);

module.exports = router;

este es el controlador que tiene la funcion de realizar el posteo a la bd
    const { response } = require('express');

const Hospital = require('../model/hospitales_model');

const crearHospital = async(req, res = response) => {

    const uid = req.uid;
    const hospital = new Hospital({
        usuario: uid,
        ...req.body
    });

    try {

        const hospitalDB = await hospital.save();

        res.json({
            ok: true,
            hospital: hospitalDB
        });

    } catch (error) {
        console.log(error);
        res.status(500).json({
            ok: false,
            msg: 'Hable con el administrador'
        });
    }

};

este es el modelo que utilizo para crear el documento en la base de datos
    const { Schema, model } = require('mongoose');

const HospitalSchema = Schema({

    nombre: {
        type: String,
        required: true
    },
    img: {
        type: String,
    },
    usuario: {
        required: true,
        type: Schema.Types.ObjectId,
        ref: 'Usuario'
    }

}, { collection: 'Hospitales' });

HospitalSchema.method('toJSON', function() {
    const { __v, ...object } = this.toObject();
    return object;
});

module.exports = model('Hospital', HospitalSchema);

este es el middleware que valida el JWB
const validarJWT = (req, res, next) => {

//leer token
const token = req.header('x-token');

if (!token) {
    return res.status(401).json({
        ok: false,
        msg: 'No hay token en la peticion'
    });
}

try {
    const { uid } = jwt.verify(token, process.env.JWT_SECRET);
    req.uid = uid;

    next();

} catch (error) {
    return res.status(401).json({
        ok: false,
        msg: 'Token invalido'
    });
}

next();

este es el error en consola, aparentemente no estoy controlando algo

este es el resultado en postman, obtengo como tal un error confuso por que es codido 400 como si la ruta misma no estuviese definida

Y aquí puedo ver que la petición si se realiza correctamente al revisar en la BD y ver el registro posteado

A: resuelto, Como muchos de los problemas de código que existen era simplemente un llamado extra de la funcion next() en el middleware validarJWT que acompaña a la petición
const jwt = require('jsonwebtoken');

const validarJWT = (req, res, next) => {

//leer token
const token = req.header('x-token');

if (!token) {
    return res.status(401).json({
        ok: false,
        msg: 'No hay token en la peticion'
    });
}

try {
    const { uid } = jwt.verify(token, process.env.JWT_SECRET);
    req.uid = uid;
    // next(); <------------ Este next sobraba
} catch (error) {
    return res.status(401).json({
        ok: false,
        msg: 'Token invalido'
    });
}

next();
};


text:
Q: With $a,\ b,\ m,\ n\in \mathbb{Z}$. Show that if ${\rm gcd}(m,n)=1$, then ${\rm gcd}(ma+nb,mn)={\rm gcd}(a,n){\rm gcd}(b,m)$ I don't really know how to prove this, i suppose it must have something to do with the definition of greatest common divisor and Bézout's identity.
I looked at some other questions here and thought that i had to get to gcd(ma+nb,mn)=1 and that gcd(a,n)gcd(b,m)=1 too, but i'm not sure.

A: By $\rm\color{#c00}H$ere $\color{#c00}{(m,n)\!=\!1}\Rightarrow (ma\!+\!nb,\color{#c00}{mn})  \overset{{\rm\color{#c00}H}}= (ma\!+\!nb,\color{#c00}m)(ma\!+\!nb,\color{#c00}n) = (b,m)(a,n)\ $ by
$$\begin{align}(\color{#0a0}ma+nb,\color{#0a0}m) &\overset{\rm\color{#f6f} R}= (nb,m) \overset{\rm\color{darkorange}L}= (b,m)\\[.2em]
(ma+\color{#0af}nb,\ \color{#0af}n) &\overset{\rm\color{#f6f} R}= (ma,n) \overset{\rm\color{darkorange}L}= (a,n)\end{align}\qquad$$
where above we applied gcd $\rm\color{#0a0}{mod}\ \color{#0af}{reduction}$ = $\rm\color{#f6f} R,\ $ and $\ \rm\color{darkorange}L = $ Euclid's Lemma, by $\, \color{#c00}{(m,n)=1}$.

A: I find it useful when doing calculations involving $\gcd(a,n)$ (or whatever variables) to use the notation:
Let $\gcd(a,n) = d$ and let $a = a'd; a'=\frac ad$ and $n = n'd; n' = \frac nd$ and we can know that that $a'$ and $n'$ are relatively prime.
Likewise let $\gcd(b,m) = e$ and let $b = b'e$ and $m = m'e$ and $b'$ and $m'$ are relatively prime.
Thus we want to prove that $\gcd(m'a'de + n'b'de, m'n'de) = de$
.....
Now you probably have proven at some point that $\gcd(fg, hg) = g\gcd(f,h)$.
So $\gcd(m'a'de + n'b'de, m'n'de) = \gcd(m'a' + n'b', m'n')de$ and we just need to prove $\gcd(m'a' + n' b', m'n') = 1$.
....
Well, let $p$ be a prime divisor of $\gcd(m'a' + n' b', m'n')$ then $p|m'n'$ so $p|m'$ or $p|n'$.  Wolog $p|m'$ so then $p|m'a' + n'b'$ so $p|n'b'$ but as $b', m'$ are relatively prime we know $p\not \mid b'$ so $p|n'$.
So $p|m'$ and $p|n'$.
But we were told $\gcd(m,n) = 1$ so there can't be any prime divisors that divide both $m',n'$.
So there are no prime divisors of $\gcd(m'a' + n' b', m'n')$.  So $\gcd(m'a + n'b', m'n') = 1$.


text:
Q: preg_match_all to find a string that may contain some html tags? My blog articles have a function where a visitor can select part of it and leave a feedback. The feedback's subject is the selection: it can be a few words, or a phrase with some html tags within it (not necessarily around it.)
My function, up until now was the below:
function enco_str_replace_nth( $search, $replace, $subject, $nth = 0 ) {

    $found = preg_match_all( '/' . preg_quote( $search ) . '/', $subject, $matches, PREG_OFFSET_CAPTURE );

    if (false !== $found && $found > $nth) {
        return substr_replace( $subject, $replace, $matches[0][$nth][1], strlen( $search ) );
    }

    return $subject;
}

It does work when there is no HTML tag(s).
a completely organic product

But shows a Warning: preg_match_all(): Unknown modifier and doesn't work when there is HTML in it.
MSM is a  natural nutrient

or
because it matters to all of us

Any idea of what I should change in this preg_match_all?

A: In addition to my comment:
function enco_str_replace_nth( $search, $replace, $subject, $nth = 0 ) {
    $found = preg_match_all( '~' . preg_quote( $search ) . '~', $subject, $matches, PREG_OFFSET_CAPTURE );

    if (false !== $found && $found > $nth) {
        return substr_replace( $subject, $replace, $matches[0][$nth][1], strlen( $search ) );
    }

    return $subject;
}


text:
Q: I'm having trouble with sending a form using POST to retrieve data in R I'm having trouble collecting doctors from https://www.uchealth.org/providers/. I've found out it's a POST method but with httr I can't seem to create the form. Here's what I have
url = url = 'https://www.uchealth.org/providers/'
formA = list(title = 'Search', onClick = 'swapForms();', doctor-area-of-care-top = 'Cancer Care')
formB = list(Search = 'swapForms();', doctor-area-of-care = 'Cancer Care')
get = POST(url, body = formB, encode = 'form')

I'm fairly certain formB is the correct one. However, I can't test it since I yield an error when trying to make the list. I believe it is because you can't use "-" characters when naming although I could be wrong on that. Could somebody help please?

A: I am unable to comment properly but try this to create an list. Code below worked for me.
library(httr)
url =  'https://www.uchealth.org/providers/'
formB = list(Search = 'swapForms();', `doctor-area-of-care` = 'Cancer Care')
get = POST(url, body = formB, encode = 'form')

When you are creating names with spaces or some other special character you have to put it into the operator above.


text:
Q: Foundation imports with Libsass, node-sass-middleware not compiling I am using Node.js with Express as my base for my app, and am attempting to use the npm packages node-sass-middleware for sass compilation and foundation-sites for the foundation scss source.
My app.js contains the following,
var sass = require('node-sass');
var sassMiddleware = require('node-sass-middleware');

app.use(sassMiddleware({
src: path.join(__dirname,'scss'),
dest: path.join(__dirname,'public/css'),
prefix: '/css',
includePaths:[path.join(__dirname, 'node_modules/foundation-sites/scss/')], //Make sure we include the foundation library. ^-^;
debug: true,
outputStyle: 'extended'

}));
app.use(express.static(path.join(__dirname, 'public')));

My style.scss looks like:
@import 'foundation';

@import 'stuff'; /*Testing imports functionality*/

body{

    color:black; /*Just for testing compilation*/

}

and stuff.scss looks like:
somerandomtag{

    @extend body;
    border:5px solid black;

}

In my layout.jade I've added
link(rel='stylesheet', href='/css/style.css')

When I refresh my page, in my log I can see the following output:

GET /login 200 356.910 ms - 511   source:
  F:\Users\trutt\Documents\Projects\MyProject\scss\style.scss   dest:
  F:\Users\trutt\Documents\Projects\MyProject\public\css\style.css
  read: F:\Users\trutt\Documents\Projects\MyProject\public\css\style.css
  GET /js/jquery.cookie.js 304 7.621 ms - - GET /css/style.css - - ms -
  -   render: F:\Users\trutt\Documents\Projects\MyProject\scss\style.scss   source:
  F:\Users\trutt\Documents\Projects\MyProject\scss\style.scss   dest:
  F:\Users\trutt\Documents\Projects\MyProject\public\css\style.css GET
  /css/style.css 200 7.127 ms - 269

All finally resulting in the compiled style.css:
/**
 * Foundation for Sites by ZURB
 * Version 6.2.1
 * foundation.zurb.com
 * Licensed under MIT Open Source
 */
somerandomtag {
  border: 5px solid black; }

/*Testing imports functionality*/
body, somerandomtag {
  color: black;
  /*Just for testing compilation*/ }

The header for foundation itself is visible, which tells me my include path is working. I have proven that Sass seems to be working via compilation checks and import tests, as well as inheritance. But... where is all of foundations css rules? Have I missed something?
All of the packages installed were freshly installed within the last 24 hours directly from npm so I would assume I'm working with the latest npm package versions.

A: After a few hours of playing with different sass/gulp/gem alternatives, I found my issue.
I was exploring the files included with foundation-sites included in the npm package.
It seems changing the following like in app.js
includePaths:[path.join(__dirname, 'node_modules/foundation-sites/scss/')],

To
includePaths:[path.join(__dirname, 'node_modules/foundation-sites/assets/')],

Fixed the issues.
I believe this is because the file foundation.scss in the above assets path contains
@import '../scss/foundation';

@include foundation-everything;

I assume the bottom line is what makes the difference. Likely the other files in the /scss/ folder do not include foundation-everything. Which I assume is the master include for the compiled foundation css.
Again, built off assumptions as to why and how this works, but documentation on Foundation with node-sass-middleware via NPM on Express is scarce, and this issue is resolved with the above modification.


text:
Q: Oracle SQL- procedure- insert into foreign table from own table not updating the table Problem- cannot insert data from own schema's table to foreign schema's table.
Details- I am trying to insert the latest data from my own schema table to a foreign schema table. I have all the rights on the foreign schema table. The table structures are exactly the same. The foreign table already has some data but I need to load incremental data with a check on duplicity based on a field called SURVEY_ID. There is no error message.
The statement 'NOT IN (SELECT SURVEY_ID FROM FORG.PROD_CL)' is somehow hampering the insert process. If I remove this 'NOT IN' clause and rather mention specific SURVEY_IDs, the data load takes place.
Here is the code-
BEGIN
INSERT INTO FORG.PROD_CL
SELECT
RESPONSE_ID,
TO_DATE(TO_CHAR(COMPLETION_DATE)) AS COMPLETION_DATE,
TO_TIMESTAMP(COMPLETION_DATE||TO_CHAR(SUBSTR(COMPLETION_TIME,11,32))) AS COMPLETION_TIME,
Q101,
Q101_LONG,
Q191,
SURVEY_ID,
REP_NAME,
ATOMIC_TS
FROM OWN1.IPROD_CL
WHERE OWN1.IPROD_CL.SURVEY_ID NOT IN (SELECT SURVEY_ID FROM FORG.PROD_CL)
ORDER BY SURVEY_ID;
COMMIT;
END;
/


text:
Q: RegexMatchError with pytube I have this code, and i cant download whit this interface, why?
When I try to run this code, just nothing happens
Traceback (most recent call last):
  File "C:\Users\gerso\PycharmProjects\pythonProject\layout.py", line 17, in <module>
    yt = YouTube('link')
  File "C:\Users\gerso\PycharmProjects\pythonProject\venv\lib\site-packages\pytube\__main__.py", line 77, in __init__
    self.video_id = extract.video_id(url)
  File "C:\Users\gerso\PycharmProjects\pythonProject\venv\lib\site-packages\pytube\extract.py", line 80, in video_id
    return regex_search(r"(?:v=|\/)([0-9A-Za-z_-]{11}).*", url, group=1)
  File "C:\Users\gerso\PycharmProjects\pythonProject\venv\lib\site-packages\pytube\helpers.py", line 34, in regex_search
    raise RegexMatchError(caller="regex_search", pattern=pattern)
pytube.exceptions.RegexMatchError: regex_search: could not find match for (?:v=|\/)([0-9A-Za-z_-]{11}).*

import PySimpleGUI as sg
from pytube import YouTube

sg.theme('DarkAmber')   # Add a touch of color
# All the stuff inside your window.
layout = [  [sg.Text('Link:'), sg.Input(key='link')],
            [sg.Text('Diretório'), sg.Input()],
            [sg.Button('Download'), sg.Button('Cancel')]]

# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    # se o usuario apertar download
    if event == 'Download':
        yt = YouTube('link')
        video = yt.streams.get_highest_resolution()
        video.download()

    if event == sg.WIN_CLOSED or event == 'Cancel': # Se o usuário fechar a janela ou cancelar
        break

window.close()

A: try upgrade to latest version so upgrade to the latest version like this
python3 -m pip install --upgrade pytube

or on windows
python -m pip install --upgrade pytube

and you can also try this driver code
import sys # import sys
import pytube

link = 'put link here'
yt = pytube.YouTube(link)
stream = yt.streams.get_highest_resolution()
finished = stream.download()
print('Download is complete')

sys.exit()


text:
Q: How to test SignalR 2 hub only notifies a single user? I've worked through the unit testing examples in the SignalR 2 documentation, but now I'd like to test that my hub only notifies a single user in certain situations.
My hub code looks like this:
public class NotificationsHub : Hub
{
    public void RaiseAlert(string message)
    {
        Clients.All.RaiseAlert(message);
    }

    public void RaiseNotificationAlert(string userId)
    {
        if (userId == null)
        {
            // Notify all clients
            Clients.All.RaiseAlert("");
            return;
        }

        // Notify only the client for this userId
        Clients.User(userId).RaiseAlert("");

    }
}

My unit test for checking that all clients are notified looks like this (it's based on the Microsoft example):
[Test]
public void NotifiesAllUsersWhenNoUserIdSpecified()
{
    // Based on: https://learn.microsoft.com/vi-vn/aspnet/signalr/overview/testing-and-debugging/unit-testing-signalr-applications

    // Arrange

    // This is faking the
    var mockClients = new Mock<IClientContract>();
    mockClients.Setup(m => m.RaiseAlert(It.IsAny<string>())).Verifiable();

    // A mock of our SignalR hub's clients
    var mockClientConnCtx = new Mock<IHubCallerConnectionContext<dynamic>>();
    mockClientConnCtx.Setup(m => m.All).Returns(mockClients.Object);

    // Set the hub's connection context to the mock context
    var hub = new NotificationsHub
    {
        Clients = mockClientConnCtx.Object
    };

    // Action
    hub.RaiseNotificationAlert(null);

    // Assert
    mockClients.Verify(m => m.RaiseAlert(It.IsAny<string>()));
}

What I'm not sure about is how to change the collection of clients represented by the var mockClients = new Mock<IClientContract>() line into a group of individual clients so that I can then test that if I notify user 1, then users 2 and 3 weren't notified?

A: I found another question about how to unit test groups and one of the answers pointed to the unit tests for the SignalR codebase.
Looking at those examples I worked out that I needed to add mocking of calls to the User method of the mockClients.  That ended up looking like this:
public interface IClientContract
{
    void RaiseAlert(string message);
}

[Test]
public void NotifiesOnlySpecifiedUserWhenUserIdSent()
{
    // Adapted from code here: https://github.com/SignalR/SignalR/blob/dev/tests/Microsoft.AspNet.SignalR.Tests/Server/Hubs/HubFacts.cs

    // Arrange

    // Set up the individual mock clients
    var client1 = new Mock<IClientContract>();
    var client2 = new Mock<IClientContract>();
    var client3 = new Mock<IClientContract>();

    client1.Setup(m => m.RaiseAlert(It.IsAny<string>())).Verifiable();
    client2.Setup(m => m.RaiseAlert(It.IsAny<string>())).Verifiable();
    client3.Setup(m => m.RaiseAlert(It.IsAny<string>())).Verifiable();

    // set the Connection Context to return the mock clients
    var mockClients = new Mock<IHubCallerConnectionContext<dynamic>>();
    mockClients.Setup(m => m.User("1")).Returns(client1.Object);
    mockClients.Setup(m => m.User("2")).Returns(client2.Object);
    mockClients.Setup(m => m.User("3")).Returns(client3.Object);

    // Assign our mock context to our hub
    var hub = new NotificationsHub
    {
        Clients = mockClients.Object
    };

    // Act
    hub.RaiseNotificationAlert("2");

    // Assert
    client1.Verify(m => m.RaiseAlert(It.IsAny<string>()), Times.Never);
    client2.Verify(m=>m.RaiseAlert(""), Times.Once);
    client3.Verify(m => m.RaiseAlert(It.IsAny<string>()), Times.Never);
}


text:
Q: how do i send data from a php file on a remote web host to a c# application on my computer? I am working on a c# wpf application that will need to receive communication from my web server. the user would enter some details on the website which will be using php/html forms. when they click submit on the form it needs to send data from the form to the c# application. the wpf application will open the php web page so if i need to send some form of identification when opening the page i can handle that with post variables. just not sure how to get the data back to the wpf app

A: Assuming the C# is a file that you can execute from the command line, or one that you can turn into that:
shell_exec();  https://www.php.net/manual/en/function.shell-exec.php
or backticks:  https://www.php.net/manual/en/language.operators.execution.php


text:
Q: How to find the value in particular tag elemnet in xml using python? I am trying to parse xml data received from RESTful interface. In error conditions (when query does not result anything on the server), I am returned the following text. Now, I want to parse this string to search for the value of status present in the fifth line in example given below. How can I find if the status is present or not and if it is present then what is its value.
content = """
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/3.0/style/exchange.xsl"?>
<ops:world-patent-data xmlns="http://www.epo.org/exchange" xmlns:ops="http://ops.epo.org" xmlns:xlink="http://www.w3.org/1999/xlink">
    <ops:meta name="elapsed-time" value="3"/>
    <exchange-documents>
        <exchange-document system="ops.epo.org" country="US" doc-number="20060159695" status="not found">
            <bibliographic-data>
                <publication-reference>
                    <document-id document-id-type="epodoc">
                        <doc-number>US20060159695</doc-number>
                    </document-id>
                </publication-reference>
                <parties/>
            </bibliographic-data>
        </exchange-document>
    </exchange-documents>
</ops:world-patent-data>
"""
import xml.etree.ElementTree as ET
root = ET.fromstring(content)
res = root.iterfind(".//{http://www.epo.org/exchange}exchange-documents[@status='not found']/..")

A: Just use BeautifulSoup:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(open('xml.txt', 'r'))

print soup.findAll('exchange-document')["status"]

#> not found

If you store every xml output in a single file, would be useful to iterate them:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(open('xml.txt', 'r'))

for tag in soup.findAll('exchange-document'):
    print tag["status"]

#> not found

This will display every [status] tag from [exchange-document] element.
Plus, if you want only useful status you should do:
for tag in soup.findAll('exchange-document'):
    if tag["status"] not in "not found":
        print tag["status"]

A: Try this:
from xml.dom.minidom import parse
xmldoc = parse(filename)
elementList = xmldoc.getElementsByTagName(tagName)

elementList will contain all elements with the tag name you specify, then you can iterate over those.


text:
Q: Gstreamer: Save image/jpeg using multifilesink every 5 seconds I am trying to figure out how to save an image using multifilesink every N seconds (lets say 5). My get-launch-1.0 pipeline is below: gst-launch-1.0 videotestsrc ! 'video/x-raw, format=I420, width=400, height=400, framerate=1/5' ! jpegenc ! multifilesink location=/some/location/img_%06d.jpg
I was thinking the framerate option could control the capture speed but it seems to not be affecting anything. How can I delay this pipeline to only save a jpeg every N seconds?
Edit: So I figured how that this will work with videotestsrc if you set "is-live=true" but I would like to do this with an nvcamerasrc or nvarguscamerasrc.

A: When the videotestsrc is not running as a live source, it will pump out frames as fast as it can, updating timestamps based on the output framerate configured on the source pad.
Setting it to live-mode will ensure that it actually matches the expected framerate.
This shouldn't be an issue with a true live source like a camera source.
However something like this can force synchronization with the videotestsrc:
gst-launch-1.0.exe videotestsrc ! video/x-raw, format=I420, width=400, height=400, framerate=1/5 ! identity sync=true ! timeoverlay ! jpegenc ! multifilesink location="/some/location/img_%06.jpg"


text:
Q: Weak convergence in $L^1$ with a bounded factor Let $Z_n$ be a variable that converges weakly in $L^1$ to $Z$, that is for all $E\in\mathcal{F}$ it holds that
$$
\mathbb{E}\left[Z_n\,I(E)\right]\to \mathbb{E}\left[Z\,I(E)\right].
$$
Let now $X$ be a bounded random variable. A want to prove that $Z_n\,X$ converges weakly to $Z\,X$, that is
$$
\mathbb{E}\left[(Z_n-Z)\,X\,I(E)\right]\to 0.
$$
In order to do prove this I am trying to find a proper inequality, I thought to the Holder inequality but it does not seem to be the proper way:
$$
\left|\mathbb{E}\left[(Z_n-Z)\,X\,I(E)\right]\right|\leq \mathbb{E}\left[\left|(Z_n-Z)\,X\,I(E)\right|\right]\leq C\,\mathbb{E}\left[\left|(Z_n-Z)\,I(E)\right|^p\right]^{1/p}
$$
with $p>1$.

A: You need a theorem from Functional Analysis which says that weakly convergent sequences are norm bounded. Hence $\sup \{\int |Z_n|+\int|Z| \}<\infty$. Now the hypothesis implies that $EZ_nY \to EZY$ for any simple function $Y$. Since $XI_E$ is a bounded measurable function there exists a simple function $Y$ such that $||XI_E-Y||_\infty<\epsilon$. Hence $E|Z_nXI_E-ZXI_E|\leq \epsilon \int |Z_n| +\epsilon\int |Z| +|\int Z_nY-\int ZY|$. Let $n \to \infty$ and then $\epsilon \to 0$.


text:
Q: Removing, Searching, and Returning a position using Type T Need help defining these methods, I am not familiar using Type T.
Define the following two methods in the LinkedList class:
1) The searchItem method takes an item to be search of type T in the list and if it is found then returns the position in the list, otherwise return -1
2) The removeItem method takes as argument an item to be removed of type T and returns true if the item is successfully removed, otherwise returns false.

A: This sounds suspiciously like homework.
When you create a generic class in java you just need the class to have the  on it.
public class LinkedList<T>

The T can be any letter you want it to be. It does not matter what you choose. Then when you create an instance of that class you will give it type t.
LinkedList<int> mylist = new LinkedList<int>();

This will create an instance of the linked list where everything that references T will be replaced with int.
So your methods just need to use type T.
public class LinkedList<T>
{

    public int Search(T toSearch)
    {
        //search your nodes
        return -1;
    }

    public boolean Remove(T toRemove)
    {
        //find item and remove if you can, return true
        return false;
    }

}

Just as a final note, returning a boolean for success is BAD. It is an exceptional case if the user tries to remove something that isn't in the list, and should throw an exception. Otherwise it does not need to return anything.


text:
Q: Annotating an annotation with Matplotlib I am currently doing some "fancy" annotation in Matplotlib:
import matplotlib.pyplot as plt
ax = plt.subplot(111)
plt.axis('equal')
src_pos, dst_pos = (0, 0), (1, 1)
src_patch = plt.Rectangle(src_pos, .25, .25, color='r')
ax.add_patch(src_patch)
dst_patch = plt.Circle(dst_pos, .25, color='b')
ax.add_patch(dst_patch)
arrowprops = dict(
    arrowstyle='<-',
    connectionstyle='arc3,rad=0.3',
    patchA=dst_patch,
    patchB=src_patch,
    shrinkA=1,
    shrinkB=1)
ant = ax.annotate('', src_pos, dst_pos, arrowprops=arrowprops)
plt.draw()
plt.show()

Now I'd like to add a bit of text next to the arrow. The output should look like:

I am interested in a general solution in which the text placement is chosen programmatically based on the renderer's choice of arrow path. E.g.,

*

*The text should be placed appropriately for unknown values of src_pos and dst_pos.

*The text should be placed appropriately regardless of how the arrowprops are set and which connectionstyle is used.

*I would prefer to not have to call plt.draw() until the end of the script.

Thanks!

A: Just looking at the http://matplotlib.org/users/annotations_intro.html page.  It seems that the text can be placed independently of the arrow if you know the coordinates.  Add this before the draw() command:
ant2 = ax.annotate('this is\nthe text\ni want\nto add', xy=(0.1, 0.8), xytext=(0.1, 0.8), horizontalalignment='left', verticalalignment='top')

In terms of a generalized solution, it would be as complex as the original annotate because there are quite a few different kinds of things that are created depending on the parameters given to annotate.  For instance if the arrowstyle is not specified then a YAArow patch instance is created.  You can call YAArow's get_path() but a path is of limited usefulness since it's more or less just a collection of points.  You would need to write a "find_middle_of_path()" which would need to take into account that paths don't necessarily need to be contiguous, and that sometimes all of the attributes of the path are not filled out by methods that use it, etc.  An example of when an arrow path would be non-contiguous would be when the middle of the arrow path is clipped by the edge of the figure.
If arrowstyle is specified then a FancyArrowPatch instance is created.  If a FancyArrowPatch is created, you can call get_path_in_displaycoord() to get the path with the same caveat as for YAArow patch path.
IMHO you are better off creating a number of rather simple routines that call annotate two times, one for the arrow and one for the text that correspond with the probably limited ways that you really want to use annotate.

A: There's a another option text() to add any text to the plot at known position.
look at this link for extra options
ant1 = ax.text(0.4, 0.6, 'text')

This doesn't denpend on the arrowprops


text:
Q: Programming cc2530 on Linux I am trying to program a cc2530 mcu, all the example software and libraries are provided for IAR, but since I am on ubuntu, I am unable to use it, I have installed sdcc but I am still unclear as to how should I go about debugging codes and where can I get hardware abstraction libraries and linker script.

A: One simple solutions would be to download and configure Eclipse CDT for Ubuntu. Last year I was able to configure a Eclipse to do embedded development for TIVA TM4C123 ARM Cortex M4 processor.  I used Open On-Chip Debugging called openocd.  To a large extend you will be doing some ground breaking work. Communities like Embedded Systems and Electronic SE are here to help you. When you are successful post the steps so other could benefit. Below are some references that might help you.  Good luck.
References:

*

*Open On-Chip Debugging

*How To: Develop on the TI Tiva LaunchPad using Linux

*CC2530 Contiki/6LowPan port

*How to burn .hex intel format file on cc2530 EB

*Getting Started with the TI Stellaris LaunchPad on Linux


text:
Q: How can knitr's cached results be used to reproduce the environment in a given chunk? tl;dr
My question: Within an R session, is there some way to use knitr's cached results to 'fast-forward' to the environment (i.e. the set of objects) available in a given code block, in the same sense that knit() itself does?

Setup:
knitr's built-in cacheing of code chunks is one of its killer features.
It's especially helpful when some chunks contain time-consuming computations. Unless they (or a chunk they depend on) is altered, the computations only need be carried out the first time the document is knited: upon all subsequent calls to knit, the objects created by the chunk will just be loaded from the cache.
Here's a minimal-ish example, a file called "lotsOfComps.Rnw":
\documentclass{article}
\begin{document}

The calculations in this chunk take a looooong time.

<<slowChunk, cache=TRUE>>=
Sys.sleep(30)  ## Stands in for some time-consuming computation
x <- sample(1:10, size=2)
@

I wish I could `fast-forward' to this chunk, to view the cached value of
\texttt{x}

<<interestingChunk>>=
y <- prod(x)^2
y
@

\end{document}

Times needed to knit and TeXify "lotsOfComps.Rnw":
## First time
system.time(knit2pdf("lotsOfComps.Rnw"))
##   user  system elapsed
##   0.07    0.02   31.81

## Second (and subsequent) runs
system.time(knit2pdf("lotsOfComps.Rnw"))
##   user  system elapsed
##   0.03    0.02    1.28

My question:
Within an R session, is there some way to use knitr's cached results to 'fast-forward' to the environment (i.e. the set of objects) available in a given code block, in the same sense that knit() itself does?

Doing purl("lotsOfComps.Rnw") and then running the code in "lotsOfComps.R" doesn't work, because all of the objects along the way must be recomputed.
Ideally, it would be possible to do something like this to end up in the environment that exists at the beginning of <<interestingChunk>>=:
spin("lotsOfComps.Rnw", chunk="interestingChunk")
ls()
# [1] "x"
x
# [1] 3 8

Since spin() is not (yet?) available, what's the best way to get the equivalent result?

A: This has to be one of the ugliest kludges I've written in a while...
The basic idea is to scan the .Rnw file for chunks, extract their names, detect which ones are cached, then determine which ones need to be loaded.  Once we do that we scan step by step grab each chunk name that needs be loaded, detect the database name from the cache folder, and load it using lazyLoad.  After we load all the chunks we need to force evaluation.  Ugly and I'm sure there are a few errors but it seems to work on the simple example you gave and some other minimal examples I created.  This makes the assumption that the .Rnw file is in the current working directory...
load_cache_until <- function(file, chunk, envir = parent.frame()){
    require(knitr)

    # kludge to detect chunk names, which come before the chunk of
    # interest, and which are cached... there has to be a nicer way...
    text <- readLines(file)
    chunks <- grep("^<<.*>>=", text, value = T)
    chunknames <- gsub("^<<([^,>]*)[,>]*.*", "\\1", chunks)
    #detect unnamed chunks
    tmp <- grep("^\\s*$", chunknames)
    chunknames[tmp] <- paste0("unnamed-chunk-", seq_along(tmp))
    id <- which(chunk == chunknames)
    previouschunks <- chunknames[seq_len(id - 1)]
    cachedchunks <- chunknames[grep("cache\\s*=\\s*T", chunks)]

    # These are the names of the chunks we want to load
    extractchunks <- cachedchunks[cachedchunks %in% previouschunks]

    oldls <- ls(envir, all = TRUE)
    # For each chunk...
    for(ch in extractchunks){
        # Detect the file name of the database...
        pat <- paste0("^", ch, ".*\\.rdb")
        val <- gsub(".rdb", "", dir("cache", pattern = pat))
        # Lazy load the database
        lazyLoad(file.path("cache", val), envir = envir)
    }
    # Detect the new objects added
    newls <- ls(envir, all = TRUE)
    # Force evaluation...  There is probably a better way
    # to do this too...
    lapply(setdiff(newls, oldls), get)

    invisible()

}

load_cache_until("lotsOfComps.Rnw", "interestingChunk")

Making the code more robust is left as an exercise for the reader.

A: Here is one solution, which is still a little bit awkward but it works. The idea is to add a chunk option named mute which takes NULL by default, but it can also take an R expression, e.g. mute_later() below. When knitr evaluates the chunk options, mute_later() can be evaluated and NULL is returned; at the same time, there are side effects in opts_chunk (setting the global chunk options like eval = FALSE).
Now what you need to do is to put mute=mute_later() in the chunk after which you want to skip the rest of the chunks, e.g. you can move this option from example-a to example-b. Because mute_later() returns NULL which happens to be the default value of the mute options, the cache will not be broken even you move this option around.
\documentclass{article}
\begin{document}

<<setup, include=FALSE, cache=FALSE>>=
rm(list = ls(all.names = TRUE), envir = globalenv())
opts_chunk$set(cache = TRUE) # enable cache to make it faster
opts_chunk$set(eval = TRUE, echo = TRUE, include = TRUE)

# set global options to mute later chunks
mute_later = function() {
  opts_chunk$set(cache = FALSE, eval = FALSE, echo = FALSE, include = FALSE)
  NULL
}
# a global option mute=NULL so that using mute_later() will not break cache
opts_chunk$set(mute = NULL)
@

<<example-a, mute=mute_later()>>=
x = rnorm(4)
Sys.sleep(5)
@

<<example-b>>=
y = rpois(10,5)
Sys.sleep(5)
@

<<example-c>>=
z = 1:10
Sys.sleep(3)
@

\end{document}

It is awkward in the sense that you have to cut-and-paste , mute=mute_later() around. Ideally you should just set the chunk label like the gist I wrote for Barry.
The reason that my original gist did not work is because chunk hooks are ignored when a chunk is cached. The second time you knit() the file, the chunk hook checkpoint for example-a was skipped, therefore eval=TRUE for the rest of chunks, and you saw all chunks were evaluated. By comparison, chunk options are always dynamically evaluated.

A: Yihui points to a gist that comes close to doing exactly what I asked for.
In response to a question from Barry Rowlingson (aka Spacedman), Yihui constructed a 'checkpoint' hook that lets the user set the name of the last chunk that will be processed by a call to knit. To process chunks up through one named example-a, simply do opts_chunk$set(checkpoint = 'example-a') somewhere in an initial 'setup' chunk.
The solution works beautifully --- the first time it is run with a given checkpoint. The second and subsequent times, unfortunately, knit seemingly ignores the checkpoint and processes all of the chunks. (I discuss a workaround below, but it's not ideal).
Here is a slightly abridged version of Yihui's gist:
\documentclass{article}
\begin{document}

<<setup, include=FALSE>>=
rm(list = ls(all.names = TRUE), envir = globalenv())
opts_chunk$set(cache = TRUE) # enable cache to make it faster
opts_chunk$set(eval = TRUE, echo = TRUE, include = TRUE)

# Define hook that will skip all chunks after the one named in checkpoint
knit_hooks$set(checkpoint = function(before, options, envir) {
if (!before && options$label == options$checkpoint) {
opts_chunk$set(cache = FALSE, eval = FALSE, echo = FALSE, include = FALSE)
}
})

## Set the checkpoint
opts_chunk$set(checkpoint = 'example-a') # restore objects up to example-a
@

<<example-a>>=
x = rnorm(4)
@

<<example-b>>=
y = rpois(10,5)
@

<<example-c>>=
z = 1:10
@

\end{document}

Because checkpoint="example-a", the script above should run through the second chunk, and then suppress all further chunks, including the ones that creates y and z. Let's try that a couple of times to see what happens:
library(knitr)

## First time, works like a charm
knit("checkpoint.Rnw")
ls()
[1] "x"

## Second time, Oops!, runs right past the checkpoint
knit("checkpoint.Rnw")
ls()
[1] "x" "y" "z"

The workaround I mentioned above is, after the first run-through, to

*

*Edit checkpoint.Rnw to set another checkpoint (by doing, e.g., opts_chunk$set(checkpoint = 'example-b'))

*Run knit("checkpoint.Rnw"),

*Edit checkpoint.Rnw to set the checkpoint back to 'example-a, (by doing, opts_chunk$set(checkpoint = 'example-a'))

*Run knit("checkpoint.Rnw) once more. This will once again process all chunks up to but not beyond example-a.

This can be much faster than recomputing all objects in the chunks, so it's good to know about, even if it's not ideal.

A: They're just like any data file produced by save.  If you grab the knitr-cache exampe from it's new location, it's just:
> library(knitr)
> knit("./005-latex.Rtex")
> load("cache/latex-my-cache_d9835aca7e54429f59d22eeb251c8b29.RData")
> ls()
 [1] "x"

A: How about adding the following code chunk at the bottom of your markdown file ?
```{r save_workspace_if_not_saved_yet, echo=FALSE}
if(!file.exists('knitr_session.RData')) {
  save.image(file = 'knitr_session.RData')
}
```

The first time you knit, the workspace state at the end of the process will be saved (assuming the process doesn't produce any errors). Every time you want the latest version of your workspace, just delete the file in your working directory.


text:
Q: What interpretation makes '$\exists x(Fx \iff Gx)$' true and '$\exists x(Fx) \iff \exists x(Gx)$' false--given the domain {1, 2, 3}? To make the antecedent true at least one thing that is or is not in the extension of $F$ must also be or not be in the extension of $G$.
But then this seems to automatically make at least one case of the second bi-conditional, true. And to find an interpretation where the first is true and the second false, I need there to be no cases where what is or is not $F$ is not the same as what is or is not $G$.
One idea I had was to set $F$'s extension to {1} and $G$'s extension to $\{∅\}$.
In general I am not clear on what it takes to make the antecedent false. For the bi-conditioanl to be false, the truth of '$\exists x(Fx)$' and '$\exists x(Gx)$' need to mismatch. And the truth of either requires at least one member of the domain to be in the extension of the predicate letter. So if I satisfy that requirement, then to get the mismatch that falsifies the bi-conditional I need to have nothing from the domain in the extension of the other predicate letter.
Thanks for any help.

A:
One idea I had was to set $F$'s extension to {1} and $G$'s extension to $\{∅\}$.

That's correct.
With $x \mapsto 2$, there is an object of which neither $F$ nor $G$ is true, so the biconditional is true, so $\exists x (F(x) \leftrightarrow G(x))$ is true.
However, with $x \mapsto 1$ there is an object of which $F$ is true, so $\exists x F(x)$ is true, but since the extension of $G$ is empty, $\exists x G(x)$ is false, so $\exists x F(x) \leftrightarrow \exists x G(x)$ is false, as desired.

In general I am not clear on what it takes to make the antecedent false

If by antecedent you mean the left-hand side of the biimplication (typically the antecedent/succedent terminology is only used with one-directional implication), $\exists x F(x)$,  then the requirement would be that the extension of $F$ is empty. But you don't necessarily need the left-hand side false, but, as you say, a mismatch between the two sides, which is achieved by having $\exists x F(x)$ true but $\exists x G(x)$ false (or vice versa).


text:
Q: Probability lotto draw - exactly one number divisible by 9? What is the probability that a lotto draw (6 out of 45) will draw exactly one number divisible by 9?
I know the probability that it will not draw a number divisible by 9 is $\frac{40}{45} * \frac{39}{44} * \frac{38}{43} * \frac{37}{42} * \frac{36}{41} * \frac{35}{40}$.
But how do I calculate the probability for exactly one number divisible by 9?

A: Out of the $\binom{45}6$ possible picks, the number of picks where exactly one number is divisble by 9 is the product of

*

*choosing the number divisible by 9, of which there are 5 of them

*choosing the other 5 numbers in the pick from the 40 numbers not divisible by 9, hence $\binom{40}5$
Thus the desired probability is $\frac{5\binom{40}5}{\binom{45}6}$. This is an example of a hypergeometric distribution.

A: Hint:
First calculate the probability that the first drawn number is divisible by $9$ and the others are not.
Then multiply this result with ... , any idea of your own here?


text:
Q: SQL: Adding another MAX field to existing MAX Date Query I have an existing query that is picking up the max date of the exdt field per below for every record for that particular item. I'm trying to add an additional MAX calculation to the sqn field, essentially picking up records with the highest exdt and sqn field together. I tried adding an additional "AND (a.sqn = (SELECT MAX(sqn) to the WHERE and it seems to not like multiple selects.
SELECT a.item, a.cpc, dt.dsc, a.exdt, a.sqn

FROM     dbo.ct AS a INNER JOIN dbo.dt ON a.cpc = dt.cpc

WHERE (a.exdt = (SELECT MAX(exdt) AS exdt FROM  dbo.ct AS a

Any help would be appreciated!
Thanks.

A: The script to get records having  max of both fields is the following
SELECT a.item, a.cpc, dt.dsc, a.exdt, a.sqn
FROM     dbo.ct AS a INNER JOIN dbo.dt ON a.cpc = dt.cpc
WHERE
a.exdt = (SELECT MAX(exdt) AS exdt FROM  dbo.ct )
and
a.sqn= (SELECT MAX(sqn) AS exdt FROM  dbo.ct)

You can also use CTEas follows
with
cte_principal as
(SELECT a.item, a.cpc, dt.dsc, a.exdt, a.sqn
 FROM     dbo.ct AS a INNER JOIN dbo.dt ON a.cpc = dt.cpc),
cte_max_exdt as (SELECT MAX(exdt) AS exdt FROM  dbo.ct),
cte_max_sqn as (SELECT MAX(sqn) AS exdt FROM  dbo.ct)

select p.* from cte_principal p
inner join cte_max_exdt  on p.exdt =cte_max_exdt.exdt
inner join cte_max_sqn  pn p.sqn=cte_max_sqn.sqn

A: Perhaps you need subquery which is going to find max date for each item.
That is ct_max_date in my case
After that you join that subquery by max_date and item_Id
SELECT a.item, a.cpc, dt.dsc, a.exdt, a.sqn

FROM     dbo.ct AS a
INNER JOIN dbo.dt ON a.cpc = dt.cpc
inner join (
select max(exdt) as max_date, ct.cpc
from dbo.ct
group by ct.dt
) as ct_max_date on a.cpc=ct_max_date.cpc and a.exdt=ct_max_date.max_date


text:
Q: Clearing inbox messages Is there any facility to clear inbox message? If I want to delete some of the messages from inbox, then is it possible?

A: No, there is no direct way to clean those "messages" because they're not standalone - they represent some real content that exist somewhere else and only linked in the message.
The only way to have messages removed from your Stack Exchange Inbox is to delete the related posts/comments.
For example, you can flag this comment as "obsolete" or "not constructive" if you want and if moderator will remove it, the related item in your Inbox would be removed as well.
In case of answers to your question (like this one)  there's not much you can do though.
If you will explain why it bothers you so much to have Inbox items maybe we can come with better answer.

A: It's not really an inbox, it's notifications of activity that is relevant to you and hence you might be interested in.
Everything you see in that 'inbox' is a public post somewhere on the Stack Exchange network. So once you've acknowledged that you've seen it (by dropping down the inbox, which clears the red dot), there's nothing more to do.

A: To clear the glowing red dot, just view them. (Click on the glowing dot)
Otherwise, nope--no facility to clear inbox messages. Why would you want that anyway?


text:
Q: JXCollapsiblePane from SwingX in a class is affecting all the other panes created in other objects made by the class I have a class that creates elements for a grid in a GridLayout, which basically consists of 4 panels that are packed together.
I wanted one of the panels (which contains a JTextArea) to be collapsible because it's fairly verbose and I don't want it to be taking up so much screen space. Naturally, I came across the SwingX library and used the JXCollapsiblePane to do this, and even though it works as intended, it seems as though it keeps affecting all the other JXCollapsiblePanes whenever I click the toggle button on just one of them. It doesn't actually open them, but it makes it so the window expands to accommodate the space as though they were opened. I can take pictures if you want a better description, but later. How do I make it so it doesn't do that? I'm pretty sure I'm not using any static attributes, so I'm not sure why it's doing that.
On a side note, if someone could tell me if this is correct coding style (I feel like what I'm doing is really inefficient with the super-nested panels, new to Swing) that would be nice.
Here are the relevant code snippets from my project:
        JXCollapsiblePane collapsiblePane = new JXCollapsiblePane();
        JButton toggle = new JButton(collapsiblePane.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION));
        toggle.addActionListener(e -> {
            toggle.setText(collapsiblePane.isCollapsed() ? "▼" : "▶");
        });
        toggle.setText("▶");
        toggle.setPreferredSize(new Dimension(20, 20));
        Border emptyBorder = BorderFactory.createEmptyBorder();
        toggle.setBorder(emptyBorder);
        resultTextPanel.add(toggle);
        collapsiblePane.setCollapsed(true);
        collapsiblePane.setSize(250, 60);
        gridElemPanel.add(resultTextPanel, BorderLayout.NORTH);
         ...
        if (ngramText != null && !ngramText.contains("null")) {
            JTextArea ngramLabel = new JTextArea(ngramText);
            ngramLabel.setLineWrap(true);
            ngramLabel.setWrapStyleWord(true);
            ngramLabel.setFont(new Font("Courier", Font.PLAIN, 12));
            JScrollPane scrollPane = new JScrollPane(ngramLabel);
            scrollPane.setPreferredSize(new Dimension(250, 60));
            scrollPane.getHorizontalScrollBar().setUnitIncrement(16);
            collapsiblePane.add(scrollPane);
            collapsiblePane.setPreferredSize(scrollPane.getPreferredSize());
            gridElemPanel.add(collapsiblePane, BorderLayout.SOUTH);
        }

A: GridLayout:

The container is divided into equal-sized rectangles

so when you change one, all change accordingly.
If you need more flexibilty (at a price of more complexity) consider GridBagLayout.


text:
Q: PFFacebookUtils logInWithPermissions fails on simulator I'm integrating my iOS app with Parse and Facebook. It works fine on my iPhone 4s - running iOS 6 -- but when I try a test account on my xCode 5 simulator it fails.
When I press my login with facebook button I'm presented with a screen saying: You have already authorized Test999 (my app's name.) This happens right when I'm calling this line:
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error)

I press OK. It sends me to a "You have to log in first" screen. I put in my username and password, and press Log In -- and I'm sent back to the You have already authorized Test999. I press OK -- and I'm presented with a blank view with an x on the top left to close it. There's nothing else to do so I push it, and I'm sent back to the "You have to log in first" screen.
So there's really no way to log in with the simulator. I tried to "Reset content and settings" but it doesn't help.
Following an answer on a similar problem I tried adding a reconnectWithFb method (below) and I also updated my Facebook sdk to version 3.9. Nothing helps.
This is from my login with facebook method:
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {

if (!user) {
    if (!error) {
        NSLog(@"Uh oh. The user cancelled the Facebook login.");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"User cancelled facebook login" message:@"Uh oh. The user cancelled the Facebook login." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Dismiss", nil];
        [alert show];
    } else {
        NSLog(@"welcome screen loginWithFB: Uh oh. An error occurred: %@", error);
        [self performSelector:@selector(reconnectWithFB) withObject:nil afterDelay:0.5];
    }
} else if (user.isNew) {
    NSLog(@"New user with facebook signed up and logged in!");
} else {
    NSLog(@"User with facebook logged in!");
    FBRequest *request = [FBRequest requestForMe];
    [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        if (!error) {
            NSString *facebookUsername = [result objectForKey:@"name"];
            [PFUser currentUser].username = facebookUsername;
            [[PFUser currentUser] setObject:[result objectForKey:@"id"] forKey:@"facebookid"];
            [[PFUser currentUser] saveEventually];
            [[NSNotificationCenter defaultCenter] postNotificationName:kUsersToWatchNotification object:result];
        } else {
            NSLog(@"Error getting the FB username %@", [error description]);
        }
    }];
}

and my reconnectWithFB (which on the simulator always have an empty fbAccounts array:)
-(void) reconnectWithFB {
    NSLog(@"reconnectWithFB called");
    ACAccountStore *accountStore;
    ACAccountType *accountTypeFB;
    if ((accountStore = [[ACAccountStore alloc] init]) && (accountTypeFB = [accountStore  accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) ){
    NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];

    NSLog(@"fbAccounts %@", fbAccounts);

    id account;
    if (fbAccounts && [fbAccounts count] > 0 && (account = [fbAccounts objectAtIndex:0])){
        [accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error) {
                //we don't actually need to inspect renewResult or error.
                if (error){
                    NSLog(@"error in reconnectWithFB %@", error);
                }
        }];
      }
   }
}

Any help with this would be greatly appreciated.

A: Looks like the solution was to add the open url methods to my App Delegate:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [PFFacebookUtils handleOpenURL:url];
}

and
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url     sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [PFFacebookUtils handleOpenURL:url];
}

A: This Answer Seems to be OutDated, the Compiler Warns of Deprecation.
Current Method should be :
- (BOOL) handleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [FBAppCall handleOpenURL:url
                      sourceApplication:sourceApplication
                      withSession:[PFFacebookUtils session]];
}

A: Updated way:
In your AppDelegate.m put the following:
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    return [FBAppCall handleOpenURL:url
                  sourceApplication:sourceApplication
                        withSession:[PFFacebookUtils session]];
}

Then make sure you call this:
- (void)applicationDidBecomeActive:(UIApplication *)application {
    [FBAppCall handleDidBecomeActiveWithSession:[PFFacebookUtils session]];
        [FBAppEvents activateApp];
}

Later on in the coding make sure you add this one-liner:
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[PFFacebookUtils session] close];
}


text:
Q: Issue displaying correct week from MySQL database I have a expenses script that displays the current week by week number based on week number in the database (w10) and can select other weeks by using ?selectWeek=w46
We have been using this script for a year now and does not show the information for this week (w10) because there are 2 entries in the database for w10 and it's getting confused which one to display.
Database Structure
ID - Base_Charge - Week - Year - Created_ At

1 - 20000 - w10 - 2021 - 2021-03-08
53 - 454333 - w10 - 2022 - 2022-03-07

Code:
<?php
include '../main.php';
check_loggedin($pdo);
// output message (errors, etc)
$msg = '';

$stmt = $pdo->prepare('SELECT * FROM expense_base_charge');
$stmt->execute();
$weekList = $stmt->fetchAll(PDO::FETCH_ASSOC);

if(isset($_GET['selectWeek'])){
    $week  =       $_GET['selectWeek'];
}else{
    $ddate  =       date('y-m-d');
    $date = new DateTime($ddate);
    $week = 'w'.$date->format("W");
}

$stmt = $pdo->prepare('SELECT * FROM expense_base_charge where week = ?');
$stmt->execute([$week]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);

$stmt = $pdo->prepare('SELECT * FROM expense where week = ?');
$stmt->execute([$base_charge['id']]);
$expense = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

Any idea how to make it view the correct week please?

A: When you want select only current year records you can improve your where statement in next way:
$week = 'w10';

$stmt = $pdo->prepare(
    'SELECT * FROM expense_base_charge WHERE week = ? AND year = YEAR(NOW())'
);

$stmt->execute([$week]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);

PHP MySQL Feddle
Another way, you can calculate default week/year values in PHP
(in next example I also changed week column format to int)
//set current week/year values when they not provided by GET
$week = $_GET['selectWeek'] ?? date('W');
$year = $_GET['selectYear'] ?? date('Y');

//debug only print
printf('YEAR: %d, WEEK: %d ' . PHP_EOL, $year, $week);

//select data fom MySQL using week & year
$stmt = $pdo->prepare(
    'SELECT * FROM expense_base_charge WHERE week = ? AND year = ?'
);

$stmt->execute([$week, $year]);

$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);

Test online

A: The problem is that you are storing the value for week and year in a denormalized form. The week number should not be stored with prefix w. Ideally, you would store both of them in a single column. Then you could use YEARWEEK() function in SQL.
This is of course assuming that you are using ISO 8601 week numbering. If you are not following this scheme then fetching the correct value will be very difficult.
If you don't want to change the table schema now, you can still get the same value using PHP. Use 'o' for year number and 'W' for week number.
$week = $_GET['selectWeek'] ?? 'w'.(new DateTime())->format("W");
$year = $_GET['selectYear'] ?? (new DateTime())->format("o");

$stmt = $pdo->prepare('SELECT * FROM expense_base_charge where week = ? and year = ?');
$stmt->execute([$week, $year]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);


text:
Q: ftplib -- deleting many files from ftp folder I am pretty new to Python, but would like to use it to do some tasks on an FTP. Feel like it should be fairly easy but I am having some issues when trying to delete multiple files (hundreds) from an FTP folder. I have the file names I want to delete as strings from a SQL table I can copy and paste if needed.
My code so far:
import os
import ftplib

ftpHost = 'ftp.myhost.com'
ftpPort = 21
ftpUsername = 'myuser'
ftpPassword = 'mypassword'

ftp = ftplib.FTP(timeout=30)

ftp.connect(ftpHost, ftpPort)

ftp.login(ftpUsername, ftpPassword)

ftp.cwd("/myftpfolder/January2023")

ftp.delete("1234myfile.mp4")

ftp.quit()

print("Execution complete...")

As above, I can delete the files one-off but is there a practical way for me to delete about 800 files from the folder above if I were able to paste them somewhere or put them in a text file and have Python read through it to execute the deletes? I suppose this isn't necessarily an FTP or ftplib specific question, but could help me get a better general understanding of lists, tuples, etc. Using Python3.10 btw.
Thanks!


text:
Q: An elegant closure property of uniform distributions?
*

*In dice notation, any collection of polyhedral dice can be represented as a polynomial in one unknown. For example, $1d^{20} + 3d^6$ denotes a collection consisting of one 20-sided die and three 6-sided dice.

*There is a map $P$ sending any such collection of dice to the corresponding probability distribution. For example, the map sends the single $k$-sided die $d^k$ to the uniform distribution $U_k$ over $1\ldots k$.

*In general, you compute the distribution of a sum of dice by taking the convolution of the individual dice distributions. For example, the map $P$ sends $d^a + 3d^b$ to $U_a\oplus (U_b \oplus U_b \oplus U_b)$.

*In this way, the map $P$ is a morphism between the space of dice polynomials (formalized as a polynomial rig) and the space of dice probabilities (formalized as the set of all the uniform distributions $U_1, U_2, U_3,\ldots$, plus all finite convolutions of them).
It preserves addition, sending polynomial sums to probability convolutions.

*But polynomials also have multiplicative structure: The product of two individual dice $d^a\cdot d^b$ is $d^{a+b}$, for example, and the corresponding distribution is $U_{a+b}$.

*My question: Can we define multiplication on the target space of distributions so that $P$ preserves multiplication as well as addition, acting as a kind of ring homomorphism?
We already know what the multiplication operator must be on the uniform distributions $U_k$; we have $U_a \otimes U_b \equiv U_{a+b}$.
I think that if we impose the distributive property along with this base case, we have enough to define $\otimes$ throughout the entire space. Indeed if $A$ and $B$ are finite convolutions of $U_i$, then $A\otimes B$ can be expanded according to the distributive property into a unique convolution of uniform distributions $U_j$.
But I am unsure how to prove whether this works---is the operator really well defined, or does it somehow give contradictory or underdetermined answers in some cases?


text:
Q: I want to transfer a number from one file in Python to another file Can I, for example, copy this number from one file to another?
inp = int(input("Enter your number:"))

I want to copy the inp to another file and I want to use the number in the other file ,like this
another file:
print("", inp)

Can I do this and thank you.

A: file1:
input_num = int(input('Enter a number: '))

file2:
from file1 import input_num
num = input_num

A: You could write it in a function, then import that function in the other file.
input.py
def input_number():
     inp = int(input("Enter your number"))
     return inp

Other file:
from input import input_number

inp = input_number()
print("", inp)


text:
Q: Highcharts : barchart I have a barchart with many years in the x-axis. I want to select the years. Here we have the opportunity to do this in 2 ways: either with a click-and-drag, either with sliders.
I have two problems.

*

*The first concerns the click-and-drag: When I select the extreme years, then appear two years, and not only those selected. For example, if I select "1960" then appears 1960 and 1961. Same if I select 2016 shows 2015 and 2016.

*The second problem concerns the sliders. If both sliders are to the same value, then there is a problem. For example, if my two sliders are on 1998, the graph shows the years 2015 and 2016. If they are both on 1966, the graph displays the years 1994 and 1995.
Here is my code HTML :

    <form oninput="output1.value=parseInt(slider1.value)+1960;output2.value=parseInt(slider2.value)+1960">
                                    <input type="range" name="slider1" class="mySlider" min="0" max="56" value="0" />
                                    <output name="output1" id="output1" for="slider1" style="font-size:10px;padding-top:0px;text-align:left">1960</output>

                                    <input type="range" name="slider2" class="mySlider" min="0" max="56" value="56" />
                                    <output name="output2" id="output2" for="slider2" style="font-size:10px;padding-top:0px;text-align:right">2016</output>
                                </form>

Here is my code JavaScript :
$(function () {
  $('#container').highcharts({
    chart: {
      type: 'column',
      zoomType: 'x'
    },
    colors:[
      '#d8d826'
    ],
    legend:{
      enabled:false
    },
    title:{
      style:{
        fontSize:'0px'
      }
    },
    subtitle:{
      style:{
        fontSize:'0px'
      }
    },
    xAxis: {
        // NOTE: There is an interesting bug here where not all labels will be shown when the chart is redrawn.
      // I'm not certain why this is occuring, and I've tried different methods to no avail. I'll check with Highcharts.
      categories: ['1960','1961','1962','1963','1964','1965','1966','1967','1968','1969','1970','1971','1972','1973','1974','1975','1976','1977','1978','1979','1980','1981','1982','1983','1984','1985','1986','1987','1988','1989','1990','1991','1992','1993','1994','1995','1996','1997','1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'],
      tickmarkPlacement: 'on', tickInterval: 1,
      minRange: 1   // set this to allow up to one year to be viewed
    },
    yAxis: {
      min: 15,
      title: {
        text: 'Number',
        style:{
          fontSize:'0px'
        }
      }
    },
    tooltip: {
      shared: false,
      useHTML: true
    },
    plotOptions: {
      column: {
        pointPadding: 0.2,
        borderWidth: 0
      }
    },
    series: [{
      name: 'data by year',
      data: [49.9,83.6,48.9,69.1,83.6,40.9,69.9,83,28.9,40.9,81.6,24.9,46.4,49.9,83.6,48.9,69.1,83.6,40.9,69.9,83,28.9,40.9,81.6,24.9,46.4,49.9,83.6,48.9,69.1,83.6,40.9,69.9,83,28.9,40.9,81.6,24.9,46.4,49.9,83.6,48.9,69.1,83.6,40.9,69.9,83,28.9,40.9,81.6,24.9,46.4,49.9,83.6,48.9,69.1,50]
    }]
  });

    // on change handler for both sliders
  $('.mySlider').bind('change', function(e) {
    e.preventDefault();
    var chart = $('#container').highcharts();
    // use setExtremes to set the x-axis ranges based on the values in the sliders
    chart.xAxis[0].setExtremes($('input[name="slider1"]').val(), $('input[name="slider2"]').val());
  });

});

Look at in : https://jsfiddle.net/uvat8u05/13/
How to solve these two problems please?
Thank you

A: Highcharts are expecting int values for setExtremes() method. So you should get the value of sliders;
$('input[name="slider1"]').val();

Then parse this value to int;
parseInt($('input[name="slider1"]').val());

Here I fixed it for you: jsFiddle


text:
Q: For a GRPC Service in NET 6, Postman is showing bool properties as [] when they have a false value If I use bool as type in the proto file Postman doesn't even show the property, if I use google.protobuf.BoolValue as type it shows "is_valid": {} when is_valid = false in C#, but it works when is_valid = true, so why it doesn't show anything when it's false?
Proto example:
syntax = "proto3";

option csharp_namespace = "xxx.Organization.V1.Contracts";

import "google/protobuf/wrappers.proto";
import "protos/txp/common/api/query/range.proto";
import "protos/txp/common/filters/string_filter.proto";
import "protos/txp/organization/v1/timezone.proto";

package txp.organization.v1;

    message AddressValidationResponse {
        Address address = 1;
        google.protobuf.BoolValue is_valid = 2;
        google.protobuf.BoolValue is_non_postal = 3;
        repeated google.protobuf.StringValue errors = 4;
        google.protobuf.StringValue success_message = 5;
        google.protobuf.StringValue address_precision = 6;
        Results results = 7;
    }

Auto-generated C# code for is_valid field:
/// <summary>Field number for the "is_valid" field.</summary>
public const int IsValidFieldNumber = 2;
private static readonly pb::FieldCodec<bool?> _single_isValid_codec = pb::FieldCodec.ForStructWrapper<bool>(18);
private bool? isValid_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool? IsValid {
  get { return isValid_; }
  set {
    isValid_ = value;
  }
}

Postman Response:

Thanks!

A: Found the reason for this, in these cases Postman won't show porperties when their value equals to its default value, so no big deal for me. But maybe there's a way to make these properties show anyway in case somebody needs them to show.


text:
Q: Manually added Link missing in Mobile menu I added a link to my WordPress menu using the "wp_nav_menu_items" hook. It works perfectly well in the normal widescreen menu but it does not show up in the mobile dropdown select menu. Is there a different hook that I need?
Here is my code (in my themes Functions.php file):
add_filter( 'wp_nav_menu_items', 'custom_menu_item', 10, 2 );
function custom_menu_item ( $items, $args ) {

    $url = ThemexUser::$data['user']['profile_url'];
    if ( is_user_logged_in() && $args->theme_location == 'main_menu' ) {
        $items .= '
My Profile
';
    }
    return $items;

}

Some visuals, just to be clear:
Normal Menu (Added link appears)
Mobile Menu (Added link is missing)
I want the "My Profile" link to show in the mobile menu as well. The theme in use is LoveStory By Themex (Version 1.15) which has been completely redesigned by a custom child theme.
Any guidance would be appreciated.


text:
Q: Dynamic Linq Query Help? How do you write a dynamic Linq query for the following simple search criteria?
1) StudentNumber
2) LastName
3) LastName and FirstName
//if (!String.IsNullOrEmpty(StudentNumber))
var results  = (from s in Students
                where s.StudentNumber == 1001
                select s
               );

//else if (!String.IsNullOrEmpty(LastName) & (String.IsNullOrEmpty(FirstName))

var results  = (from s in Students
                where s.LastName == "Tucker"
                select s
               );

//else if (!String.IsNullOrEmpty(LastName) & (!String.IsNullOrEmpty(FirstName))
var results  = (from s in Students
                where s.LastName == "Tucker" && s.FirstName == "Ron"
                select s
               );

A: You need to declare your results variable outside of any individual query. This will allow you append different filters based upon your varying criteria, and append as many filters as you need. An example:
var results = Students.AsEnumerable(); // use .AsQueryable() for EF or Linq-to-SQL

if (!string.IsNullorEmpty(StudentNumber))
{
    results = results.Where(s => s.StudentNumber.Equals(StudentNumber));
}
else if (!string.IsNullOrEmpty(LastName))
{
    results = results.Where(s => s.LastName.Equals(LastName));

    if (!string.IsNullOrEmpty(FirstName))
    {
         results = results.Where(s => s.FirstName.Equals(FirstName));
         // filter is in addition to predicate against LastName
    }
}

// results can be used here

If dealing with Linq-to-Entities or -Sql, type the initial query with Students.AsQueryable(); so that the filtering happens at the database rather than inside the application.

Is there a way I can construct the WHERE clause first and use it in a
  Linq query without if...else

If you want to build the entire where before the first step of the query, it's the same logic. You are conditionally building the predicate, so you will have some sort of if/else involved. However, to build the entire predicate first, you could build against a Func<Student, bool> for Linq to Objects.
Func<Student, bool> predicate;
if (!string.IsNullOrEmpty(StudentNumber))
{
    predicate = s => s.StudentNumber.Equals(StudentNumber);
}
else if (!string.IsNullOrEmpty(LastName))
{
    predicate = s => s.LastName.Equals(LastName);

    if (!string.IsNullOrEmpty(FirstName))
    {
        Func<Student, bool> p = predicate;
        predicate = s => p(s) && s.FirstName.Equals(FirstName);
    }
}
else
{
    predicate = s => true;
}

var query = Students.Where(predicate);

You'll notice it's the exact same if/else structure. You could collapse that down into a complicated conditional expression
Func<Student, bool> predicate;
predicate = s =>
    !string.IsNullOrEmpty(StudentNumber)
    ? s.StudentNumber.Equals(StudentNumber)
    : !string.IsNullOrEmpty(LastName)
        ? !string.IsNullOrEmpty(FirstName)
            ? s.LastName.Equals(LastName) && s.FirstName.Equals(FirstName)
            : s.LastName.Equals(LastName)
        : true;

var query = Students.Where(predicate);

But I find that pretty well difficult to follow, certainly as compared to the longer if/else. This predicate is also bigger than the one we build via the if/else, because this one contains all the logic, it's not just the logic we conditionally added.


text:
Q: Equivalent of c# class virtual member in TypeScript So in C# when I've been creating model classes and lazy loading things, I do something like this:
public int? User_ID { get; set; }
public int? Dept_ID { get; set; }

Then a little farther down in my class I pop in my virtuals like so:
public virtual User User {get; set;}
public virtual Department Dept {get; set;}

How would I do this in Typescript? Something like this?:
User_ID: number;
Dept_ID: number;
User: User;
Dept: Department;

I don't think interfaces is what I want/need...but then again protected doesn't seem correct either.  Something tells me I'm missing an obvious answer here.

A: The following applies equally to TypeScript and JavaScript:
There is no equivalent.
Every member access in JavaScript is subject to dynamic dispatch by definition. This is because member access in JavaScript is, morally, a key lookup in a hash table.
An object may declare a member with the same key as one it inherits via the prototype chain and thereby shadow the inherited member but this is not the same as virtualness, a concept not present in the language.

A: All methods in Javascript and Typescript are technically virtual since there's nothing preventing you from being able to override any method.

A: Yes there are ..
//non-abstract or abstract class
class A {

    // The virtual method
    protected virtualStuff1?():void;

    public Stuff2(){
        //Calling overridden child method by parent if implemented
        this.virtualStuff1 && this.virtualStuff1();
        alert("Baseclass Stuff2");
    }
}

//class B implementing virtual method
class B extends A{

    // overriding virtual method
    public virtualStuff1()
    {
        alert("Class B virtualStuff1");
    }
}

//Class C not implementing virtual method
class C extends A{

}

var b1 = new B();
var c1= new C();
b1.Stuff2();
b1.virtualStuff1();
c1.Stuff2();

A: I achieved this using an arrow function as a property of the class (note this was in ts, but if you're handy at modern js it should work):
class baseClass {
    doSomething = () => {};
}

class derivedClass extends baseClass {
    constructor() {
        this.doSomeThing = () => { console.log('something'); };
    }
}


text:
Q: flutter error when I do future http.get and return body value the console log dont stop the log not stop

I run this code and the console log is like this

how can I fix it?
I want console log just one time
the getCrewInfo() called here

A: You should check the code again, which code that called the CrewInfoAPI? if you havent solved the problem, you may have to update more details on the question.


text:
Q: pandas index_col="datetime" makes df['datetime'] unavailable The title says it all.
The following bit of pseudo-code returns the following error:
df = pd.read_sql(query, conn, parse_dates=["datetime"],
                             index_col="datetime")
df['datetime']

I get :
Exception in thread Thread-1:
 Traceback (most recent call last):
   File "C:\Users\admin\.virtualenvs\EnkiForex-ey09TNOL\lib\site-packages\pandas\core\indexes\base.py", line 2656, in get_loc
     return self._engine.get_loc(key)
   File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
   File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
   File "pandas\_libs\hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
   File "pandas\_libs\hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
 KeyError: 'datetime'

Am I misunderstanding what's going on by indexing the datetime col? I can access all the other columns normally though.

A: An index is not a column. Think of the index as labels for the rows of the DataFrame. index_col='datetime' makes the datetime column (in the csv) the index of df. To access the index, use df.index.

A: import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(d)

time = pd.date_range(end='4/5/2018',periods=2)
df.index = time
df.index

the end is DatetimeIndex(['2018-04-04', '2018-04-05'], dtype='datetime64[ns]', freq='D')
just use df.index can get the information of the index_col