text:
Q: Is there a good PDF to XHTML strict converter It is basically all in the title, I need to take a bunch of large  PDFs and have them in XHTML 1.0 strict, close is good enough, then I can clean it up.
Thanks

A: This is a complex request, because it depends on the PDF itself (and how it was created) whether this can be done or not.
As a first attempt, I would try to use adobe's own online PDF to HTML convertor
http://www.adobe.com/products/acrobat/access_onlinetools.html
and then try to fix up the HTML after the fact with something like tidy
http://tidy.sourceforge.net/
If the PDFs were creating by scanning images in then there may be no text associated with them at all - then the best you can do is either cut apart the pages and turn them into JPG documents, or use some sort of OCR software on the PDF itself.
I warn you that even if the PDFs were created by hand and thus have text information in them, there are likely to be a lot of mistakes in the conversion process that will have to be fixed by hand. I work on a product that basically does this process for corporate annual reports/etc and we ultimately settled on cutting up the pages into JPG/GIF images and HTMLing that - as the other processes we tried introduced too many error and it was too labor intensive to fix them all.


text:
Q: Web.config in a virtual directory... permission denied on root directory web.config? Under IIS 6 Win23k. At the root directory of a website there is a web.config (I think the root website is actually a sharepoint site). I create a virtual directory and plunk in my asp.net application and it's web.config. My application runs as a specific user id, and one that doesn't happen to have rights to the root directory's web.config.
Turns ought my virtual directory's web.config has an error in it (a reference was misspelled). When I access the virtual directory through the browser I was getting an ASP.NET error about "permission denied".
Change the permission on  the parent web.config... poof I now get the correct error. Delete the parent web.config... poof I now get the correct error.
What's going on here? Why does my virtual directory need/want the root directory's web.config? How can I prevent my virtual directory from doing this?
Edit: This is sharepoint being a bad citizen. It sets the permissions on web.confg to be only Administrators and System with full control and STS_WPG as read only. Note the first time sharepoint has messed with a webserver I'm sure.
Thanks!
Rob

A: afaik, virtual directories "inherits" the root config. You can disable that behaviour:
http://dotnetslackers.com/Security/re-55457_Stopping_ASP_NET_web_config_inheritance.aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to highlight correct word on searchDelegate? I highlighted the word, but not the correct word.
In my BuilderSuggection, I added like this code,

 title: RichText(
          text: TextSpan(
              text: suggestList[index].d.substring(0, query.length),
              style: TextStyle(
                  color: Colors.black, fontWeight: FontWeight.bold),
              children: [
            TextSpan(
                text: suggestList[index].d.substring(query.length),
                style: TextStyle(color: Colors.grey))
          ])),

A: Based on @George's answer there is a similar function with the only difference that the query is first split by spaces and each separate word is then highlighted. It took me a while to make it work properly so why not to share:
List<TextSpan> highlightOccurrences(String source, String query) {
  if (query == null || query.isEmpty) {
    return [TextSpan(text: source)];
  }

  var matches = <Match>[];
  for (final token in query.trim().toLowerCase().split(' ')) {
    matches.addAll(token.allMatches(source.toLowerCase()));
  }

  if (matches.isEmpty) {
    return [TextSpan(text: source)];
  }
  matches.sort((a, b) => a.start.compareTo(b.start));

  int lastMatchEnd = 0;
  final List<TextSpan> children = [];
  for (final match in matches) {
    if (match.end <= lastMatchEnd) {
      // already matched -> ignore
    } else if (match.start <= lastMatchEnd) {
      children.add(TextSpan(
        text: source.substring(lastMatchEnd, match.end),
        style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
      ));
    } else if (match.start > lastMatchEnd) {
      children.add(TextSpan(
        text: source.substring(lastMatchEnd, match.start),
      ));

      children.add(TextSpan(
        text: source.substring(match.start, match.end),
        style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
      ));
    }

    if (lastMatchEnd < match.end) {
      lastMatchEnd = match.end;
    }
  }

  if (lastMatchEnd < source.length) {
    children.add(TextSpan(
      text: source.substring(lastMatchEnd, source.length),
    ));
  }

  return children;
}

The usage is the same as with @George's answer:
RichText(
  text: TextSpan(
    children: highlightOccurrences(suggestList[index].d, query),
    style: TextStyle(color: Colors.grey),
  ),
),

A: I wrote a quick function that returns a List of TextSpan.
Function matches the query string against the source string, enumerating the matches one by one, cutting the source string into pieces: before the match, after the match, and the match itself - making it bold.
It is intended to be used in a RichText widget.
List<TextSpan> highlightOccurrences(String source, String query) {
  if (query.isEmpty || !source.toLowerCase().contains(query.toLowerCase())) {
    return [ TextSpan(text: source) ];
  }
  final matches = query.toLowerCase().allMatches(source.toLowerCase());

  int lastMatchEnd = 0;

  final List<TextSpan> children = [];
  for (var i = 0; i < matches.length; i++) {
    final match = matches.elementAt(i);

    if (match.start != lastMatchEnd) {
      children.add(TextSpan(
        text: source.substring(lastMatchEnd, match.start),
      ));
    }

    children.add(TextSpan(
      text: source.substring(match.start, match.end),
      style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
    ));

    if (i == matches.length - 1 && match.end != source.length) {
      children.add(TextSpan(
        text: source.substring(match.end, source.length),
      ));
    }

    lastMatchEnd = match.end;
  }
  return children;
}

Example based on your code:
RichText(
  text: TextSpan(
    children: highlightOccurrences(suggestList[index].d, query),
    style: TextStyle(color: Colors.grey),
  ),
),

Let me know if this helped.

A: Sorry for my very late answer, but I wanted to give also my support for this kind of "problem".
I wanted to find a different way, and I figured it out without using if statements, which is pretty nice looking, and maybe even easier to manage it;
I considered the "suggestion string" as divided in the worst case scenario of 3 substrings: 2 strings on the side, and one in the center. The center one, as you can imagine is the "bold" one. That's it!
If there's no correspondence, obviously there will be no result shown in suggestion box.
I directly copy&pasted the same code I used.
return ListView.builder(
        itemCount: _posts.length,
        itemBuilder: (context, index) {
          int startIndex = _posts[index].title.toLowerCase().indexOf(query.toLowerCase());
          return ListTile(
            title: query.isEmpty
                ? Text(_posts[index].title)
                : RichText(
                    text: TextSpan(
                    text: _posts[index].title.substring(0, startIndex),
                    style: TextStyle(color: Colors.grey),
                    children: [
                      TextSpan(
                        text: _posts[index]
                            .title
                            .substring(startIndex, startIndex + query.length),
                        style: TextStyle(
                            fontWeight: FontWeight.bold, color: Colors.black),
                      ),
                      TextSpan(
                        text: _posts[index]
                            .title
                            .substring(startIndex + query.length),
                        style: TextStyle(color: Colors.grey),
                      )
                    ],
                  )),
            subtitle: Text(_posts[index].date),
          );

A:         //hight light occurrentces
    List<TextSpan> _highlightOccurrences(String text, String query) {
      final List<TextSpan> spans = [];
      final String lowercaseText = text.toLowerCase();
      final String lowercaseQuery = query.toLowerCase();

      int lastIndex = 0;
      int index = lowercaseText.indexOf(lowercaseQuery);

      while (index != -1) {
        spans.add(TextSpan(text: text.substring(lastIndex, index)));
        spans.add(TextSpan(text: text.substring(index, index + query.length), style: const TextStyle(fontWeight: FontWeight.bold)));
        lastIndex = index + query.length;
        index = lowercaseText.indexOf(lowercaseQuery, lastIndex);
      }

      spans.add(TextSpan(text: text.substring(lastIndex, text.length)));

      return spans;
    }

using:

    @override
      Widget buildSuggestions(BuildContext context) {
        final suggestions = lstString.where((name) {
          return name.toLowerCase().contains(query.toLowerCase());
        }).toList();

        //limit suggest
        const int limitSuggest = 5;
        if (suggestions.length > limitSuggest) {
          suggestions.removeRange(limitSuggest, suggestions.length);
        }

        return ListView.builder(
          itemCount: suggestions.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: query.isEmpty
                  ? Text(
                      suggestions.elementAt(index),
                    )
                  : RichText(
                      text: TextSpan(
                          children: _highlightOccurrences(suggestions[index], query), style: TextStyle(color: Theme.of(context).colorScheme.onSurface)),
                    ),
              onTap: () => query = suggestions.elementAt(index),
            );
          },
        );

  }


text:
Q: Spring Security is not working - HTTP Status 405 - Request method 'POST' not supported I'am having a problem with Spring Security which now bang my head. When i try to submit a login then this error message is displayed: "HTTP Status 405 - Request method 'POST' not supported". I have read a ton of articles related to this issue but still not lucky.
Security Config:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = { "vn.com.tma.hrm.security" })

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Autowired
DataSource dataSource;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/", "/assets/**").permitAll()
            .antMatchers("/users/**").hasAuthority("ADMIN")
            .anyRequest().fullyAuthenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .usernameParameter("email")
            .permitAll()
            .and()
        .logout()
            .logoutUrl("/logout")
            .deleteCookies("remember-me")
            .logoutSuccessUrl("/")
            .permitAll()
            .and()
        .rememberMe()
            .and()
        .csrf();
}

@Bean
public PersistentTokenRepository persistentTokenRepository() {
    JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
    db.setDataSource(dataSource);
    return db;
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(new BCryptPasswordEncoder());

}
}

application context:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

  <context:annotation-config/>
  <context:component-scan base-package="vn.com.tma.hrm"></context:component-scan>
  <mvc:annotation-driven />
  <mvc:interceptors>
    <bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
      <property name="cacheSeconds" value="0"/>
      <property name="useExpiresHeader" value="true"/>
      <property name="useCacheControlHeader" value="true"/>
      <property name="useCacheControlNoStore" value="true"/>
    </bean>
  </mvc:interceptors>

  <mvc:default-servlet-handler/>

  <mvc:view-controller path="/" view-name="home1"/>

  <mvc:resources mapping="/libs/**" location="/libs/"></mvc:resources>
  <mvc:resources mapping="/assets/**" location="/assets/"></mvc:resources>
  <mvc:resources mapping="/app/**" location="/app/"></mvc:resources>

  <jpa:repositories base-package="vn.com.tma.hrm.repository"
                    entity-manager-factory-ref="entityManagerFactoryBean"
                    transaction-manager-ref="txManager"/>

  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="classpath:application.properties" />
  </bean>
  <bean id="hrmDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${db.driver}" />
    <property name="url" value="${db.url}" />
    <property name="username" value="${db.username}" />
    <property name="password" value="${db.password}" />
  </bean>

  <bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="hrmDataSource" />
    <property name="packagesToScan" value="${entitymanager.packages.to.scan}" />
    <property name="jpaVendorAdapter">
      <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
      <props>
        <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
        <prop key="hibernate.dialect">${hibernate.dialect}</prop>
        <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
        <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
      </props>
    </property>
  </bean>

  <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactoryBean" />
  </bean>
  <tx:annotation-driven />

  <bean id="baseUri" class="org.springframework.data.rest.webmvc.BaseUri">
    <constructor-arg value="/api" />
  </bean>

</beans>

Dispatcher Servlet

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
  </bean>
</beans>

Login Form

<c:url value="/login" var="loginUrl"/>
<form name="myForm" action="${loginUrl}" method="post">
 <%-- <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> --%>
 <fieldset>

    <input type="text" class="form-control" placeholder="Username"
        name="email" id="email" ng-model="email" ng-trim="true" required="true" ng-pattern="/^([a-zA-Z0-9]+)$/"
      ng-minlength="3" ng-maxlength="10"/>

    <input type="password" class="form-control" placeholder="Password" name="password" id="password"
        ng-model="password" required="true" ng-minlength="3" ng-maxlength="10" ng-trim="true" />

   <c:if test="${loginView == null}">

     <input type="checkbox" class="ace" />
      Remember Me

   </c:if>
   <button type="submit" class="width-35 pull-right btn btn-sm btn-primary">

    Login
   </button>

 </fieldset>
</form>

Please help me on this!
Updated
Adding web.xml file:

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0">
  <display-name>Archetype Created Web Application</display-name>

  <welcome-file-list>
    <welcome-file>index</welcome-file>
  </welcome-file-list>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


text:
Q: Better way of reading a huge file using PHP which does not make my server hang I am trying to read a huge file (6 million lines, 80mb) using
this syntax in PHP :
readfile("output.data");

I have to read this file and display only few lines of data from this huge file, now my problem is my WAMP server is hanged whenever I include this line
(readfile("output.data"); ) in my php code,

A: Ever tried jQuery ajax?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    $( document ).ready( function ()
    {
        $.ajax( {
            url: "myUrl.php",
            type: "GET",
            success: function ( R )
            {
                $( "#IDselector" ).html( R );
            },
            beforeSend: function ()
            {
                $( "#IDselector" ).html( "Loading" );
            }
        } )
    } );
</script>

In this, your myUrl.php file would contain the logic and printing for the reading of the file and the AJAX would handle what to do when complete. (All data in the myUrl.php that you want to see MUST be printed as you would normally for the user to see))
Worth a read into to allow the page to load fully then read in extra data
Also, look into fopen, fread etc. They are useful and better for reading files IMO


text:
Q: ZF2 Dependency Injection onto Controller objects without the Service Locator I have been doing a read up on ZF2 Service Locator component and could say I understand how its being used. I have, however, a question which I think its silly but it wouldn't hurt to ask.
I want to have a namespace inside my Module called Component where I can put generic code in like say FunctionsComponent.php, MailerComponent.php or ExcelComponent.php. This would allow me to do some stuff inside my controllers.
What I would like to tryout is to have an ability to have controllers define the components they are interested to use (see below):
class SalesController extends AbstractController
{
  protected $components = ['Excel'];

  //In some action
  public function exportAction()
  {
    $data = ['data to be exported'];
    /**
      $data : data to be exported
      boolean : Whether to force download or save the file in a dedicated location
    */
    $this->Excel->export($data, true);
  }
}

The idea is to create a ComponentCollection that perhaps implements the FactoryInterface or ServiceLocatorInterface and then let it check each controller when the MvcEvent has been triggered inside my Module class and have the ComponentCollection inject all the controller component and make them accessible without using the service locator as shown below:
$excel = $sm->get('Application\Component\Excel');

I am well aware that this may seem like a daunting ask but I feel like the best way to learn a framework among other things is to play around with it and try to do the unimaginable.

A: You should create a BaseController somewhere and then extend all your Controllers from BaseController. Then you can inject your dependencies in your BaseController and use anywhere in kids. For example, I am doing this in my Controller to set head title:
<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class BaseController extends AbstractActionController
{

    /**
     * Sets the head title for every page
     *
     * @param string $title
     */
    public function setHeadTitle($title)
    {
        $viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
        // Getting the headTitle helper from the view helper manager
        $headTitleHelper = $viewHelperManager->get('headTitle');

        // Setting a separator string for segments
        $headTitleHelper->setSeparator(' - ');

        // Setting the action, controller, module and site name as title segments
        $siteName = 'Ribbon Cutters';
        $translator = $this->getServiceLocator()->get('translator');
        $title = $translator->translate($title);
        $headTitleHelper->append(ucfirst($title));
        $headTitleHelper->append($siteName);
    }

}

Instead of defining methods, you can define properties.
public $headTitleHelper

and assign it in constructor of BaseController
$this->headTitleHelper = $this->getServiceLocator()->get('ViewHelperManager')->get('headTitle');

Now you can use $this->headTitleHelper in child controllers.
And then
<?php

namespace Application\Controller;

use Zend\View\Model\ViewModel;
use Application\Controller\BaseController;

class IndexController extends BaseController
{

    /**
     * Property for setting entity manager of doctrine
     */
    protected $em;

    /**
     * landing page
     *
     * @return ViewModel
     */
    public function indexAction()
    {

        $this->setHeadTitle('Welcome');  // Welcome - Ribbon Cutters

        $viewModel = new ViewModel();

        return $viewModel;
    }

    /**
     * Sets and gives Doctrine Entity Manager
     *
     * @return Doctrine Entity Manager
     */
    protected function getEntityManager()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
        }
        return $this->em;
    }
}

I think this can help you.


text:
Q: Showing ProgressDialog only once in a recursive AsyncTask In the Java code I have executed an AsyncTask class and with the returned result I have done a recursive call to itself in the onPostexecute method. Example:
MainActivity.java
public void button_clicked(){
  UploadAsync send_data = new UploadAsync(MainActivity.this);
  send_data.execute("send first data", user_data, file_path);
}

UploadAsync.java
@Override
protected String doInBackground(String... params) {
  String task = params[0];
  if(task.equals("send first data"){
    String user_data = params[1];
    String file_path = params[2];

    //send in the user_data to a php file

  }else if(task.equals("send file"){
    String file_path = params[1];

    //send the file_path to another php file

  }
}

@Override
protected void onPreExecute() {
 ProgressDialog pd = ProgressDialog.show(context, "Sending", "Please wait");
}

@Override
protected void onPostExecute(String result) {
  if(result.equals("data sent"){
    UploadAsync send_data = new UploadAsync(context);
    send_data.execute("send file", file_path);
  }else{
    //show error
  }

  pd.dismiss();
}

The code above is only an example made. Now the thing is, implementing this example will run the progress dialog twice. I have tried many ways to only show the progress dialog once while the AsyncTask is sending the user data and the file path but I'm not succeeding. Is there any suggestions on how to implement this correctly?

A: Can't you call pd.dismiss() and dismiss ProgressDialog for the current UploadAsync before executing new UploadAsync?

A: In onPostExecute first, dismiss the dialog and then start new asynctask like this:
@Override
protected void onPostExecute(String result) {

  pd.dismiss();

  if(result.equals("data sent"){
    UploadAsync send_data = new UploadAsync(context);
    send_data.execute("send file", file_path);
  }else{
    //show error
  }

}

I hope this will help you.

A: Let ProgressDialog as global data .
private ProgressDialog pd;

@Override
protected void onPreExecute() {
    // show the ProgressDialog
    if (pd == null) {
        pd = ProgressDialog.show(context, "Sending", "Please wait");
    }
}

@Override
protected void onPostExecute(String result) {
    if (result.equals("data sent") {
        UploadAsync send_data = new UploadAsync(context);
        send_data.execute("send file", file_path);
    }else{
        //show error
    }
    // edited here ,make the ProgressDialog dismiss
    if (pd.isShowing() && pd != null) {
        pd.dismiss();
        pd = null;
    }
}

A: In that case use callback mechanism between the async task and the caller(here, MainActivity).
Implement as I explained below.

*

*Define an interface with showProgressDiaglog() and
DismissProgressDialog() methods.

*MainActivity implements this interface and implements the two
methods to show and dismiss progress dialog respectively.

*Define setter method in your AsyncTask class and call this setter
method from the MainActivity by passing this(this refers to
MainActivity) after creating the AsyncTask instance and before
calling execute method. store the passed interface implementation in
the AsyncTask class as an instance variable.

*Modify AsyncTask constructor to pass the task type instead of passing
in the execute method and store this task type in the AsyncTask as an
instance variable.

*Now from within the AsyncTask constructor, in onPreExecute()
method, call showProgressDialog() method based on the task type.
and in onPostEecute() method call dismissProgressDialog()
depending on the task type.


text: Q: How to find start/end cluster for a file In O&O defrag, after doing analysiz, we can see what file in each cluster. What if I am looking for a certain file, is there any tool to know in which cluster that file are? Thanks!


text:
Q: Support US Government for Office 365 Management API When I ingest data through Office 365 Management API (here), I use login.windows.net as authentication endpoint, and manage.office.com as API request endpoint.
But for Government region, it doesn't work cause for different region, the endpoint is different. However, I didn't find any useful information from Microsoft's official documentation.
Please help me if anyone had successfully connected to Government region. Thanks a lot.


text:
Q: How to evaluate $\int_0^1\int_0^1 \frac{1}{1-xy} \, dy \, dx$ to prove $\sum_{n=1}^{\infty} \frac{1}{n^2}=\frac{\pi^2}{6}$. I've read somewhere on this site that if you consider:
$$\int_0^1 \int_0^1 \frac{1}{1-xy} \,dy\,dx$$
Then using the power series, we have this is equal to $\sum_{n=1}^{\infty} \frac{1}{n^2}$ which I decided to try and was able to show.
Apparently we can show this is equal to $\frac{\pi^2}{6}$, and using what little I know about double integrals from a few khan academy videos (I haven't taken multivariable  calculus yet), I tried to evaluate this double integral by techniques of single variable calculus $u=xy$..and I got this:
$$-\int_{0}^{1} \frac{\ln (1-x)}{x}dx$$
The usual way I would evaluate this is with a Taylor series, but that just that just leads us in circles.
So I want to know how can I evaluate this, so we can prove $\sum_{n=1}^{\infty} \frac{1}{n^2}=\frac{\pi^2}{6}$.

A: Here, we present an approach the relies on integration methodologies only, including transformation of coordinates.  To that end we proceed.
We can transform coordinates by setting $x=s+t$ and $y=s-t$.  Then, $dx\,dy\to 2\,ds\,dt$ and the transformed integral domain is the square-shaped region with vertices in the $s-t$ plane at $(0,0)$, $(1/2,1/2)$, $(1/2,-1/2)$, and $(1,0)$.  Then, we can write
$$\begin{align}
\int_0^1\int_0^1 \frac{1}{1-xy}\,dx\,dy&=\int_0^{1/2}\int_{-s}^{s}\frac{2}{(1-s^2)+t^2}\,dt\,ds+\int_{1/2}^{1}\int_{s-1}^{1-s}\frac{2}{(1-s^2)+t^2}\,dt\,ds\\\\
&=\int_0^{1/2}\frac{4}{\sqrt{1-s^2}}\arctan\left(\frac{s}{\sqrt{1-s^2}}\right)\,ds\\\\&+\int_{1/2}^{1}\frac{4}{\sqrt{1-s^2}}\arctan\left(\sqrt{\frac{1-s}{1+s}}\right)\,ds\\\\
&=4\int_0^{1/2}\frac{\arcsin(s)}{\sqrt{1-s^2}}\,ds+4\int_{1/2}^1\frac{\arccos(s)}{2\sqrt{1-s^2}}\,ds\\\\
&=2\arcsin^2(1/2)+\arccos^2(1/2)\\\\
&=2\left(\frac{\pi}{6}\right)^2+\left(\frac{\pi}{3}\right)^2\\\\
&=\frac{\pi^2}{6}
\end{align}$$
as expected!


text:
Q: Problem with validation of SOAP request with Zeep (python) I have problems to get SOAP request through Zeep, I get a (client) validation error... I have also tested with SoapUI and that does NOT give me the same validation error...
The specification below is from the server... Based on that specification, the OrderStatus and SynchStatus are needed to perform the request.
<soapenv:Envelope xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/ xmlns:web="WebServiceProvider">
   <soapenv:Header/>
   <soapenv:Body>
      <web:Order_Get>
         <!--Optional:-->
         <web:orderOptions>
            <web:FromDate>?</web:FromDate>
            <web:ToDate>?</web:ToDate>
            <web:OrderStatus>?</web:OrderStatus>
            <web:SynchStatus>?</web:SynchStatus>
            <!--Optional:-->
            <web:OrderNumber>?</web:OrderNumber>
            <web:FromOrderNumberToLastRecieved>?</web:FromOrderNumberToLastRecieved>
            <web:PaymentStatus>?</web:PaymentStatus>
         </web:orderOptions>
      </web:Order_Get>
   </soapenv:Body>
</soapenv:Envelope>

However, executing this from the SoapUI without OrderStatus and SynchStatus will give me a list of all the orders for the specified dates:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="WebServiceProvider">
   <soapenv:Header/>
   <soapenv:Body>
      <web:Order_Get>
         <web:orderOptions>
            <web:FromDate>2021-03-30</web:FromDate>
            <web:ToDate>2021-03-31</web:ToDate>
         </web:orderOptions>
      </web:Order_Get>
   </soapenv:Body>
</soapenv:Envelope>

I want to do the same with Zeep (https://github.com/mvantellingen/python-zeep) but the client validation fails...
I initiate the request with the following code:
api_url = 'https://abc.se/Webservice20/v3.0/webservice.asmx?WSDL'
session.auth = HTTPDigestAuth(username, password)
api = Client(api_url, transport=Transport(session=session))

And then I try to execute the following request:
order_options = {
  'FromDate': '2021-03-30',
  'ToDate': '2021-03-31',
}
orders = api.service.Order_Get(orderOptions=order_options)

This will result in the following error:
zeep.exceptions.ValidationError: Missing element OrderStatus (Order_Get.orderOptions.OrderStatus)

If I add OrderStatus to the request, I will get a validation error saying that SynchStatus is missing. When that has been added as well, the request is sent to the server.
I.e. it seems like the zeep client is more strict with regards to validating the data in the request than what the server is... Is there a way to force the client to skip this validation?
Many thanks in advance!

A: Searched a bit more and found a workaround in this post: Getting zeep.exceptions.ValidationError: Missing element for method that worked with suds
So the solution in my case looks like this:
from zeep import xsd
...

order_options = {
  'FromDate': '2021-03-30',
  'ToDate': '2021-03-31',
  'OrderStatus': xsd.SkipValue,
  'SynchStatus': xsd.SkipValue,
}

response = api.service.Order_Get(orderOptions=order_options)

This will block zeep from doing client side validation of the parameters OrderStatus and SynchStatus.

A:
it seems like the zeep client is more strict with regards to validating the data in the request than what the server is...

Looks like it.
Looking at the request SoapUI generates based on the WSDL, the two fields you mention are mandatory:
 <web:orderOptions>
    <web:FromDate>?</web:FromDate>
    <web:ToDate>?</web:ToDate>
    <web:OrderStatus>?</web:OrderStatus>
    <web:SynchStatus>?</web:SynchStatus>
    <!--Optional:-->
    <web:OrderNumber>?</web:OrderNumber>
    <web:FromOrderNumberToLastRecieved>?</web:FromOrderNumberToLastRecieved>
    <web:PaymentStatus>?</web:PaymentStatus>
 </web:orderOptions>

So the error that the zeep client displays is correct. Zeep inspects the WSDL and generates the corresponding code to use the types in the contract. Your WSDL contract says that OrderStatus and SynchStatus are mandatory. The fact that the server doesn't validate them shows a problem: the web service isn't respecting it's own documented contract
The WSDL and the behavior of the web service should be the same. I suggest you contact the web service owners and ask about this behavior. It might be a validation missing on the server and what you get is just some side effect of that, or the behavior is intentional but someone forgot to update the WSDL to say that you can also make the call without those parameters.
Meanwhile, the workaround is very simple. Download the WSDL, change it to make the two fields optional, then feed this changed WSDL to zeep for it to generate the code, instead of using the original WSDL. You should however clarify this with the web service provider. If it's indeed a neglect of someone, this might be spotted at some point and fixed, making your workaround call fail a server validation because of the missing fields.


text:
Q: TypeError: Cannot read property 'id' of undefined in Jest My test case is failing, saying  TypeError: Cannot read property 'id' of undefined. This is what I am doing in code  -
act(() => {
        wrapper
            .find(ComponentA)
            .first()
            .find(RadioButton)
            .first()
            .props()
            .onChange('first', {id:'first' , isChecked: true });
    });

in this code I am getting error, says id is undefined. When I am consoling the code like -
console.log(wrapper
        .find(ComponentA)
        .first()
        .find(RadioButton)
        .first()
        .props(), "console")

Then I am getting following output -
{
        id: 'first',
        isChecked: true,
        onChange: [Function: onChange],
        radioFontSize: '1.43rem',
        labelFontSize: '1rem',
        radioColor: 'rgb(9, 114, 142)',
        labelColor: 'rgb(48, 46, 44)'
      } console

If I am getting id in console then why it is saying undefined id ? I have written this test case in jest. Can someone help me in that ?


text:
Q: I am getting an error in Kapt Debug Kotlin. I have update versions of dependencies in gradle file. still facing this issue My app was running smoothly but I am getting this error now.I am getting an error in Kapt Debug Kotlin. I have update versions of dependencies in gradle file. still facing this issue. How it can be resolved? I saw somewhere to see your room database , dao and data class. still not able to figure out what is the issue.

The error is showing this file

ROOM DATABASE
@Database(entities = [Transaction::class], version = 1, exportSchema = false)
abstract class MoneyDatabase : RoomDatabase(){

    abstract fun transactionListDao():transactionDetailDao
    companion object {
        // Singleton prevents multiple instances of database opening at the
        // same time.
        @Volatile
        private var INSTANCE: MoneyDatabase? = null

        fun getDatabase(context: Context): MoneyDatabase {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    MoneyDatabase::class.java,
                    "transaction_database"
                ).build()
                INSTANCE = instance
                // return instance
                instance
            }
        }
    }
}

DAO
@Dao
interface transactionDetailDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insert(transaction : Transaction)

    @Delete
    suspend fun delete(transaction : Transaction)

    @Update
    suspend fun update(transaction: Transaction)

    @Query("SELECT * FROM transaction_table ORDER BY id ASC")
    fun getalltransaction(): LiveData<List<Transaction>>
}

DATA CLASS
enum class Transaction_type(){
    Cash , debit , Credit
}
enum class Type(){
    Income, Expense
}
@Entity(tableName = "transaction_table")
data class Transaction(
    val name : String,
    val amount : Float,
    val day : Int,
    val month : Int,
    val year : Int,
    val comment: String,
    val datePicker: String,
    val transaction_type : String,
    val category : String,
    val recurring_from : String,
    val recurring_to : String
){
    @PrimaryKey(autoGenerate = true) var id :Long=0
}

A: I believe that your issue is due to the use of an incorrect class being inadvertently used, a likely culprit being Transaction as that it also a Room class
Perhaps in transactionDetailDao (although it might be elsewhere)
See if you have import androidx.room.Transaction? (or any other imports with Transaction)?
If so delete or comment out the import
As an example with, and :-

And with the import commented out :-

Imported from github, had a play issue definitely appears to be with co-routines. commented out suspends in the Dao :-
@Dao
interface transactionDetailDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insert(transaction : Transaction)

    @Delete
    suspend fun delete(transaction : Transaction)

    @Update
    suspend fun update(transaction: Transaction)

    @Query("SELECT * FROM transaction_table ORDER BY id ASC")
    fun getalltransaction(): LiveData<List<Transaction>>
}

Compiled ok and ran and had a play e.g. :-

A: The error is resolved. I was using the kotlin version 1.6.0. I reduced it to 1.4.32. As far as I understood, above(latest) version of Kotlin along with Room and coroutines doesn't work well.


text:
Q: Multidimensional array in Java like PHP I want to create an multidimensional array in Java, like the PHP one shown below. I want to create an exact same array. Is it possible?
Array
(
    [0] => Array
        (
            [name] => sagar
            [company] => Visa
        )

    [1] => Array
        (
            [name] => shloka
            [company] => Doctor
        )

    [2] => Array
        (
            [name] => sanket
            [company] => zon
        )

    [3] => Array
        (
            [name] => kamlesh
            [company] => nsc
        )

    [4] => Array
        (
            [name] => siddhi
            [company] => KES
        )

    [5] => Array
        (
            [name] => sanket
            [company] => zon
        )

    [6] => Array
        (
            [name] => bunty
            [company] => India Bull
        )

    [7] => Array
        (
            [name] => siddhi
            [company] => KES
        )

)

A: The "Way of the Java" would be to make a POJO class to store that info, like this:
class UserInfo {
    private String name;
    private String company;

    public UserInfo(String name, String company) {
        this.name = name;
        this.company = company;
    }

    public String getName() {
        return name;
    }

    public String getCompany() {
        return company;
    }
}

UserInfo[] users = {
    new UserInfo("sagar", "visa"),
    new UserInfo("shloka", "Doctor"),
    ....
};

However, if you want it exactly the same way you did in PHP, there you go:
public static Map<String,String> createUser(String name, String company) {
    final Map<String,String> result = new HashMap<String,String>();
    result.put("name",name);
    result.put("company",company);
    return result;
}

List<Map<String,String>> users = new ArrayList<Map<String,String>>();
users.add(createUser("sagar","visa"));
users.add(createUser("shloka","Doctor"));
....

Added:
For the sake of completeness of the answer, here's another way using instance initializers. It may look prettier that the other solutions in some cases, but basically it has one flaw: it uses unrequired permgen space. Not much of it, but it is still unrequired:
List<Map<String,String>> result = new ArrayList<Map<String,String>>() {{
    add(new HashMap<String,String>() {{
        put("name", "someName");
        put("company", "someCompany");
    }});
    add(new HashMap<String,String>() {{
        put("name", "someName1");
        put("company", "someCompany1");
    }});
}};

Basically this solution is overriding an ArrayList with a new class (that's why a permgen is used) which has an instance initializer with addition commands. Each addition also uses an overriden HashMap class with an instance initializer. This may be considered a "synthetic sugar" for Java.

A: In your case, you need an array of maps.
Something like:
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
// 0
Map<String, String> tmp = new HashMap<String, String>();
tmp.put("name", "sagar");
tmp.put("company", "Visa");
list.add(tmp);
// 1
tmp = new HashMap<String, String>();
tmp.put("name", "shloka");
tmp.put("company", "Doctor");
list.add(tmp);
// so on, so forth...

A: Java does not have associative arrays; you can use a List of Maps instead.
List<Map<String, String>> myArray = new ArrayList<Map<String, String>>();
for (int i = 0; i < max; ++i) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("name", names[i]);
    map.put("company", companies[i]);
    myArray.add(map);
}

Unfortunately, there's no nice syntactic sugar that allows you to declare such a data structure without writing some procedural code.

A: Multi-dimensional arrays in Java are done as arrays of arrays.
int foo[][] = new int[8][8];
foo[0][0] = 3;
But yes, you want an array of Maps in your case.


text:
Q: store Recursive function value in array (php) I have function to find all parent of child I have created  function i m getting parent id but not able to save in one array and return one array instead only last valu getting inserted . array_push is not working in my case here.
function has_parent($parent,$con) {
    $return  = array();
        $selectparent = "select * from table where id = $parent ";
        $qResult = mysqli_query($conobj,$selectparent);
        $qRow = mysqli_fetch_assoc($qResult);
        $parent_id = $qRow['parent_id'];
        if ($parent_id != 0) {
            //$return[] = $parent_id;
            echo $parent_id; // geting parent id as 432
            $return[] = $parent_id;
            $a = has_parent($parent_id, $con);
        }else{
            return $parent_id;
        }

    return $return;
}

$marray =  folder_has_parent($parent ,$con);
print_r($marray); // getting last array only

Array
(
    [0] => 4
)

expected output:
Array
(
    [0] => 4
    [1] => 3
    [3] => 2
)

A: You are overriding $return all the time when you calling the recursive function in the line $return  = array();. so instead you should try making the $return a global variable hence it is no longer in the function scope.
function has_parent($parent,$con) {
    global $return; // global variable
    $selectparent = "select * from table where id = $parent ";
    $qResult = mysqli_query($conobj,$selectparent);
    $qRow = mysqli_fetch_assoc($qResult);
    $parent_id = $qRow['parent_id'];
    if ($parent_id != 0) {
        //$return[] = $parent_id;
        echo $parent_id; // geting parent id as 432
        $return[] = $parent_id;
        $a = has_parent($parent_id, $con);
    }else{
        return $parent_id;
    }

    return $return;
}

$return  = array(); // setting the global variable
$marray =  folder_has_parent($parent ,$con);
print_r($marray);

A: This may be slow because of array_merge, but it will return array in order that you wish.
function has_parent($parent,$con) {
    $return  = array();
    $selectparent = "select * from table where id = $parent ";
    $qResult = mysqli_query($conobj,$selectparent);
    $qRow = mysqli_fetch_assoc($qResult);
    $parent_id = $qRow['parent_id'];
    if ($parent_id != 0) {
        $return = [ $parent_id ];
        $return = array_merge( $return, has_parent($parent_id, $con) );
    }
    return $return;
}

This may work faster, but result will be in reversed order
function has_parent($parent,$con) {
    $return  = array();
    $selectparent = "select * from table where id = $parent ";
    $qResult = mysqli_query($conobj,$selectparent);
    $qRow = mysqli_fetch_assoc($qResult);
    $parent_id = $qRow['parent_id'];
    if ($parent_id != 0) {
        $return = has_parent($parent_id, $con);
        $return[] = $parent_id;
    }
    return $return;
}

Of course time required for array copy will be negligible compare to query time, but I'd prefer to use second variant and then run array_reverse. It's more readable (for my opinion).
UPDATE: This function can be easily rewrite to iterative function. Iterative functions easier to understand (meter of taste), and it may work better (at least require less memmory) then recursive.
function has_parent($parent,$con) {
    $return  = array();
    do{
       $selectparent = "select * from table where id = $parent ";
       $qResult = mysqli_query($conobj,$selectparent);
       $qRow = mysqli_fetch_assoc($qResult);
       $parent_id = $qRow['parent_id'];
       if( $parent_id != 0) {
          $return[] = $parent_id;
          $parent = $parent_id;
       }
    } while( $parent_id != 0 );
    return $return;
}


text:
Q: Building single sided buffer around categorized polygon layer I need to build a 100m buffer around a categorized polygon layer using QGIS 3.2.
The layer has four classes and no holes. The difficulty here is, that the buffer needs to be split into the 4 categories at the edges of the original polygons. Hard to explain in words, so I drew a quick sketch:

It doesnt have to follow a specific rule and it can be a multistep solution as well.
How can this be done using QGIS 3.2? And is there a special term for single sided buffers like this?

A: This sort of situation lends itself to a raster solution, then you can convert back to polygon.  Conceptually, you are really buffering and then assigning the buffered area the nearest polygon value. So, breaking it down into steps:
1) perform a 100m buffer of all your polygons which will be used as a mask layer.
2) assign a numerical value to your polygon classes and convert the polygons to raster using the buffered mask layer to assign NoDATA to the area within the buffer area, but excluding the polygon (data) areas (simply using the buffer area as the output raster extent works too, if you were to assign values to all pixels within the extent and then clip to buffer later).
3) run the GDAL "Fill NoData" tool (aka "Nibble" tool in ESRI software).
4) convert your raster to polygons.
At this point you can joined based on class to get any extra attributes and erase and append/merge to get your original polygons into the output.


text:
Q: how can I update multiple values in a firestore map using only one write without overwriting the entire map this code will overwrite the entire map in firestore
Map<String, String> map = {};
for (MapEntry e in someGientMap.entries) {
  map[e.key] = e.value;
}
await db.doc('document path').update({
  'FirestoreGiantMap': map,
});

and this code will write the document too many times
for (MapEntry e in someGientMap.entries) {
  await db.doc('document path').update({
    'FirestoreGiantMap.${e.key}: e.value,
  });
}

A: You're almost there. Combing the two techniques leads to:
Map<String, String> map = {};
for (MapEntry e in someGientMap.entries) {
  var key = 'FirestoreGiantMap.' + e.key;
  map[key] = e.value;
}
await db.doc('document path').update(map);


text:
Q: 'Restore Defaults' Preference Page Functionality in Eclipse Is there a programmatic method of achieving the same results as clicking 'Restore Defaults' in an Eclipse preference page?
I already know how the field editor system works and preference storage works.
Thanks! :)

A: The method setToDefault() of IPreferenceStore seems to be a good candidate.
You can see the EditorsUI using this function:
public static void useQuickDiffPreferencePage(IPreferenceStore store) {
  MarkerAnnotationPreferences.useQuickDiffPreferencePage(store);
  store.setToDefault(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
  store.setToDefault(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_CHARACTER_MODE);
  store.setToDefault(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER);
}

Or in the method resetToDefaultSettings() of class HeapWalkingManager:
/**
 * Resets the preferences controlled by this manager to their default settings
 */
public void resetToDefaultSettings(){
  JDIDebugPlugin.getDefault().getPluginPreferences().setToDefault(JDIDebugPlugin.PREF_SHOW_REFERENCES_IN_VAR_VIEW);
  JDIDebugPlugin.getDefault().getPluginPreferences().setToDefault(JDIDebugPlugin.PREF_ALL_REFERENCES_MAX_COUNT);
  JDIDebugPlugin.getDefault().getPluginPreferences().setToDefault(JDIDebugPlugin.PREF_ALL_INSTANCES_MAX_COUNT);
}


text:
Q: JavaScript Hoisting - Hoisted code after Memory Creation phase I was reading Kyle Simpson book: https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/scope%20%26%20closures/ch4.md#functions-first.
But I don't fully understand this line "Notice that var foo was the duplicate (and thus ignored) declaration, even though it came before the function foo()... declaration, because function declarations are hoisted before normal variables."
Let's say this is the code:
console.log(foo);     // The output is: foo() { return 2; }

function foo() {
    return 1;
}

function foo() {
    return 2;
}

var foo = 3;

I want to visualize what would be the output in JS Engine after Memory Creation phase. Will it be like this?
function foo() {
    return 2;
}

console.log(foo);

If yes, why var foo = 3; was ignored? There is no duplicate for var in the snippet. If no, can anyone please help me visualize what would be the output in JS Engine after Memory creation phase?
Thanks

A: *

*Function declarations

*

*Declare a variable with the same name as the function (this is hoisted)

*Assign the function to that variable (this is hoisted)

*var statements with associated assignments

*

*Declare a variable with that name (this is hoisted)

*Assign the value to that variable (this is not hoisted)

var foo = 3 is not ignored.
The variable declaration (var foo) is ignored because the earlier function declarations already declared that variable. (i.e. because it duplicates the declaration of foo).
foo = 3 is not ignored and does assign 3 to foo … it just does so after your console.log statement runs because it isn't hosited.

A: I think the text refers to
// scope creation
var foo; // the name was declared. Thrice.
foo = undefined; // from the var
foo = function foo() { return 1 }; // from the first declaration
foo = function foo() { return 1 }; // from the second iteration

// execution
console.log(foo);
;
;
foo = 3;

where foo is initialised with undefined due to the var foo declaration, but then gets overwritten by the initialisation value from  the function foo declaration which takes precedence - regardless of the order in which the declarations appeared in the code, function declarations overrule var declarations.


text:
Q: dbms_scheduler - Passing log_id in event based job I am trying to create an event based job using oracle dbms_scheduler as described below. Is there a way we can pass the job information that raised the event into the job that is executed based on that event.
Subscribing to the queue
BEGIN
   sys.DBMS_SCHEDULER.add_event_queue_subscriber ('my_queue_agent');
END;

Create program that will be called by the first job
begin
  sys.dbms_scheduler.create_program(program_name        => 'PROGRAM_TEST',
                                    program_type        => 'STORED_PROCEDURE',
                                    program_action      => 'PROC_TEST_SCHEDULER',
                                    number_of_arguments => 2,
                                    enabled             => false,
                                    comments            => '');
  sys.dbms_scheduler.define_program_argument(program_name        => 'PROGRAM_TEST',
                                             argument_position   => 1,
                                             argument_name       => 'P_JOB_NAME',
                                             argument_type       => 'VARCHAR2',
                                             default_value       => '');

  sys.dbms_scheduler.define_metadata_argument(program_name       => 'PROGRAM_TEST',
                                              metadata_attribute => 'LOG_ID',
                                              argument_position  => 2,
                                              argument_name      => 'LOG_ID');
  sys.dbms_scheduler.enable(name => 'PROGRAM_TEST');
end;

Create job that utilizes the program.
begin
  sys.dbms_scheduler.create_job(job_name            => 'TEST_PROGRAM_JOB',
                                program_name        => 'PROGRAM_TEST',
                                start_date          => to_date(null),
                                repeat_interval     => '',
                                end_date            => to_date(null),
                                job_class           => 'DEFAULT_JOB_CLASS',
                                enabled             => false,
                                auto_drop           => false,
                                comments            => '');
  sys.dbms_scheduler.set_job_argument_value(job_name       => 'TEST_PROGRAM_JOB',
                                            argument_name  => 'P_JOB_NAME',
                                            argument_value => 'TEST_PROGRAM_JOB');

 sys.dbms_scheduler.set_attribute(name => 'TEST_PROGRAM_JOB', attribute => 'raise_events', value => sys.dbms_scheduler.job_started + sys.dbms_scheduler.job_succeeded + sys.dbms_scheduler.job_failed);
end;

Create second job that would be triggered based on events of first job.
BEGIN
   sys.DBMS_SCHEDULER.create_job (
      job_name          => 'UPDATE_STATUS_JOB',
      job_type          => 'PLSQL_BLOCK',
      job_action        => 'insert into t_log values (''UPDATE'' || tab.user_data.log_id,sysdate);',
      event_condition   => '(tab.user_data.event_type = ''JOB_SUCCEEDED'' OR
                             tab.user_data.event_type = ''JOB_FAILED'' or
                             tab.user_data.event_type = ''JOB_STARTED'' or
                             tab.user_data.event_type = ''JOB_COMPLETED'') AND tab.user_data.object_name = ''TEST_PROGRAM_JOB''',
      queue_spec        => 'sys.scheduler$_event_queue,my_queue_agent',
      enabled           => TRUE);
END;

Is there a way I can pass the current log_id of TEST_PROGRAM_JOB into UPDATE_STATUS_JOB? I want to log the status of the TEST_PROGRAM_JOB. Right now, I tried using tab.user_data.log_id but with no success.

A: sys.dbms_scheduler.define_metadata_argument only works with 'job_name', 'job_subname', 'job_owner', 'job_start', 'window_start', 'window_end', and 'event_message.
In your case try to use event_message. You can also replace p_job_name with job_name.


text:
Q: Firebase cloud functions bundled with webpack? I've been stuck for a while trying to make a webpack build for my cloud functions files.
My project structure:
ROOT

- FUNCTIONS
  - DIS
    - bundle.js // THIS SHOULD BE GENERATED BY WEBPACK
  - SRC
    - myCloudFunction.js  // SOURCE CODE FOR A CLOUD FUNCTION
    - entryPoint.js  // ENTRY POINT FOR WEBPACK
  - index.js
  - package.json

- SRC
  - App.js

.babelrc
firebase.json
webpack.prod.js    // THIS BUILDS FOR CLIENT (WORKING FINE)
webpack.server.js  // THIS SHOULD BUILD FOR THE SERVER (NOT WORKING)

My goal is:

*

*Write cloud functions files and the index.js in modern JS and transpile and bundle them with webpack (using the same webpack that I use to bundle my client code, but with another config file).

myCloudFunction.js (simple function logging some text)
module.exports = (req,res) => {
  console.log('myCloudFunction is executing...');
  res.status(200).send('From myCloudFunction...');
}

entryPoint.js (basically imports function's code and export them as cloud functions)
const functions = require('firebase-functions');
const myCloudFunction = require('./src/myCloudFunction');

module.exports.myCloudFunction = functions.https.onRequest(myCloudFunction);

If I make the index.js exactly like my entryPoint.js it works just fine. But I want to bundle the files using webpack from the entryPoint.js and set the bundled result to my index.js file. Basically only 2 files will be bundled in this case (entryPoint and myCloudFunction).
I'm using webpack to bundle:
webpack.prod.server.js
const webpack = require('webpack');
const path = require('path');
const Dotenv = require('dotenv-webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  mode: 'development',
  stats: 'verbose',
  devtool: 'inline-source-map',

  entry: {
    app: './functions/src/entryPoint.js'
  },

  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './functions/dist'),
    publicPath: '/'
  },

  // externals: {
  //   "firebase-admin": true,
  //   "firebase-functions": true
  // },

  target: 'node',
  externals: [nodeExternals(),'firebase-functions', 'firebase-admin','firebase'],

  plugins:[
    new CleanWebpackPlugin(),
    new webpack.HashedModuleIdsPlugin(),
    new webpack.DefinePlugin({
        'process.env.ON_SERVER': true
    }),
    new Dotenv()
  ],

  module: {
    rules:[
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        use: ['babel-loader']
      },
    ]
  }
};

I read that you shouldn't bundle node_modules to the backend, that's why I'm using the externals property.
bundle.js (the result bundle after running webpack with the config above)
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/        }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/        if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/            Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/        }
/******/        Object.defineProperty(exports, '__esModule', { value: true });
/******/    };
/******/
/******/    // create a fake namespace object
/******/    // mode & 1: value is a module id, require it
/******/    // mode & 2: merge all properties of value into the ns
/******/    // mode & 4: return value when already ns object
/******/    // mode & 8|1: behave like require
/******/    __webpack_require__.t = function(value, mode) {
/******/        if(mode & 1) value = __webpack_require__(value);
/******/        if(mode & 8) return value;
/******/        if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/        var ns = Object.create(null);
/******/        __webpack_require__.r(ns);
/******/        Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/        if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/        return ns;
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "/";
/******/
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = "oFca");
/******/ })
/************************************************************************/
/******/ ({

/***/ "4ouX":
/*!******************************************!*\
  !*** ./functions/src/myCloudFunction.js ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = (req,res) => {
  console.log('myCloudFunction is executing...');
  res.status(200).send('From myCloudFunction...');
}

/***/ }),

/***/ "O8Wp":
/*!*************************************!*\
  !*** external "firebase-functions" ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = firebase-functions;

/***/ }),

/***/ "oFca":
/*!********************************!*\
  !*** ./functions/src/index.js ***!
  \********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

const functions = __webpack_require__(/*! firebase-functions */ "O8Wp");
const myCloudFunction = __webpack_require__(/*! ./myCloudFunction */ "4ouX");

module.exports.myCloudFunction = functions.https.onRequest(myCloudFunction);

/***/ })

/******/ });

IT SHOULD BE WORKING, BUT I'M GETTING THIS ERROR:
I would expect to copy the contents of bundle.js and paste it to index.js and make it work. But when I do this, I get this error when I'm trying to serve the function. See the error line in the picture below.
>>> firebase serve --only hosting,functions

+  functions: Using node@10 from host.
+  functions: Emulator started at http://localhost:5001
i  functions: Watching "C:\Projects\test-ssr\functions" for Cloud Functions...
i  hosting: Serving hosting files from: public
+  hosting: Local server: http://localhost:5000
!  ReferenceError: firebase is not defined
    at Object.O8Wp (C:\Projects\test-ssr\functions\index.js:110:20)

QUESTION
What am I doing wrong? Any help would be appreciated!

UPDATE
I've just found out that this fixes the problem, but I have no idea why this is necessary. I still would like some better understanding of this issue.
webpack.prod.server.js
output: {
    filename: '[name].[contenthash:5].js',
    // filename: 'index.js',
    path: path.resolve(__dirname, './functions/dist'),
    publicPath: '/',
    libraryTarget: 'commonjs'   // <--- THIS FIXED IT
  },

A: As you found, you need to set libraryTarget in order to build a webpack bundle that can itself be imported by another module outside the webpack build (e.g. from cloud functions).
It's a good idea to bundle your functions app using webpack for alot of reasons. As you've pointed out, it means you can compile the same code in a consistent way for different purposes - e.g. SSR and browser side. Other benefits:

*

*access to webpack loaders/plugins

*much better developer experience with HMR (that works better than the functions runtime's implementation)

*better performance for deployment and runtime (one or a few optimized chunks vs hundreds/thousands of unoptimised/unused files)

In any case, you might have an easier time using webpack-cloud-functions (of which I'm the author). It abstracts away much of the configuration you need to do that, including configuring the libraryTarget.


text:
Q: Global CBT hook is never called I'm trying to make an application that gets informed on creation and destruction of top-level windows, system-wide. I've made a code to exploit a CBT hook. The solution contains two projects, DLL and EXE. EXE project has a reference to the DLL project. The hook is being set from a DLL. There is a message loop in EXE project. The problem is that CBT hook is not working. With the help of VS debugger, I've found out that hook callback is never called, while return code from SetWindowsHookEx is non-zero, implying the hook was set. What's a mistake? How do I fix it?
Here's a minimal example. DLL, main.cpp:
#include <windows.h>

typedef void(*DECODERPROC)(int code, WPARAM wParam, LPARAM lParam);

HINSTANCE hInst = nullptr;
HHOOK hHook = nullptr;
DECODERPROC fpDecoder = nullptr;

LRESULT CALLBACK cbtProc(int code, WPARAM wParam, LPARAM lParam) {
    // FIXME: never called
    if (code > 0 && fpDecoder) {
        fpDecoder(code, wParam, lParam);
    }
    return CallNextHookEx(hHook, code, wParam, lParam);
}

__declspec(dllexport) bool InstallHook(DECODERPROC decoder) {
    if (hHook) return false;
    fpDecoder = decoder;
    return (hHook = SetWindowsHookEx(WH_CBT, cbtProc, hInst, 0)) != NULL;
}

__declspec(dllexport) bool UninstallHook() {
    if (!hHook) return false;
    bool res = UnhookWindowsHookEx(hHook) != NULL;
    if (res) hHook = NULL;
    return res;
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    hInst = reinterpret_cast<HINSTANCE>(hModule);
    return TRUE;
}

EXE, main.cpp
#include <iostream>
#include <locale>

#include <windows.h>
#include <fcntl.h>
#include <io.h>
using namespace std;

typedef void(*DECODERPROC)(int code, WPARAM wParam, LPARAM lParam);
__declspec(dllimport) bool InstallHook(DECODERPROC);
__declspec(dllimport) bool UninstallHook();

int main() {
    _setmode(_fileno(stdout), _O_U8TEXT);
    WNDCLASS windowClass = {};
    windowClass.lpfnWndProc = [](HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT {
        if (message == WM_DESTROY)
            UninstallHook();
        return DefWindowProc(hWnd, message, wParam, lParam);
    };
    LPCWSTR windowClassName = L"Foobar";
    windowClass.lpszClassName = windowClassName;
    if (!RegisterClass(&windowClass)) {
        wcerr << L"Failed to register window class" << endl;
        return 1;
    }
    HWND messageWindow = CreateWindow(windowClassName, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, 0);
    if (!messageWindow) {
        wcerr << L"Failed to create message-only window" << endl;
        return 1;
    }

    InstallHook([](int code, WPARAM wParam, LPARAM lParam) {
        wcout << L"Never called" << endl;
    });

    MSG msg;
    while (GetMessage(&msg, 0, 0, 0) > 0) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

A: If you are running on Windows 64-bit, you need both 32-bit and 64-bit versions of the DLL in order to hook every running process. A 32-bit DLL cannot hook a 64-bit process, and vice versa. So you need to call SetWindowsHookEx() from a 32-bit process to hook 32-bit processes, and from a 64-bit process to hook 64-bit processes.
More importantly than that, a separate instance of your DLL gets injected into every running process, so your fpDecoder callback pointer is NULL in every instance of the DLL except for the one that your EXE is calling InstallHook() on. So you need to redesign your hook to use inter-process communication (window message, named pipe, mailslot, socket, etc) to communicate with your main EXE, you can't use a function pointer.
Depending on which process you are actually debugging, you might not see cbtProc() getting called. If you are debugging your main EXE process, your code is not doing anything to trigger any CBT activity within your EXE's process once the hook has been installed, and the debugger would not show you any CBT activity occurring in other processes that it is not debugging.
Depending on what you are actually looking for in your hook, you might consider using SetWinEventHook() instead, as it can be used with or without a DLL, and it has more flexible filtering capabilities than SetWindowsHookEx().


text:
Q: Is it possible to bind  to kill-whole-line in cshell? Due to using Matlab and ipython, I have muscle memory to hit escape to blow away a line and start over. Is it possible to make a key binding to kill-whole-line for the escape key? I don't really understand what I'm doing, but have tried things like this:
bindkey -k escape kill-whole-line

but that doesn't actually work.

A: Yes:
bindkey '^[' kill-whole-line

However, since Escape is also used as a prefix for arrow keys and Meta combos, you may be better off using e.g. two escapes so as not to interfere with them:
bindkey '^[^[' kill-whole-line


text:
Q: Fragment to Activity Shiffting I am using this as my code it is a fragment as
I want to add OnClickListener on my button Login
How to do it and what I should do so that it works. New at Java day -03.
Do I have to import any classes? Please clarify it with more and more clarification
//This is my code
public class LoginTabFragment  extends Fragment {

    EditText email,password;
    TextView forgotPass;
    Button login;
    float v =0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login_tab_fragment, container, false);

        email = root.findViewById(R.id.email);
        password = root.findViewById(R.id.password);
       forgotPass = root.findViewById(R.id.forgot_pass);
        login = root.findViewById(R.id.btn);

        email.setTranslationX(800);
        password.setTranslationX(800);
        forgotPass.setTranslationX(800);
        login.setTranslationX(800);

        email.setAlpha(v);
        password.setAlpha(v);
        forgotPass.setAlpha(v);
        login.setAlpha(v);

        email.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
        password.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(500).start();
        forgotPass.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(500).start();
        login.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(700).start();

        return root;

    }
}```

>It Animates my screen now I want to log in and move to the other page. So what should I do?


text:
Q: How to remove all but last n commits from git history to save space I use git to backup and restore folders that can change on my system and they can get really large as useless history accumulates. I only need the last 4 or so commits, how can I squash or delete the whole history except for the last n commits?

A: Disclaimer: Your first sentence may have unfortunately tainted this question:

I use git to backup and restore folders that can change on my system and they can get really large as useless history accumulates.

If the history is "useless", than perhaps Git isn't the correct tool to use. As mentioned in the comments, Git is generally not the right tool for a backup system. That being said, if your question didn't include the first sentence, we wouldn't have been able to pass judgement as to "why" you wish to do this, and your remaining question is certainly valid:

I only need the last 4 or so commits, how can I squash or delete the whole history except for the last n commits?

Here's one fairly straight-forward way to accomplish this. Note this method requires that you determine some things before you begin:

*

*The branch name you wish to rewrite. (This answer will assume it is called main.)

*The root commit of your branch. Get it with: git log main --reverse (This answer will assume it is called <old-repo-root-commit-id>.)

*The oldest commit ID you want to keep, e.g. your forth commit from the top, which will become your new repo root commit. (This answer will assume it is called <new-repo-root-commit-id>.)

*Your git status should be clean before you start. If it isn't, consider committing (or undoing) your most recent changes.

Here are the set of commands to run:
git switch --detach <new-repo-root-commit-id>
git reset --soft <old-repo-root-commit-id>
git commit --amend --reuse-message=<new-repo-root-commit-id>
git rebase <new-repo-root-commit-id> main --onto @

I see your title mentions your goal is to save space. In order for this to also achieve that goal you can't have any other refs leftover in your repo which point to your old commit IDs. If you only have a single branch in your system without any tags, then the old commits will eventually get garbage collected. If you want to clean it up right now, see this question.
Detailed explanation of how the commands work:

*

*The switch command simply checks out the specific commit you want to be your new root commit. This is identical to git checkout <new-repo-root-commit-id> but the newer switch command requires you specify --detach when you are checking out a commit ID rather than a named branch.

*The reset command says to change which commit you're currently pointing to, to instead be the root commit ID, and the --soft says to not change your local files, and also leave all the changes that would happen as a result of this reset, as staged and ready to be committed.

*Note after the reset you are pointing to the very first commit in your repo, and now you are going to amend (rewrite) that commit to include all changes between the root and the new root commit. This is essentially just squashing all the previous commits into a single commit. The --reuse-message option says to use the commit message from the new repo root instead of the original repo root. This isn't actually needed, but it's more likely that the more recent commit message is better than the original one. This of course depends on what your commit messages say; when committing you can set a message from any other commit if you wish, or create a new different one too.

*After the commit command you have exactly one commit, and now you will rebase (replay) the remaining (e.g. 3) commits that were on main, "onto" your new commit, leaving you with just 4 commits. At this point if you do a diff of main with the commit ID that main was on before this process, the results should be empty, because you didn't actually change your working files at all. (Note you can use git reflog to see what commit ID main was on before you did this, as long as you didn't perform a full garbage collection yet of reflogs and old commits.)


text:
Q: Trying to show full size image from thumbnails retrieved using php and database I'm trying to use thumbnails retrieved from database. PHP is working fine and displaying my thumbnails. I don't know how to get the id from database into the imageID for JavaScript function and getElementById, to display as full size when clicked.   I can do straight JavaScript inline onsubmit in my code.  The inline JavaScript is working; the thumbnail is being displayed, and when clicked a full size shows, but I want to use my database retrieved images to show the full size image when clicked.  Do you think you can help me with my code?
<!DOCTYPE html>

<title></title>

<?php

$host = "localhost";
$user = "root";
$pass = "";
$database = "travel1";

$conn = new mysqli($host, $user, $pass, $database);

if ($conn->connect_error)
    die ("Unable to connect to database: " . $conn->connect_error );

$sql = "select * from what_to_do
    where DESTINATION='NEW YORK CITY'";
$result = $conn->query($sql);

if ($result->num_rows >= 0) {
    echo "
";
        while($row = $result->fetch_assoc()) {
            echo "".$row["THUMBNAIL"]."	";
        }
        echo "
";
}
else {
        echo "You have no destinations";
}
$conn->close();
?>

A: In this code the second img tag is closed prematurely, like  src="something" etc etc. If that tag were properly formed, I think this should work?
Otherwise, you would just do something like " src="/blah" />
Hopefully that answers your question?
And then for the I onclick function just do essentially the same thing.

A: I'm going to presume a lot, but here goes!
The above answer is correct, you are prematurely closing an image tag at the bottom of your code, it should be like this:

But otherwise there are a few other issues to address...
First, by typing in the specific name of the destination for each query on every page you'll be defeating the purpose in using a database! Just like you've mentioned, you need to use the ID and pull in the data accordingly.
To do this you need to define what the ID is by letting the user select the destination on a previous page/section(in your example a destination list might be appropriate with all the destinations in some kind of order, be that ascending or descending ect... PHP has a few different ways.)
So first, the query to sort by ID is:
SELECT * FROM travel1 order by id desc

and then to set the ID in the URL when the destination link is clicked, here's an example link using php to carry the ID to the next page:
<a href="/destination-info.php?id=<?php echo $rows['id']; ?>">more info

Once you get to the destination info page(that's what I'm calling your above code), filter your data so that you can access the specific destination by ID by firstly adding this to your page(after you've connected to the database that is):
<?php
if(isset($_GET['id'])){
        $id = preg_replace('#[^0-9]#i', '',$_GET['id']);
        $result = $con->query("SELECT * FROM travel1 WHERE id='$id' ");
        while($rows = $result->fetch_assoc()) {
        echo "".$row["THUMBNAIL"]."	";
         }

         } else {
 echo "We're having some issues...";
}
?>

The above code will pick up the database ID from your URL which was carried over from the previous page(your new destination list) and can be echoed out like your other links such as:
'echo "".$row["THUMBNAIL"]."	";'

I hope this helped! =D


text:
Q: jQuery or angularjs plugin to build dynamic reports I'm looking for some sort of drag and drop  jquery/angular/javascript plugin that can create dynamic report.
The type of report I want to create is not charts but simple tables and grids with texts . After creating this I could be able to download it as pdf or excel file. Basically I want to create pdf or excel reports.
Could not find anything after lots of googling. I hope someone knows of something that can help!
Thanks

A: I believe you have to pay for it but the best plugin I've seen for this type of stuff is the Telerik Kendo UI Grid.
Check it out here:
http://demos.telerik.com/kendo-ui/grid/index


text:
Q: Will intel Wifi AX200 work with ubuntu 20.4 in WIFI 6 mode Intel Wifi AX200 wifi 6 compatibility with Ubuntu 20.04. Or 20.10
If so can anyone sugest a descktop adapter- preferably intel manufactured board.
I have a tp-link AX1500 Wifi router used with Windows 10.
Can you include detailed instruction in Kernel, Firmware, and Driver modifications if needbe.
I'm pretty new to these thing.


text:
Q: How to deploy an existing war file to AWS using bitbucket I am creating a java web application and using bitbucket as my code repository. And I have an AWS instance (Running in Ubuntu) in which I host my web application under an apache tomcat application server.
I want to automatically deploy my war file to the webapp folder in tomcat (tomcat directory is something like home/ubuntu/etc/etc)
I know that it is possible to automate war file deployments to AWS using bitbucket and I tried various tutorials and instructions, but it didn't get me anywhere.

A: It seems like using the rsync-deploy pipe is the way to go. The pipe will sync your war file to the destination folder on your tomcat server. This is an example of the pipeline configuration:
pipelines:
  default:
    - step:
        script:
          - pipe: atlassian/rsync-deploy:0.4.1
            variables:
              USER: 'username'
              SERVER: 'server-hostname'
              REMOTE_PATH: '/deploy-directory-name/'
              LOCAL_PATH: 'application.war'


text:
Q: How to create a two way mapping between an input space and a higher dimensional sparse constrained space? I think this problem can be solved with ML because there are some properties of the output space that I want to achieve.
Problem: D1 <-> D2  where D1 is input space and D2 is a space such that: D2 will have more dimensionality (by orders of magnitude probably) where each dimension is constrained to a natural number between 0 and N and there is a probability P that +-1 change to a random dimension in D2 will have no effect on the mapping back to D1. There is a probability P2 that such a change will only affect a single dimension in D1, probability P3 that it will affect 2 dimensions, and other such rules...
The goal is to create a way to map that would allow the application of genetic algorithms to the D2 space with the rationale that this is how DNA works and it's obviously effective.
Genetic algorithms applied to D1 can be next to useless if there are hidden relationships between dimensions, it's the main reason D2 is needed, where such relationships would be minimized and where they do exist their impact magnitude back to D1 would be randomized.

A: It sounds like you are looking for an "error correcting code." In this case, D1 is your initial representation, and D2 is a redundant code. The theory of these codes allows you to calculate the probability of recovering the correct representation, given the size of the code D2, and the probability of D2 being corrupted.
One really excellent reference for binary error correcting codes is David MacKay's Information Theory, Inference, and Learning Algorithms, particularly section II. Note that this is not exactly what you want, as you mentioned natural numbers from 0 to N, not binary numbers. You can also search for "analog error correcting codes," which might get you closer to exactly what you're requesting here.
About genetic algorithms, apparently these can also be applied to the problem of discovering ideal error correcting codes, for example in this paper.


text:
Q: Remapping issues. How do I map CtrlP to 'ff' Im trying to remap :CtrlP to :ff but I cant seem to get it to work.
Here is what I have tried:
nnoremap ff :CtrlP<cr>
nnoremap <ff> :CtrlP<cr>
Would appreciate the help!

To give more context, im trying to use the method :CtrlP when I open my project by doing: vi .. I am using Nerdtree as well.

A: It's not possible to remap :CtrlP to :ff, because user-defined ex commands must start with a capital letter.  You could map it to :Ff by doing the following:
command! Ff CtrlP

If you want to map it as a normal mode command instead of an ex command, then the first choice you've mentioned should do it.


text:
Q: I want to send some data to loaclstorage with useContext properly, how should I do it? (react JS) I am making my project with Fullcalendar and I have a problem with making it.
first, This is my state:
const [state, setState] = useState({
    externalEvents: [],
  });

and this is my todo-input form to make a new externalEvent.
export default function Todo({state,setState}) {

  const [color, setColor] = useState("");
  const [custom, setCustom] = useState("");
  const [title, setTitle] = useState("");

  const getColor = (e) => {
    setColor(e.target.value);
  };

  const addTodo = (e) => {
    e.preventDefault();
    if (title === "" || color === "") {
      alert("please type what to do or choose a color");
    } else {
      setState({
        externalEvents: [
          ...state.externalEvents,
          { title: title, color: color, custom: custom, id: uuidv4(), },
        ],
      });

      localStorage.setItem("todoStore", JSON.stringify(state.externalEvents));

      setTitle("");
      setCustom("");
    }
  };

  return (
    <>
       <form className="todoinput" onSubmit={addTodo}>
            <input
              className="addevent"
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Add event"
            />
            <input
              className="detail"
              type="text"
              value={custom}
              onChange={(e) => setCustom(e.target.value)}
              placeholder="detail"
            />
            <select className="selectcolor" onChange={getColor} value={color}>
              <option value="select">select color</option>
              <option value="#34568B">dolphin</option>
              <option value="orange">tangerine</option>
              <option value="#88B04B">grass</option>
              <option value="#6B5B95">violet</option>
            </select>
            <button className="addtodo" type="submit"><FontAwesomeIcon icon={faPlusCircle}/> Add todo  </button>
          </form>
    </>
  )
}

If I make a new todo it is saved in State and I'm gonna show the list of externalEvents via map() like below

              {state.externalEvents.map((event) => (
                <div

                  draggable={true}
                  className="fc-event"
                  title={event.title}
                  data-id={event.id}
                  data-color={event.color}
                  data-custom={event.custom}
                  key={event.id}
                  style={{
                    backgroundColor: event.color,
                    borderColor: event.color,
                    cursor: "pointer",
                  }}

                >

                  {event.title}

                {event.custom}

              ))}

The first problem happened here. that mapping part works fine, However, saving it to localStorage part is a little bit tricky
:
localStorage.setItem("todoStore", JSON.stringify(state.externalEvents));

above code doesn't save the first externalEvent I made and It starts to save it to localStorage from the second one.
The second problem is more tricky. I wanted to show externalEvents even after I rerender(refresh) the page. so I made a DataProvider Component like below
import React,{useState,useEffect,createContext} from 'react'

export const DataContext = createContext();

export const DataProvider = (props) => {
    const [todos, setTodos] = useState({
      externalEvents: [],
    });

    useEffect(() => {
      const todoStore = JSON.parse(localStorage.getItem('todoStore'))
      if(todoStore) setTodos(todoStore)

    },[])

    useEffect(() => {
      localStorage.setItem('todoStore', JSON.stringify(todos));
    },[todos])

  return (
   <DataContext.Provider value={[todos,setTodos]}>
     {props.children}
   </DataContext.Provider>

  )
}

above code is a component that I made before to manage the same problem in my other todoproject, So I tried to my current todoComponent with this data provider
like below
import React, { useState } from "react";
import {DataProvider} from './components/calendar/DataProvider'
...

function App() {
  <>
<DataProvider>
...
<Switch>
...
<Route path="/calendar" component={Calendar} /> // calendarcomponets has above code and components in it
</Switch>
</DataProvider>
  </>
   }

So, I thought now, I can change my State
from this
 const [state, setState] = useState({
    externalEvents: [],
  });

to this
const[state,setState] = useContext(DataContext);

However, It seems like It doesn't work because my state already has kind of form
So I changed DataContext like below
export const DataContext = createContext({
externalEvents: [],

});
But, as you expected It doesn't work at all.
I'm pretty new to use useContext and tbh also new to coding. So I don't know how can I pass my states to DataProvider properly, Can you help me with it?
Thx for reading, your help will be appreciated.


text:
Q: Find the number of observations since the opposite event occured in R using datatables I am hoping to create a new variable in datatable that adds a column telling me the number of days since the opposite (or other event occured).
The dataset I have looks like the following:
  date     event  id obs_since_event_1 obs_since_event_2
2000-07-06     2  1        NA                 NA
2000-07-07     1  1        NA                 1
2000-07-09     0  1        1                  2
2000-07-10     0  1        2                  3
2000-07-15     2  1        3                  4
2000-07-16     1  1        4                  1
2000-07-20     0  1        1                  2
2000-07-21     1  1        2                  3
2000-07-06     1  2        NA                 NA
2000-07-07     2  2        1                  NA
2000-07-15     0  2        2                  1
2000-07-16     0  2        3                  2
2000-07-17     2  2        4                  3
2000-07-18     1  2        5                  1

And I am hoping to add a column called days_since_opposite. which records number of days since the opposite event occurred (the opposite events being 1 and 2). I already have the number of days since either an event 1 or 2 occurred. Now I need to work out an if statement that works in datatables that will provide me with the corresponding values in the final column.
  date     event  id obs_since_event_1 obs_since_event_2 days_since_opposite
2000-07-06     2  1        NA                 NA                  NA
2000-07-07     1  1        NA                 1                   NA
2000-07-09     0  1        1                  2                   NA
2000-07-10     0  1        2                  3                   NA
2000-07-15     2  1        3                  4                   3
2000-07-16     1  1        4                  1                   1
2000-07-20     0  1        1                  2                   NA
2000-07-21     1  1        2                  3                   3

I hope this is clear. I also have different ids to reckon with but not sure if it impacts the results.
I tried something along the following lines but it did not work:
data[,days_since_opposite:=ifelse(event==1,obs_since_event_2,ifelse(event==2,obs_since_event_1,0)),]

Thanks in advance
DATA
Input = (
  '  date     event  id obs_since_event_1 obs_since_event_2
2000-07-06     2  1        NA                 NA
2000-07-07     1  1        NA                 1
2000-07-09     0  1        1                  2
2000-07-10     0  1        2                  3
2000-07-15     2  1        3                  4
2000-07-16     1  1        4                  1
2000-07-20     0  1        1                  2
2000-07-21     1  1        2                  3
2000-07-06     1  2        NA                 NA
2000-07-07     2  2        1                  NA
2000-07-15     0  2        2                  1
2000-07-16     0  2        3                  2
2000-07-17     2  2        4                  3
2000-07-18     1  2        5                  1')
df = read.table(textConnection(Input), header = T)

A: Here is an option:
#identify the opposite event
DT[, oppev := c(0L, 2L, 1L)[event + 1L]]

#for event 1 and 2, perform non-equi join to find the prev opp event
DT[event %in% c(1L, 2L), days_since_opposite := DT[.SD,
    on=.(id, event=oppev, date<date), mult="last", as.integer(i.date - x.date)]]

output:
          date event id oppev days_since_opposite
 1: 2000-07-06     2  1     1                  NA
 2: 2000-07-07     1  1     2                   1
 3: 2000-07-09     0  1     0                  NA
 4: 2000-07-10     0  1     0                  NA
 5: 2000-07-15     2  1     1                   8
 6: 2000-07-16     1  1     2                   1
 7: 2000-07-20     0  1     0                  NA
 8: 2000-07-21     1  1     2                   6
 9: 2000-07-06     1  2     2                  NA
10: 2000-07-07     2  2     1                   1
11: 2000-07-15     0  2     0                  NA
12: 2000-07-16     0  2     0                  NA
13: 2000-07-17     2  2     1                  11
14: 2000-07-18     1  2     2                   1

data:
library(data.table)
DT <- fread("date     event  id
2000-07-06     2  1
2000-07-07     1  1
2000-07-09     0  1
2000-07-10     0  1
2000-07-15     2  1
2000-07-16     1  1
2000-07-20     0  1
2000-07-21     1  1
2000-07-06     1  2
2000-07-07     2  2
2000-07-15     0  2
2000-07-16     0  2
2000-07-17     2  2
2000-07-18     1  2")[, date := as.IDate(date, format="%Y-%m-%d")]


text:
Q: WAMP Server virtual hosts configuration OK, I have my wamp installed and simply can't setup my virtual hosts properly.
Here's what I have:
Wamp install dir: F:\wamp
Projects dir: F:\www
# F:\wamp\bin\apache\apache2.4.2\conf\extra\httpd-vhosts.conf
<Directory "F:\www">
    AllowOverride AuthConfig FileInfo Indexes Limit Options
    Order Deny,Allow
    AllowOverride All
    Allow from all
</Directory>

NameVirtualHost 127.0.0.1
<VirtualHost 127.0.0.1>
    ServerName localhost
    DocumentRoot "F:\wamp\www"
</VirtualHost>

# Yes, it's a symfony2 project
<VirtualHost 127.0.0.1>
    DocumentRoot "F:\www\my_project\web"
    DirectoryIndex app_dev.php
    ServerName my_project
</VirtualHost>

hosts file from windows is configured and has the necessary: 127.0.0.1 project_name line included.
Apache httpd.conf:
# Virtual hosts
Include conf/extra/httpd-vhosts.conf

Now the browser tells me this, when accessing URL: my_project/
Forbidden
You don't have permission to access / on this server.

Could somebody give me a clue on what's going on here?

A: Try this as your conf/extra/httpd-vhosts.conf
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80

## must be first so the the wamp menu page loads
## and leave as Allow from 127.0.0.1 as outside access should not be required to the wamp homepage
<VirtualHost *:80>
    ServerAdmin webmaster@homemail.net
    DocumentRoot "F:/wamp/www"
    ServerName localhost
    ServerAlias localhost
    <Directory  "F:/wamp/www">
        Order Deny,Allow
        Deny from all
        Allow from 127.0.0.1
    </Directory>
</VirtualHost>

# Yes, it's a symfony2 project
<VirtualHost *:80>
    DocumentRoot "F:\www\my_project\web"
    ServerName myproject.dev
    ServerAlias myproject.dev www.myproject.dev
    Options Indexes FollowSymLinks
    <Directory "F:\www\my_project\web">
        AllowOverride All
        Order Deny,Allow
        Allow from 127.0.0.1
        Allow from 192.168.2
        ## change to Allow from all when it works
    </Directory>
</VirtualHost>

Now you need to add the site name(s) to your hosts file like this.
127.0.0.1 myproject.dev
::1 myproject.dev

EDIT:
For your browser to find your site domain names you must tell windows that the domain name you are using for testing exists and which ip address it lives on. You do this by adding your testing domain names to a file called hosts. This is read when windows loaded its networking component and cached by a service called DNS Client
To add new local domain names you must edit the windows hosts file
c:\windows\system32\drivers\etc\hosts

And add one line for each of your virtual hosts like this
127.0.0.1  myproject.dev
127.0.0.1  myproject2.dev
127.0.0.1  myproject3.dev
::1  myproject.dev
::1  myproject2.dev
::1  myproject3.dev

Once this is saved, launch a command prompt using Run as Administrator (right click + shift  over the Windows command processor icon to show a menu containing the Run as Administrator menu line) and issue these 2 commands to restart the 'DNS Client' service so it picks up your changes. Alternatively just reboot.
net stop dnscache

when that completes
net start dnscache

PS. The double quotes are required as there is a space in the service name!
HOW TO EDIT THE HOSTS FILE
The hosts file is protected by windows, in order to save it you must have Administrator privilages.
On Vista/W7/W8 you may think you are an Administrator BUT YOU ARE NOT.
To successfully save the hosts file do this to launch your editor with Admin Privilages.
Locate your editors icon on the desktop or from the Start menus ( notepad will do if you have nothing else )
right click + shift  over your chosen editor icon - will show a menu.
select "Run As Administrator" from the menu.
Using file -> open Navigate your editor to the c:\windows\system32\drivers\etc\hosts file.
When you have made changes you will now be allowed to save them.