text:
Q: Security annotation - can't secure
I have a problem using : @Secured({"ROLE_ADMIN"}) above a protected method.
I am logged in with ROLE_EMPLOYEE and I still able run methods annotated with: @Secured({"ROLE_ADMIN"})
this is my config:
<security:global-method-security secured-annotations="enabled" />
<bean id="affiliatesApi" class="com.affiliates.api.AffiliatesApi" />

this is my  AffiliatesApi class
public  class AffiliatesApi extends BaseApplicationAPI<Object> {
@Secured({"ROLE_ADMIN"})
    public ResultContainer getAll(IFilter filter) {
        ISecurityFilter securityFilter = (ISecurityFilter)SecurityUtills.getSecurityFilter();
        return affiliateDao.getAll(Affiliate.class,securityFilter,filter);
    }
}

I am calling the affiliatesAPI from another package as the following:
@Controller
@RequestMapping("/api/affiliates")
public class AffiliatesController extends BaseController{

    @Resource(name="affiliatesApi")
    AffiliatesApi affiliatesApi = new AffiliatesApi();

         @RequestMapping(value = "/get" )
     public ModelAndView get(@RequestParam(value="id",required=false ) String){
            affiliatesApi.getAll(filter);
        }
}

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

            http://www.springframework.org/schema/security/spring-security-3.0.xsd">
    <security:global-method-security secured-annotations="enabled" />
    <security:http auto-config="true" use-expressions="true"
        access-denied-page="/Management/auth/denied">

        <security:intercept-url pattern="/Management/auth/login"
            access="permitAll" />
        <security:intercept-url pattern="/Management/main/admin"
            access="hasRole('ROLE_EMPLOYEE')" />
        <security:intercept-url pattern="/Management/api/affiliates/**"
            access="hasRole('ROLE_EMPLOYEE')" />

        <security:form-login login-page="/Management/auth/login/"
            authentication-failure-url="/Management/auth/login?error=true"
            login-processing-url="/Management/auth/j_spring_security_check"
            default-target-url="/Management/auth/login?error=false" />
        <security:logout invalidate-session="true"
            logout-success-url="/Management/auth/login/" logout-url="/Management/auth/logout" />
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider
            user-service-ref="customUserDetailsService">
            <security:password-encoder ref="passwordEncoder" />
        </security:authentication-provider>
    </security:authentication-manager>

    <bean
        class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"
        id="passwordEncoder" />

    <bean id="customUserDetailsService" class="com.affiliates.service.CustomUserDetailsService" />

    <bean id="affiliatesApi" class="com.affiliates.api.AffiliatesApi" />

</beans>

This is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
        /WEB-INF/spring-security.xml
        /WEB-INF/applicationContext.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j-myapp.properties</param-value>
    </context-param>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/Management/*</url-pattern>
    </servlet-mapping>

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

</web-app>

This is the excepton i am getting while loading the tom cat:
Mar 7, 2011 5:44:57 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'affiliatesController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'affiliatesApi' must be of type [com.affiliates.api.AffiliatesApi], but was actually of type [$Proxy44]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:300)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4521)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5004)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:4999)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:636)
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'affiliatesApi' must be of type [com.affiliates.api.AffiliatesApi], but was actually of type [$Proxy44]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:349)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:541)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:147)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:297)
    ... 21 more

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

    <!-- Declare a view resolver -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/pages/" p:suffix=".jsp" />

</beans>

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

    <!-- Declare a view resolver -->
    <bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/pages/" p:suffix=".jsp" />

    <!- scan annotated controllers -->
     <context:component-scan base-package="com.affiliates" /

</beans>


text:
Q: No such file or directory when making system calls in Rails production env I'm getting some annoying errors when trying to make system calls in the rails console in a production environment.
Loading production environment (Rails 4.0.2)
2.0.0 :001 > `hostname`
bin/rails: No such file or directory - hostname
 => nil

It works fine in irb.
$ irb
2.0.0-p353 :001 > `hostname`
=> "app-1\n"

Same thing happens on my local machine. rails c is fine but rails c production gives the error above.
ruby -v outputs ruby 2.0.0p353 (2013-11-22 revision 43784) [x86_64-linux]
rails --version outputs Rails 4.0.2
I'm not really sure where to start debugging this so any advice is welcome! I have tried running rake rails:update:bin, based on "bin/rails: No such file or directory" w/ Ruby 2 & Rails 4 on Heroku, but it didn't seem to make a difference. Any ideas?

A: The difference in the PATH is the problem.  You'll need to look into your code or hosting environment to find out how the PATH is being set in the rails app.  It could be in the app itself, or whatever app server is launching the app - details can vary wildly.
Your rails console output:
"$HOME/.rvm/gems/ruby-1.9.3-p429/bin:$HOME/.rvm/bin:$PATH"

indicates that something is trying to add to the path, but it is inserting literal dollar signs instead of expanding the existing environment variable.  For example in a shell script setting a path, if you used the wrong quote symbols you'd see something like what you've got.
export PATH="$HOME/.rvm/gems/ruby-1.9.3-p429/bin:$HOME/.rvm/bin:$PATH"   # right
export PATH='$HOME/.rvm/gems/ruby-1.9.3-p429/bin:$HOME/.rvm/bin:$PATH'   # wrong

I hope this points you in the right direction :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why right join (A[B]) returns NULL if column is of type list since by default it should return NA? I would like to know if I have missed something in the documentation or this is a bug and I should post this on GitHub.
library(data.table)

dt_list <- data.table(id = c(1, 3),
                 col1 = list(c(1, 2, 3), 2))

dt_2 <- data.table(id = c(1, 2, 3))

dt_list[dt_2, on = "id"]
#>    id  col1
#> 1:  1 1,2,3
#> 2:  2       # this is NULL
#> 3:  3     2

dt_not_list <- data.table(id = c(1, 3),
                 col1 = c(5, 6))

dt_2 <- data.table(id = c(1, 2, 3))

dt_not_list[dt_2, on = "id"]
#>    id col1
#> 1:  1    5
#> 2:  2   NA # this is NA
#> 3:  3    6

As you can see in the example above - once we have a NULL and once NA. If this is not a bug - how can I get NA in case of list?
NB: I'm afraid that similar problem exists when I make dcast on data.table if column which contains values is of type list, i.e. missing values are filled by NULL instead of NA, but I'm just signaling this on the margin (I still need to double check this) since I'm not sure if this should be a separate question or not.


text:
Q: jQuery-UI autocomplete does not display choices I have a jQuery-UI autocomplete function that is loaded before the form it applies to is loaded.
$('#groupset').autocomplete({
    source: 'ajax/php/leeruns.php',
    minlength: 2,
    select: function(event, ui) {
        if(ui.item.groupset_id){
            $('#groupsetdesc').val(ui.item.description);
            if(groups.loaded!=ui.item.groupset_id)groups.load(ui.item.groupset_id);
        } else {
            $('#groupsetdesc').val('');
        }
    }
});

The relevant html is:

Groupset Name
    <input name='filename' id='groupset' type='text' value='' >

Groupset Description
    <input name='groupsetdesc' id='groupsetdesc' type='text' value=''>

If I type "gr" into the input box, Firebug tells me that this JSON is returned:
[{"value":"Group_by_Column",
  "groupset_id":"1",
  "description":"12 groups, each of 8 wells from one column",
  "create_date":"2010-02-24 13:27:26"},
 {"value":"Group_by_Row",
  "groupset_id":"2",
  "description":"8 groups of 12 wells, each from 1 row",
  "create_date":"2010-06-02 14:36:33"}
]

I expect to see a faux-dropdown including the entries returned from the autocomplete function.  But no choices show up. This is replicable in IE8 and FF4. Any idea what I'm missing?
jQuery v1.5.1
jQuery-UI 1.8.11

A: This was a beast to solve as the problem wasn't with the autocomplete code at all.  On the same page, I was also loading the jQuery validate plugin .  Version 1.7 of validate has some sort of incompatibility with autocomplete.  Once I upgraded validate to v1.8, autocomplete worked again.
I hope this helps someone else.


text:
Q: Binding ColorPicker in JavaFX to Label Background property Works well for foreground by simply:
    ObjectProperty op = label.textFillProperty();
    ColorPicker cp = new ColorPicker(Color.GRAY);
    ...
    op.bind(cp.valueProperty());

How do I do it for Background - not even sure it is possible, due to the complexity of Background property

A: First, don't use raw types. The code you posted should be
ObjectProperty<Paint> op = label.textFillProperty();
ColorPicker cp = new ColorPicker(Color.GRAY);
...
op.bind(cp.valueProperty());

For the background you can use Bindings.createObjectBinding():
ObjectProperty<Background> background = label.backgroundProperty();
background.bind(Bindings.createObjectBinding(() -> {
    BackgroundFill fill = new BackgroundFill(cp.getValue(), CornerRadii.EMPTY, Insets.EMPTY);
    return new Background(fill);
}, cp.valueProperty());


text:
Q: Cравнение пикселей по цвету в разное время, в одной точке на python мне нужно написать код на Python где при смене пикселей делается скрин и отправляется мне в ЛС. Нужно часть сравнения.
код:
from mss import *
import telebot
import numpy as np
from time import *

# Проба цвета с координ
x=886
y=395
m = mss()
monitor = {
    "left": x,
    "top": y,
    "width": 1,
    "height": 1,
}
# Получаем пиксель с экрана монитора
im = m.grab(monitor)
# Преобразуем этот пиксель в матрицу
im_arr = np.array(im)

  #Проба цвета с координат

monito = {
    "left": x,
    "top": y,
    "width": 1,
    "height": 1,
}
# Получаем пиксель с экрана монитора
img = m.grab(monito)
# Преобразуем этот пиксель в матрицу
img_arr = np.array(img)

print(im_arr)
sleep(5)
print(img_arr)
if np.array_equal(im_arr, img_arr):
    print(1)
else:
    print(0)

Но ошибка:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Помогите пж.

A: Используйте функцию numpy.array_equal для сравнения двух массивов Numpy:
if np.array_equal(im_arr, img_arr):

Хотя, если у вас ровно один пиксел, то можно взять первое (и единственное) значение из каждого массива и сравнивать его:
if im_arr[0] == img_arr[0]:


text:
Q: Problems with .NET 4.5, Entity Framework and Oracle I am working on an application (let's call it A, an ASP.NET MVC3 web site) in .NET 4.0, under Visual Studio 2010 and with Entity Framework and Oracle. Everything goes right.
For an other application (let's call it B), I installed Visual Studio 2012, which installed the new version of the .NET framework. Since, I can not get A working right.
The error I get is : Oracle 11.2.0.3.0  does not support APPLY
I've made some digging and I found a solution : uninstall the .NET framework 4.5 when I need to work on A, and install it back when I need to work on B. This is not very
satisfactory.
It looks like Oracle did not succeed to translate the EF query into an Oracle query. But why ? I still target the same version of the .NET framework (4.0) ...
I am currently trying different ODAC version in order to see if the problem could come from an incompatibility between ODAC and the new version of .NET.
Do you have any other idea of what could cause that and how to fix it ?
Thank you !
Sorry for my english, I am not a native speaker.

A: Oracle does not support CROSS/OUTER APPLY and some queries generated by EF require these operators. See this and this for more details
Having said that - as per the comments there seems to be a regression in EF5/.NET Framework 4.5 where EF started creating Apply nodes in queries for which Apply nodes were not created in EF4. It was previously investigated but apparently this scenario was not covered.
This regression was actually fixed in EF6 (which is probably not extremely helpful since currently there is no Oracle EF6 provider (at least not from Oracle) at this point)


text:
Q: cURL fails to acknowledge function argument I am using a cURL function from a popular comment on the php.net manuals, though the argument for the function, which is to specify a URL, isn't being recognized or initiated. Now when i enable the CURLOPT_URL and specify the URL there in the array, it displays the webpage and the array returns the appropriate information, but I do not want the webpage to be displayed, just return the information in the array, but curl_exec is needed in the sum of it all and that always displays the webpage.
What am i doing wrong?
//defines the function get_web_page
$url = "http://ulrichzukowebtv.comli.com";
    function get_web_page($url)
{
    $options = array(
        //CURLOPT_URL => 'http://ulrichzukowebtv.comli.com',

        CURLOPT_RETURNTRANSFER => true,     // return web page

        CURLOPT_HEADER         => false,    // don't return headers

        CURLOPT_FOLLOWLOCATION => true,     // follow redirects

        CURLOPT_ENCODING       => "",       // handle compressed

        CURLOPT_USERAGENT      => "spider", // who am i

        CURLOPT_AUTOREFERER    => true,     // set referer on redirect

        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect

        CURLOPT_TIMEOUT        => 120,      // timeout on response

        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects

    );

    $ch = curl_init();

    curl_setopt_array($ch, $options);

    $content = curl_exec($ch);

    $err = curl_errno($ch);

    $errmsg = curl_error($ch);

    $header = curl_getinfo($ch);

    curl_close($ch);

    $header['errno'] = $err;

    $header['errmsg'] = $errmsg;

    $header['content'] = $content;

    return $header;

} //end defining function

$curl_data = "var1=60&var2=test";

//call the function
$response = get_web_page($url, $curl_data);

print '<pre>';

//Returns an array containing all the CURL flags specified
print_r($response);

A: try using
CURLOPT_RETURNTRANSFER => false,

what i know, if returntransfer is set to TRUE, the web page is displayed in brower. all the filter and other coding comes after the returntranfer, so you are unable to view them
and dont worry, if it is set to false, still curl will get the page and will do the task whatever you will code..
Hoping This will help you..

A: Try this and see if it does what you want. I haven't actually changed that much, just refactored the code to make it easier to read and added some more descriptive/readable comments to explain what everything does. Where I have changed something, there is a comment explaining what I changed an why.
<?php

  function get_web_page ($url, $params = NULL) {

    // Add a query string to the URL if one was supplied.
    // Previously your second argument $curl_data was unhandled and ignored.
    if (is_array($params) || is_object($params)) {
      // Build a query string from an associative array or object and append to the URL
      $url .= '?'.http_build_query($params);
    } else if ($params !== NULL) {
      // Append scalar values directly to the URL
      $url .= '?'.$params;
    }

    // Define the options for cURL
    $options = array (
      CURLOPT_URL            => $url,     // URL we will be loading
      CURLOPT_RETURNTRANSFER => true,     // Return data instead of outputting it
      CURLOPT_HEADER         => false,    // Omit headers from the return value
      CURLOPT_FOLLOWLOCATION => true,     // Follow redirects
      CURLOPT_ENCODING       => "",       // Handle compressed
      CURLOPT_USERAGENT      => "spider", // Tell the server who we are
      CURLOPT_AUTOREFERER    => true,     // Set referer on redirect
      CURLOPT_CONNECTTIMEOUT => 120,      // Timeout on connect (2 minutes is a very long time...!)
      CURLOPT_TIMEOUT        => 120,      // Timeout on response (2 minutes is a very long time...!)
      CURLOPT_MAXREDIRS      => 10        // Stop after 10 redirects
    );

    // Initialise cURL and set the options we defined above
    $ch = curl_init();
    curl_setopt_array($ch, $options);

    // Make the request
    $content = curl_exec($ch);

    // Fetch the result info into an array
    $result = array();
    $result['options'] = $options;         // The options used for the request
    $result['content'] = $content;         // The body of the response from the server
    $result['header'] = curl_getinfo($ch); // Information about the request, including some headers
    $result['errno'] = curl_errno($ch);    // The numeric error code of the result
    $result['errmsg'] = curl_error($ch);   // The textual error of the result

    // Close the curl handle
    curl_close($ch);

    // Return the result info
    return $result;

  } // End function definition

  // Define the URL to load
  $url = "http://ulrichzukowebtv.comli.com/"; // You need the trailing forward slash if you are loading the root of the domain

  // Define the GET parameters to pass
  // We'll define this as an array to make if easier to read
  $params = array (
    'var1' => 60,
    'var2' => 'test'
  );

  // Call the function
  $response = get_web_page($url, $params);

  // Show the result - if you don't want the page to be output, remove these three lines
  print '<pre>';
  print_r($response);
  print '<pre>';


text:
Q: Consequences of Space Complexity in React Apps I've recently been taking a class on Big O Notation for space and time complexity and I'm trying to apply the concepts to their real world consequences in my day to day job as a React developer. I understand the consequences of time complexity. If a function is a higher complexity the larger that the data set grows the longer it will take to compute, ergo longer load times for the user which no one likes. What I don't understand is the consequences of space complexity in a React App. What are the consequences to either the user or the application if you have a really large data set and you end up using a huge amount of space in the browser?

A: Actually, it is not based specifically on React or any other frameworks. The concept of time complexity and space complexity doesn't depend much on frameworks or languages. That is the concept behind using time and space complexity notations.
Now coming to your question, the answer really depends on the browser you are using to run your React App. Every browser allocates max memory to each tab. If the website uses more than the allocated memory, the browser kills that webpage.
Here is a question about memory limits on StackOverflow--
Javascript memory limit

In Chrome and Chromium OS, the memory limit is defined by the browser,
and you can inspect the limit with the following command in the
Developer Tools command-line by hitting F12:

window.performance.memory.jsHeapSizeLimit 1090519040 On my Windows 10 OS, it is about 1 GB.

On Chrom(e/ium), you can get around the heap size limit by allocating
native arrays:
var target = [] while (true) {
target.push(new Uint8Array(1024 * 1024)); // 1Meg native arrays }
This crashes the tab at around 2GB, which happens very rapidly. After
that Chrom(e/ium) goes haywire, and repeating the test is not possible
without restarting the browser.

In the above link, there is a mention of react and angular

Here are some examples of frameworks with well-known performance
degradation:
..........
React Again,
Immutable collections of JS objects only scale so far.
create-react-app internally uses Immutable.JS, and Immutable.JS can
only create about 500k immutable collections before it dies.

One more side effect the user can experience is overall system lag. The lag may be due to the low RAM available and OS actively swapping to allocate more memory to your app until you reach your max limit before the browser kills it.


text:
Q: Is there a java api that will identify the ipv6 address fd00:: as local/private? I'm looking for a java api that will correctly identify if a given ip address is private or local.  This code seems to work for most ipv4/ipv6 addresses:
    boolean isLocalIp = InetAddress.getByName(ipAddr).isSiteLocalAddress() ||
                        InetAddress.getByName(ipAddr).isLinkLocalAddress() ||
                        InetAddress.getByName(ipAddr).isLoopbackAddress() ;

Particularly, it identifies "fec0::" as a local/private type address but it does not identify, for example, "fc00::" or "fd00::" as local/private type addresses.
Looking at this wikipedia link https://en.wikipedia.org/wiki/Private_network#IPv6:

The address block fc00::/7 is reserved by IANA for Unique Local Addresses (ULA).[2] They are unicast addresses, but contain a 40-bit random number in the routing prefix to prevent collisions when two private networks are interconnected. Despite being inherently local in usage, the IPv6 address scope of unique local addresses is global.
The first block defined is fd00::/8, designed for /48 routing blocks, in which users can create multiple subnets, as needed.

Can anyone help with explaining if there is some false assumption here (e.g. that "fc00::" or "fd00::" should be identified as a local/private ipv6 address) or if there is some other java api that will correctly identify all local/private ip addresses?
Thanks for any feedback/answers!

A:
Can anyone help with explaining if there is some false assumption here (e.g. that "fc00::" or "fd00::" should be identified as a local/private ipv6 address)

Addresses in those blocks are not meant to be routed outside a single administrative domain, but the term "site-local address" means something much more specific.  That now-deprecated term refers specifically to the block fec0::/10.
Addresses in the block fc00::/7 are "unique local addresses" that are not guaranteed to be globally unique, but they are not link-local because they are permitted to be routed between different broadcast domains.

or if there is some other java api that will correctly identify all local/private ip addresses?

I looked briefly at InetAddress.isAnyLocalAddress(), but its docs do not seem to match what you're trying to do.  It doesn't look like the standard library has such a method available.


text:
Q: Number of all graphs that contain at least one $k$-clique There are $n$ vertices and natural number $k$.

How many are there graphs that contain at least one $k$-clique?

I tried to find number of all homomorphism between complete graph $K_{k}$ and graph with $n$-vertices. But i don't know how to do this.
A few weeks ago i asked simillar question that its answer would imply solution for this problem, but i saw that using that method some graphs are counted more than once.

A: Exact results don't seem to be known, even for the simplest nontrivial case $k=3$ (in the case $k=2$, the answer is $2^{\binom n2} - 1$, since all $n$-vertex graphs except the empty graph contain a copy of $K_2$).
For any $k \ge 1$, almost all of the $2^{\binom n2}$ $n$-vertex graphs contain a $k$-clique (that is, the fraction of $n$-vertex graphs that don't approaches $0$ as $n \to \infty$). It is more natural to count the graphs that are $K_k$-free, and subtract the resulting number from $2^{\binom n2}$ to get the answer you want.
Let $f_k(n)$ denote the number of $K_k$-free graphs on $n$ vertices. The $(k-1)$-partite Turán graph on $n$ vertices has approximately $\binom{k-1}{2}(\frac{n}{k-1})^2 = (1 - \frac1{k-1})\frac{n^2}{2}$ edges; this is exact when $k-1 \mid n$. This graph, and every subgraph of this graph, is $K_k$-free; this gives us $2^{(1 - \frac1{k-1})\frac{n^2}{2}}$ distinct $K_k$-free graphs already.
Erdös, Frankl and Rödl (The asymptotic number of graphs not containing a fixed subgraph and a problem for hypergraphs having no exponent) show that this is asymptotically tight in the following sense: we have $$f_k(n) = 2^{(1 - \frac1{k-1} + o(1))\frac{n^2}{2}}$$ for fixed $k$ as $n \to \infty$. Here, $o(1)$ stands for a function approaching $0$ as $n\to \infty$. More is true: the same bound holds if we consider $H$-free graphs for any fixed graph $H$ with chromatic number $k$. So the answer to your question is that asymptotically, $$2^{\binom n2} - 2^{(1 - \frac1{k-1}+o(1))\frac{n^2}{2}}$$ of the $n$-vertex graphs contain at least one $K_k$.


text:
Q: 'Object reference not set to an instance of an object.' in C# linq to SQL this is the line of code where it shows the error
var physician = (from userAccounts in myDb.Physicians
                            where userAccounts.Phy_UserName == txtUserName.Text
                            select userAccounts).FirstOrDefault();

            setFirstName(physician.Phy_FName);

But in my setter I have a pre condition that if it's a null value it wouldn't do anything but how come it still shoes that error? here's my setters code
public void setFirstName(string fName) {
            if (fName == null)
            {
            }
            else {
                firstName = fName;
            }
        }

A: I'm guessing that your physician query returns null.
You're then attempting to call a property, Phy_FName, on a null value.
Checking for a null value in your setFirstName method will not protect you in this case, because Phy_FName isn't what's null, physician is.
As an aside, you may also want to check that fName isn't an empty string in your setFirstName method.  You could check against both conditions by using if (!String.IsNullOrEmpty(fName))

A: Try this:
var physician = (from userAccounts in myDb.Physicians
                            where userAccounts.Phy_UserName == txtUserName.Text
                            select userAccounts).FirstOrDefault();

if(physician != null)
{
  setFirstName(physician.Phy_FName);
}
else
{
  //Throw Error or any any other processing as needed.
}

A: I bet physician is null.  Are you sure you're getting anything back from the query?

A: The Phy_FName property will be evaluated either way so make sure physician isn't null before trying to read its properties.
You'll need to check the value of physician before attempting to use it:
if (physician != null)
    setFirstName(physician.Phy_FName);

A: To clarify on a wrong assumption of my own that maybe you were thinking also:
FirstOrDefault will return defaults if there is one, but the default for an object is null. So, most likely your Linq query is returning a null value for physician. Of which you are then trying to access the Phy_FName.
Here is a SO question that clarifies this more in depth: Specify default value for a reference type


text:
Q: How to control positioning of the KendoUI dropdown and prevent its overlapping of the input text box? I've been seeing one strange thing which I can't solve and it is related to the fact that in my site the drop down portion of the combo box and/or drop down list overlaps/hides the text entry. Is there anyone who faced the same issue and if yes how it was solved ?
<UPDATE>

Link of the repro page showing the overlapping can be found here kendotest.azurewebsites.com
</UPDATE>
Illustration of the problem in 3 pictures...
Here's how it looks on a KendoUI demo web site - proper behavior

And here's the behavior on my site -  faulty overlapping

A: I found an answer
Default MVC 4 template has in site.css next entry for body:
body
{
    background-color: #fff;
    border-top: solid 10px #000;
    color: #333;
    font-size: .85em;
    font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif;
    margin: 0;
    padding: 0;
}

enter code here

When I remove the border-top line the dropdown starts working as it should


text:
Q: Eclipse - Showing how eclipse runs project with java.exe When I run a Java project within the Eclipse IDE, I assume in the background it is simply calling java.exe or javaw.exe with certain parameters, such as the classpath it's using and the actual class it's running.
Is there a way I can make Eclipse show this invocation, with all it's parameters? Ideally I'd like to be able to copy&paste it into a command window to duplicate the running of the project outside of the Eclipse IDE.

A: (Original Answer: February 2011)
Launch your program in debug mode in Eclipse.
You can then see the exact command in the properties of the Debug views (see this thread or this thread)

First run or debug one of the configurations.
  In the Debug view in the Debug perspective, right-click the running process and select "Properties". The command line used to launch the configuration is displayed.

Bug 10820 was about "[java launching] Launch config: show cmd line before launch"... but it is closed as WONTFIX.

Update (March 2012)
bbuser reports in the comment having

had to remove -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:60019 from the command line shown in properties in the Debug view.
  Otherwise I got connection errors.
  Also changing javaw.exe to java.exe might be advisable


text:
Q: ¿como soluciono Notice: Undefined index? queria saber si hay alguna solucion en mi codigo, ya que cuando lo ejecuto me salta el error de Undefined Index... a continuacion les dejo mi codigo, respondan porfavor.

   <TITLE>Conversor de monedas</TITLE>

Conversor de monedas

<?PHP
$enviar = $_REQUEST['enviar'];
   if (isset($enviar))
{
      $tablaconversion = array (
      "dolar" => 0.0124,
      "euros"  => 0.0104,
      "chilenos"   => 9.59,
      "reales"   => 0.0666,
      "guaranies"   => 87.17
      );
   $pesosarg = $_REQUEST['pesosarg'];
   $moneda = $_REQUEST['moneda'];
   if ($pesosarg == "")
      print ("
Debe introducir una cantidad
\n");
   else
   {
      $cantidad = $pesosarg * $tablaconversion ["$moneda"];
      print ("
$pesosarg Peso(s) equivale(n) a $cantidad $moneda
\n");
   }

      print ("
[ Volver ]
\n");
   }
   else
   {
?>

el error que me sale es en la linea 12, es decir en esta $enviar = $_REQUEST['enviar']; la que sale en el principio...

A: Debes comprobar si el indice existe en el array, no si existe la variable a la que tratas de asignarle el contenido:
<?php
$enviar = isset($_REQUEST['enviar']) ? $_REQUEST['enviar'] : null;
if ($enviar) {

    // tu código

} else {
    echo 'no existe el indice "enviar" en $_REQUEST';
}

La línea:
$enviar = isset($_REQUEST['enviar']) ? $_REQUEST['enviar'] : null;

es un ternario, equivale a:
if (isset($_REQUEST['enviar'])) {
    $enviar = $_REQUEST['enviar'];
} else {
    $enviar = null;
}

EN principio $_REQUEST es una superglobal y debe existir aunque sea como array vacío. Puedes ver su contenido con:
var_dump($_REQUEST);

Cuando tienes un array, si no sabes si un indice concreto existe, esta sería la comprobación mínima antes de tratar de acceder a ese indice:
if (isset($arr['indice'])) {
    // ...
}

y si no sabes si ese array existe en ese punto del programa:
if ($arr && isset($arr['indice'])) {
    // ...
}


text:
Q: Remove "All categories" from searchbar dropdown I have been struggling with this and could not find a clear answer online.
Will putting a product search bar I have a dropdown visible with all the categories you can search in.
I would just like to keep only the categories and remove the "all categories" option.
You can see the current search I would like to fix here :
https://compare-tech.fr
Thank you to anyone who will be able to help :)

A: This list can be modified using WooCommerce filters.  However, without a thorough testing I could not find a specific filter to help you. You might check the API for a better answer.
Meanwhile, I have used this CSS snippet to successfully hide the "All Categories" entry from the drop-down selector:
li.option[data-value=''] {
    display: none;
}

This will only prevent users from selecting "All Categories" again.  It will not prevent your page from defaulting to "All Categories".
Hope this is helpful!

A: Thank you for your help !
We are halfway there.
The "All categories" only shows before anything else is selected. So I just need to change the default selected category.
I used this :
function wp_dropdown_categories( $args = '' ) { $defaults = array( 'selected' => 2, );

But it crashed my website.. that might not be it. Can anyone see my mistake ?


text:
Q: Running test with testcontainers as part of a Dockerfile My dockerfile looks something like this:
FROM maven:3-jdk-11-slim
COPY pom.xml .
COPY src src
RUN mvn clean install

That means that part of the build is the execution of the unit tests. Some of the unit tests use a testcontainer. Running mvn clean install on my local machine works fine, but running docker build . -t my-app doesn't because the testcontainers won't start.
(...)
15:54:38.793 [ducttape-0] DEBUG org.testcontainers.dockerclient.DockerClientProviderStrategy - Pinging docker daemon...
15:54:38.794 [ducttape-0] DEBUG com.github.dockerjava.core.command.AbstrDockerCmd - Cmd: org.testcontainers.dockerclient.transport.okhttp.OkHttpDockerCmdExecFactory$1@355cb260
15:54:39.301 [ducttape-0] DEBUG org.testcontainers.dockerclient.DockerClientProviderStrategy - Pinging docker daemon...
15:54:39.301 [ducttape-0] DEBUG com.github.dockerjava.core.command.AbstrDockerCmd - Cmd: org.testcontainers.dockerclient.transport.okhttp.OkHttpDockerCmdExecFactory$1@1c1a1359
15:54:39.469 [main] ERROR org.testcontainers.dockerclient.EnvironmentAndSystemPropertyClientProviderStrategy - ping failed with configuration Environment variables, system properties and defaults. Resolved dockerHost=unix:///var/run/docker.sock due to org.rnorth.ducttape.TimeoutException: Timeout waiting for result with exception
org.rnorth.ducttape.TimeoutException: Timeout waiting for result with exception
(...)

I've seen examples of running docker run with working testcontainers, but how do I make my docker build work?
Help is much appreciated.

A: For future reference: I believe this is simply not possible.
docker run allows you to mount the Docker socket (and thus access the host's Docker daemon) with -v /var/run/docker.sock:/var/run/docker.sock.
docker build doesn't support such an argument.
My workaround will be to modify my Dockerfile to
RUN mvn clean install -Dmaven.test.skip=true and run the unit tests separately.

A: In the docker file, you need to have docker installed to run TestContainer.
I have learned this from one of the existing projects in my workplace. hopefully, it can give you some hints to solve your problem.
RUN curl -fsSL get.docker.com | sh

RUN curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose && \
chmod +x /usr/local/bin/docker-compose

In the docker-compose file,
volumes:
  - /var/run/docker.sock:/var/run/docker.sock
  - /mnt/cachedata/.m2:/root/.m2
  - .:/app


text:
Q: Painting a circular graph by script written in Matlab using Excel. Working with COM\VBA I need to write a script in Matlab, which will read some data from Excel table and paint a circular graph in Matlab's figure. However I was adviced to paint it using Excel facilities. It's not hard to paint a circular graph in Excel but I still haven't found any way to make it work from Matlab, using Matlab's figure. I've already asked this question on other forums but haven't receive any answer. I'll be very grateful for any help.

A: So, I figured out how to use ActiveX control in Matlab's figure.
Firstly, you need to install driver mschrt20.ocx (is free and available to download from the internet). In 32-bit system you must put it in C:/System32 then install it by typing 'regsvr32 mschrt20.ocx' in cosole (as Administrator).
Then create a Matlab figure and put an ActiveX object to it, save. To activate it type to Matlab's interpretator something like this:
 anyone = actxcontrol('MSChart20Lib.MSChart.2');
 anyone.get;
 get(anyone,'ChartData')

Now you could see all the properties of the object. In guide choose the right property 'charType' and make field 'Legend' 'Visible' if you need it.
To paint a pie chart using your ActiveX object you need to set the meaning of it's field 'ChartData'. It's a cell 2xn. Use it as in the example below:
   S = cell(2, 3);
   S(1,: ) = {'first', 'second', 'third'} ; %legend
   S(2,: ) = {1, 10, 5} ; %meanings
   set(handles.activex1,'ChartData', S);

That's how it works. There some other abilities available with ActiveX control.

A: There are a lot of ways to understand your question:
If you want a pie chart, matlab can do that with the 'pie' function:
http://www.mathworks.com/help/techdoc/ref/pie.html
x = [1 3 0.5 2.5 2];
explode = [0 1 0 0 0];
pie(x,explode)
colormap jet

If you wanted to actually plot a circle, then you would use the 'rectangle' command with 'Curvature' settings like this:
rectangle('Position',[1,2,5,10],'Curvature',[1,1],...
          'FaceColor','r')
daspect([1,1,1])
xlim([0,7])
ylim([1,13])

Or you could look at these sites for alternatives for drawing a circle:
http://blogs.mathworks.com/pick/2008/03/21/drawing-a-circle/
http://www.mathworks.com/matlabcentral/fileexchange/2876
If instead you wanted polar axes:
http://www.mathworks.com/help/techdoc/ref/polar.html
figure
t = 0:.01:2*pi;
polar(t,sin(2*t).*cos(2*t),'--r')

The following is the equation for a circle (and so you'll see a red circle overlaid over the black polar plot axes:
polar(t,sin(t).^2+cos(t).^2,'--r')


text:
Q: Get and set JScrollBar position in Java Swing I've a JTable that is a view for a large amount of data retrieved from a database.
For this reason, I thought to show only a part of these data (e.g. first 100 rows) and, when user reach the end of the JTable with the JScrollBar, the JTable will show other rows.
So I'm looking for a mechanism that lets me know when a scrollbar is at the end of the JTable and only at that moment, perform another query. And, when I get the new List, set the scrollbar position to the one before the new query, just for a "continuity" to the user.
Could anyone give some tips to achieve this task?
Thank you in adance

A: As you may saw before, most of the JComponents has models and they are being rendered according to their model. So if you can access the model, you can access the events and the data you need for your purpose.
According to this, JScrollBar also follows this rule and has it's own model. By getting this model (which is a BoundedRangeModel) and adding a ChangeListener you may create what you want for retrieving next page of data from database.
Important point is to find the rule which is ruling over the JScrollBar model. BoundedRangeModel has some properties to which you can refer. Some of them which are important to you in this case are:

*

*valueIsAdjusting

*value

*extent

*maximum
ValueIsAdjusting is the one that indicates are we in the middle of the process of changing the range of BoundedRangeModel or not. To be frank, it means: Is the scrollBar getting dragged?
Other properties value, extent and maximum are the ones you can use to find out whether the ScrollBar reached the end of the range or not. If the Scrollbar reached there, it is the time for retrieving next page of data from database. To indicate this situation the following equation must apply:
value + extent = maximum
Following snippet code may clarify the above explanations:
import java.awt.BorderLayout;

import javax.swing.BoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;

public class LiveJTableDemoFrame extends JFrame {
    private static final int FRAME_HEIGHT = 200;
    private static final int FRAME_WIDTH = 400;
    //
    private JTable table;
    private String[] columnNames;
    private DefaultTableModel tableModel;

    public LiveJTableDemoFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(FRAME_WIDTH, FRAME_HEIGHT);
        //
        columnNames = new String[]{"ID", "A", "B", "C", "D"};
        //
        tableModel = new DefaultTableModel(columnNames, 0);
        table = new JTable(tableModel);
        //
        final JScrollPane p = new JScrollPane();
        p.setViewportView(table);
        p.getVerticalScrollBar().getModel().addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                BoundedRangeModel scModel = p.getVerticalScrollBar().getModel();
                boolean valueIsAdjusting = scModel.getValueIsAdjusting();
                if(!valueIsAdjusting){
                    if(scModel.getValue() + scModel.getExtent() == scModel.getMaximum()){
                        retrieveData();
                    }
                }
            }
        });
        //
        retrieveData();
        //
        this.setLayout(new BorderLayout());
        this.add(p, BorderLayout.CENTER);
    }

    //Dummy method to simulate retrieving data from database
    private void retrieveData(){
        for (int i = 0; i < 10; i++){
            Object[] rowData = new Object[columnNames.length];
            //
            rowData[0] = tableModel.getDataVector().size();
            rowData[1] = "A";
            rowData[2] = "B";
            rowData[3] = "C";
            rowData[4] = "D";
            //
            tableModel.addRow(rowData);
        }
        //tableModel.fireTableDataChanged();
    }

    public static void main(String[] args) {
        new LiveJTableDemoFrame().setVisible(true);
    }
}

[UPDATE]
Another way to do this is to add an AdjustmentListener to the vertical JScrollBar and use the event to get the value and ValueIsAdjusting. Also you have to get the extent and maximum from the JScrollBar's model. Following snippet shows the alternative way:
    final JScrollPane p = new JScrollPane();
    p.setViewportView(table);
    p.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener(){
        @Override
        public void adjustmentValueChanged(AdjustmentEvent e) {
            // here the control if vertical scroll bar has reached the maximum value
            if(!e.getValueIsAdjusting()){
                JScrollBar source = (JScrollBar) e.getAdjustable();
                int extent = source.getModel().getExtent();
                int maximum = source.getModel().getMaximum();
                if(e.getValue() + extent == maximum){
                    retrieveData();
                }
            }

        }
    });

Good Luck.


text:
Q: 'charmap' codec can't encode character '\ud64d' I have written a python code to read from a log file and save some of the infos from that log file to a text file
This is the log.txt file
2022-10-12 18:15:22.992 0026/? I/AsrDecActor25: channels=1, size=82434
2022-10-12 18:15:22.992 0026/? I/AsrDecActor25: waiting asr-core ready: 12 secs
2022-10-12 18:15:23.058 0199/? I/AsrDecActor27: asr state: START, true
2022-10-12 18:15:23.058 0199/? I/AsrDecActor27: asr state 2: START
2022-10-12 18:15:23.058 0199/? I/AsrDecActor27: end of decoding 57 true 0
NEC Input :secure folder app close it
NEC Replacement suggestion :Secure folder
NEC Input Before Replace : secure folder app close it
NEC Matching Word : secure folder app
Replaced Word  : Secure folder
NEC Output After Replace : Secure folder close it
Changes : 1
2022-10-12 18:15:23.060 0199/? I/LangPackActor: eASR [NEC] Run completed, Time: 2 ms
PostProcessSubstitutions::Output of question mark processing: secure folder uninstall Kare
[eITN] Input:Secure folder uninstall kare OutputSecure folder uninstall Kare
2022-10-12 18:15:23.069 0199/? I/LangPackActor: eASR [Timestamp] getTimestamp starts
2022-10-12 18:15:23.069 0199/? I/LangPackActor: eASR string2IntegerList 14 20 23 32 36
2022-10-12 18:15:23.069 0199/? I/LangPackActor: eASR string2IntegerList 14 20 23 32 36
2022-10-12 18:15:23.069 0199/? I/LangPackActor: eASR levenshteinMapping
2022-10-12 18:15:23.069 0199/? I/LangPackActor: eASR new ASRResult
2022-10-12 18:15:23.091 0021/? I/AsrDecActor26: decoding

Now I have written a code to extract the lines with beginning "NEC Input Before Replace", "NEC Matching Word", "Replaced Word" and "NEC Output After Replace" such that my output.txt file looks like this
NEC Input Before Replace : secure folder app close it
NEC Matching Word : secure folder app
Replaced Word  : Secure folder
NEC Output After Replace : Secure folder close it

The code I have written for the same is
#!/usr/bin/env python
f = open('log.txt','r',encoding='utf-8')
f1 = open('output.txt', 'a')

doIHaveToCopyTheLine=False

for line in f.readlines():
    if 'NEC Input Before Replace' or 'NEC Matching Word' or 'Replaced Word' or 'NEC Output After Replace' in line:
        f1.write(line)

f1.close()
f.close()

But this code is throwing me this error
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
Input In [14], in <cell line: 7>()
      7 for line in f.readlines():
      8     if 'NEC Input Before Replace' in line or 'NEC Matching Word'  or 'NEC Output After Replace' in line:
----> 9         f1.write(line)
     14 f1.close()
     15 f.close()

File D:\Anaconda\lib\encodings\cp1252.py:19, in IncrementalEncoder.encode(self, input, final)
     18 def encode(self, input, final=False):
---> 19     return codecs.charmap_encode(input,self.errors,encoding_table)[0]

UnicodeEncodeError: 'charmap' codec can't encode character '\ud64d' in position 20: character maps to <undefined>

But when I remove 'Replaced Word' and 'NEC Output After Replace' from the condition statement if 'NEC Input Before Replace' in line or 'NEC Matching Word' or 'Replaced Word' or 'NEC Output After Replace' in line:, then the code works fine.
Anyone knows what is the issue and how it fix this?


text:
Q: Ingress, rewrite-target, frontend and API same URL. Version 0.22.0+ I am tying to put together a setup like this :

*

*example.com   #frond end

*example.com/api

*example.com/authentication

And obviously each of them separated applications and should be able to continue their own path , ex.   http://example.com/api/v1/test?v=ok
Right now I have a yaml  like this:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
 name: test-ingress
 annotations:
   nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
 rules:
 - http:
     paths:
     - path: /
       backend:
         serviceName: frontend-service
         servicePort: 80
     - path: /api(/|$)(.*)
       backend:
         serviceName: backend-service
         servicePort: 80
     - path: /authentication(/|$)(.*)
       backend:
         serviceName: identityserver-service
         servicePort: 80

/api  and /authentication  behave the way I want, but the sub path for front end is not working.  So for example   http://example.com/css/bootstrap.css is not found.
So far I've tried to
1- add (/|$)(.*) at the and of front end path
2- add a copy of front end path with the same backed and  port  and path of /.*
None of them solved the problem.
Here is the describe result:
Name:             test-ingress
Namespace:        default
Address:          127.0.0.1
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
  Host        Path  Backends
  ----        ----  --------
  *
              /                          frontend-service:80 (10.1.80.38:80,10.1.80.43:80,10.1.80.50:80)
              /api(/|$)(.*)              backend-service:80 (10.1.80.39:80,10.1.80.42:80,10.1.80.47:80)
              /authentication(/|$)(.*)   identityserver-service:80 (10.1.80.40:80,10.1.80.41:80,10.1.80.45:80)
Annotations:  nginx.ingress.kubernetes.io/rewrite-target: /$2
Events:
  Type    Reason  Age                 From                      Message
  ----    ------  ----                ----                      -------
  Normal  UPDATE  43s (x14 over 13h)  nginx-ingress-controller  Ingress default/test-ingress

PS :   I'vd found a few answers that seems to be older than Version 0.22.0 and not working anymore ex .  kubernetes ingress with multiple target-rewrite

A: The problem in your case lies with incorrect regular expression.
The $ operator matches the end of the string or end of a line if the multiline flag is enabled.  With first group you are capturing / or $ but your string does not end and there is not match.
I tested this and it works with this regex:
 paths:
 - path: /()(.*)
   backend:
     serviceName: frontend-service
     servicePort: 80


text:
Q: Is Fisher's exact test right for this problem? Let's say I have 4 plants and I measure something under 2 conditions. For example:
The entries in the table show how many times I saw something under condition (C1 or C2) for plant (P1, P2, P3 or P4).

     P1,  P2,  P3,  P4
C1    0   20    0   19
C2  100   80  180  150

Now I would like to answer the question "what is the probability that these 39 times of seeing something is unevenly distributed between these 4 plants"?
I am much interested in observation like this, rather than, say:

     P1,  P2,  P3,  P4
C1   25   20   15   19
C2  100   80  180  150

Is it right to use Fisher's exact test for this? I just extended the question from a 2*2 table to 2*4.

A: There's no reason you can't apply Fisher's exact test to this problem. Or you could use a standard chi-squared test for independence, as the expected cell counts aren't that small.
Neither approach will answer the question "what is the probability that these 39 times of seeing something is unevenly distributed between these 4 plants" though. That would require a fully Bayesian analysis.


text:
Q: Jenkins: From Gradle 2.2.2.pom com.android.tools.build:gradle:2.2.2 I am setting up Jenkins for my Android projects automated build.
Since VM has Internet disabled, I downloaded gradle.2.2.2.pom from:
https://jcenter.bintray.com/com/android/tools/build/gradle/2.2.2/gradle-2.2.2.pom

In my build.gradle I have linked the gradle-2.2.2.pom file like this:
buildscript {
    repositories {
        jcenter{
        url file("C:/JenkinsSetup/gradle_2.2.2.pom_file/gradle-2.2.2.pom")
    }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

But, still I am getting this error:
> Could not resolve all dependencies for configuration ':classpath'.
   > Could not find com.android.tools.build:gradle:2.2.2.
     Searched in the following locations:
         file:/C:/JenkinsSetup/gradle_2.2.2.pom_file/gradle-2.2.2.pom/com/android/tools/build/gradle/2.2.2/gradle-2.2.2.pom
         file:/C:/JenkinsSetup/gradle_2.2.2.pom_file/gradle-2.2.2.pom/com/android/tools/build/gradle/2.2.2/gradle-2.2.2.jar
     Required by:
         :LocationSensing:unspecified

Any idea what should I do next? I have downloaded and linked the .pom file build system asked me.

A: you should put gradle-2.2.2.pom to the path:

C:/JenkinsSetup/gradle_2.2.2.pom_file/gradle-2.2.2.pom/com/android/tools/build/gradle/2.2.2/

if you use:

    url file("C:/JenkinsSetup/gradle_2.2.2.pom_file/gradle-2.2.2.pom")


text:
Q: Adding Tuple as Thread safe input in Parallel.Foreach loop in C# I need help with Parallel.Foreach loop in C#. I have a feeling that sometimes "result" tuple is rewritten by other parallel thread so there is no correct output. It doesn't occur often, but sometimes it spits out bad result.
Scenario: Network device is accessible, everything works fine output is stored in the "result" tuple. But then I when I work with the "result" further, the tuple is sometimes empty even though the output was stored there. Could it be that other thread in parallel processing is erasing the "result" ? Can I make it more threadsafe ?
Tuple <string, int> result;

/*loop through all hosts and execute commands -> In paralel*/
        Parallel.ForEach(devices, (hostname, state) =>
        {
            //because we have multithreading every thread must differentiate -> based on hostname (first value in list) - key is also hostname
            device_checked_with_all_parameters.Add(cleaned_hostname, new List<string> { DateTime.Now.ToString("d.M.yyyy HH:mm:ss"), cleaned_hostname, "", "", "", "" });

                //if stop is pushed break all threads
            if (token.IsCancellationRequested)
            {
                canceled_loop = 1;
                state.Break();
            }

            //PERFORM ACTION ON DEVICE - STORE OUTPUT IN RESULT
            result = core.connect_to_device_and_perform_actions(device_checked_with_all_parameters[cleaned_hostname][1], config_vlan_ids_based_on_type);

         });


text:
Q: Is O(N^2) nested for loop as O(N) while loop possible? Am I correct in saying that this code will execute in O(N) time? This is to iterate through a map< int, vector< int > >.
  int counter = 0;
  unsigned int u = 0;
  unsigned int v = 0;
  bool notDone = true;
  while (notDone) {
    if (u < map.size()) {
      if (v < map.at(u).size()) {
        if (map.at(u)[v] == -1) {
          ++v;
        }
        else {
          ++counter;
          ++v;
        }
      }
      else {
        v = 0;
        ++u;
      }
    } else {
      notDone = false;
    }
  }

A: If N is the number of map entries, and TV is the sum of the sizes of all the vectors, then your program is O(N + TV) regardless of whether it is written as a "while" or a nested "for".
If N is the number of map entries and MV is the mean of the sizes of all the vectors, then your program is O(N * MV) regardless of whether it is written as a "while" or a nested "for".
UPDATE: Commenter Tim notes that map.at is O(lg N) in the size of the map, and it is called O(N) times, so that makes the actual complexities O(N * lg N + TV) and O(N * lg N * MV) respectively. Thanks!
I do not know enough about the C++ standard library to say if there is a more efficient way; I would suspect that an O(1) iterator over the map exists. If it does, then you could use it rather than your index to iterate the map, and the lg N term would vanish again.

A: In a comment you said,

I have a map of vectors and I want to loop through every element in the map and every element of the vector, but I'm trying to do it in O(N) time.

That is not possible.
If you have M elements in the map and N elements in each of the vectors, you have M*N elements all together. There is no way you can iterate over them in O(N) time.

A: You iterate over the map of length N, and in each loop you iterate over a vector of length M. Assuming all vectors have the same length, your algorithm will run in O(N*M).


text: Q: How to do OAuth authentication in Twitter using fabric This is the first time I am doing social integration as a part of an assignment given to me. I am trying to make a twitter like app. But I have a query. To access Twitter API, the documentation says I need oAuth tokens. What I am getting is object of TwitterAuthToken. Is it the same as OAuth token? I am using fabric for developing this app. Kindly help.


text:
Q: Calling async function in a Razor View using a Custom View Base In my MVC5 application some view components do not get rendered in RAZOR if the user does not have the permissions for it.
The permissions are fetched using a Repository pattern which is completely async as the rest of my application.
I have implemented a IPermission Service that has the following methods
public interface IPermissionService
{
    Task<bool> IsUserAllowed(string moduleName, string action);

    Task<bool> IsUserAdmin();
}

Now to be able to use this service in my view I have written a custom View Base which inherits from the WebViewPage as follows:
public abstract class ViewBase<T> : WebViewPage<T> where T : class
{
    public IPermissionService Permissions;

    public override void InitHelpers()
    {
        base.InitHelpers();
        Permissions= DependencyResolver.Current.GetService<IPermissionService>();
    }

    public override void Execute()
    {

    }
}

I am not able to use these async functions from my View as await doesnt work there. I dont want to create a separate non-async implementation of the data repositories. Also I feel calling a async function without await by doing something like Task.Result() also is not a good idea as per call async method without await #2
Is there a better way of doing this?

A: You could try decoupling loading of these resources from the loading of your view.
Your view itself should load all items that all users have permission to.
As the view is rendered on client-side, send an async ajax call back to an Action on the server that will evaluate what the user has permission to see, and will return appropriate data/models for client-side loading.
This way you dont have to worry about running async server code in the view, and still have complete control of what the user can see (which is also async)

A: This seems like a good candidate for dependency injection. For example, check out Autofac's suggestions for property injection:
http://docs.autofac.org/en/latest/integration/mvc.html#enable-property-injection-for-view-pages


text:
Q: Ardupilot - Dronekit Setting the Current Location of the Vehicle Hello everybody, hope you are all doing well.
I am doing in a project in which I receive GPS data (Longitude, and Latitude) from an Android device via an SQL server. What I am trying to do is to send this Longitude - Latitude data to my SITL vehicle in Ardupilot. I thought about using Dronekit Python API as such:
from dronekit import connect, VehicleMode

import time
import mysql.connector
import time

#--- Start the Software In The Loop (SITL)
import dronekit_sitl
#
sitl = dronekit_sitl.start_default()   #(sitl.start)
#connection_string = sitl.connection_string()

mydb = mysql.connector.connect(
  host="******",
  user="******",
  password="*****",
  database="koordinat"
)
mycursor = mydb.cursor()

#--- Now that we have started the SITL and we have the connection string (basically the ip and udp port)...
print("Araca bağlanılıyor")
vehicle = connect('tcp:127.0.0.1:5762', wait_ready=False, baud = 115200)
vehicle.wait_ready(True, raise_exception=False)

#-- Read information from the autopilot:
#- Version and attributes
vehicle.wait_ready('autopilot_version')
print('Autopilot version: %s'%vehicle.version)

#- Does the firmware support the companion pc to set the attitude?
print('Supports set attitude from companion: %s'%vehicle.capabilities.set_attitude_target_local_ned)

vehicle.mode = VehicleMode("GUIDED")
vehicle.armed = True

while(True):

    mycursor.execute("SELECT * FROM koordinat WHERE 1")

    location = str(mycursor.fetchall())
    location = location.split(",")

    location[0] = location[0].replace("[", "")
    location[0] = location[0].replace("(", "")
    location[0] = location[0].replace("'", "")

    location[1] = location[1].replace("[", "")
    location[1] = location[1].replace(")", "")
    location[1] = location[1].replace("'", "")
    location[1] = location[1].replace(")", "")

    # Converting the longitude and latitude to float, before assigning to the vehicle GPS data:

    location[0] = float(location[0])
    location[1] = float(location[1])

    # Setting the location of the vehicle:

    vehicle.location.global_frame.lat = location[0]
    vehicle.location.global_frame.lon = location[1]

    print('Konum:', str(vehicle.location.global_frame.lat)+str(","), str(vehicle.location.global_frame.lon)+str(","), str(vehicle.location.global_frame.alt))

    #- When did we receive the last heartbeat
    print('Son bilgi gelişi: %s'%vehicle.last_heartbeat)

    time.sleep(1)

However, when I check from the SITL and Mission Planner (also from the print statement from my code) the location does not change; the simulator simply ignores those commands sent by the Dronekit. Is there a working method to accomplish what I am trying to do? I tried to change the sim_vehicle.py script which I use to start the simulation. But I was only able to change the starting/home location of the vehicle. I was not able to change the current location of the vehicle on SITL and Mission Planner.

A: This is incorrect. You're modifying the attribute of the vehicle object that's connected to the SITL, not sending any commands to the actual autopilot.
vehicle.location.global_frame.lat = location[0]
vehicle.location.global_frame.lon = location[1]

What you want to do is set the mode to GUIDED and use the simple_goto function in dronekit to make the drone move to lat/lon/alt coordinates.
Otherwise, you can also send this MAVLink command SET_POSITION_TARGET_GLOBAL_INT to guide it.


text:
Q: ERROR that DataTable is not a function I am getting an error

__WEBPACK_IMPORTED_MODULE_1_jquery___default(...)(...).DataTable is
  not a function

I cannot understand why this error is coming as i am new to this.
This is my Global.js file where i written the jQuery code.
    import React, { Component } from 'react';
    import $ from 'jquery';

    function filterGlobal () {
        $('#example').DataTable().search(
            $('#global_filter').val(),
            $('#global_regex').prop('checked'),
            $('#global_smart').prop('checked')
        ).draw();
    }

    $(document).ready(function() {
        $('#example').DataTable();

        $('input.global_filter').on( 'keyup click', function () {
            filterGlobal();
        } );

    } );

    class Global extends React.Component {
      constructor(props) {
        super(props);
      };

      render() {
        return (

                  Target
                  Search text

                  Global search
                  <input type="text" className="global_filter" id="global_filter" />
                  <input type="checkbox" className="global_filter" id="global_regex" />
                  <input type="checkbox" className="global_filter" id="global_smart" defaultChecked="checked" />

                  Name
                  Position
                  Office
                  Age
                  Start date
                  Salary

                  Tiger Nixon
                  System Architect
                  Edinburgh
                  61
                  2011/04/25
                  $320,800

                  Shad Decker
                  Regional Director
                  Edinburgh
                  51
                  2008/11/13
                  $183,000

                  Michael Bruce
                  Javascript Developer
                  Singapore
                  29
                  2011/06/27
                  $183,000

                  Donna Snider
                  Customer Support
                  New York
                  27
                  2011/01/25
                  $112,000

                  Name
                  Position
                  Office
                  Age
                  Start date
                  Salary

        );
      }
    }

    export default Global;

This is my index.html file where my css and javascripts links and scripts are placed.I had kept some jQuery scripts is there any mistake in that scripts.
    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.min.css">
    <link rel="stylesheet" href="https://npmcdn.com/react-bootstrap-table/dist/react-bootstrap-table-all.min.css">
    <link rel="stylesheet" href="/css/custom.css">
    <link rel="stylesheet" href="selectbox.min.css">
    <title>React App</title>

      You need to enable JavaScript to run this app.

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">

My error

Can anyone help me why this error occured.
Thank you.

A: Just add

import DataTable from 'datatables.net';

after

import $ from 'jquery';

on your Global.js file
So the first three lines will be:

import React, { Component } from 'react';
import $ from 'jquery';
import DataTable from 'datatables.net';

A: First refer to the site below to install the datatable. That is
npm install datatables.net

https://www.npmjs.com/package/datatables.net
Then make sure you have these in your component file.
import $ from "jquery"
import DataTable from 'datatables.net';

And these are in your public/index.html file
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"
/>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">


text:
Q: How do cookies play role/helps in session management in PHP? I studied basic concepts of Cookies in PHP but couldn't get how they are used or helpful in Session Management.
Can someone please explain me how the cookies are used in session management or session processing specifically in PHP only?
If you could accompany your answer with some working "VALID" example it would be good for understanding.
Thanks.

A:
Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users.

You could use a cookie for a login system that has the option of "Remember me" for example. Once the login has been validated, you could store a cookie auto_login with the encrypted id of the user. Then next time if the user access the website and the session is over, you could auto login for him with the cookie's id.
I'm not saying it's the right way to do it; just a quick example.


text:
Q: Copy docker configuration to other PC I'm using docker composer in order to run ChirpStack on my Windows 10 machine. I need to reinstall operating system, but how to keep working ChirpStack docker system without creating new one?

A: It is not possible. Once you remove the existing OS docker will no longer be able to communicate with the kernel. Even if you reinstall the OS it would not be the same. You will have to remove docker and install it again. Unless you are using persistent volumes, the docker container data will also get erased. You can check this by having a snapshot or a recovery point before reinstalling the OS.


text:
Q: How to I make python curses application pipeline friendly? I am writing a python application that is intended to be used interactively inside unix pipelines. The application should fire up a curses based terminal UI, and based on user interaction, write to the standard output only right before exiting.
Typical usage would be that of a typical pipeline:
foo_command | my_application | sink_app

The problem I am having is that python curses library sends all sorts of things to stdout while the app is running. Furthermore, sink_app starts executing while my_application is running.

*

*How to I prevent curses from polluting stdout?

*How do I buffer the output and control when I want to flush it?

*Is it possible to control when sink_app starts executing and when it stops accepting input?

From what I gather, I need to save a reference to the stdout file descriptor so I can later write to it. And pass another fd (which one?) to ncurses. Supposedly through newterm(), but this isn't available on python curses binding.

A: You could do this (setup a curses application in a pipeline) by using the newterm function to directly open the terminal for managing the screen, while reserving stdout for the pipeline.  The dialog program does this.
But the Python curses interface does not have newterm (it only has initscr, which uses stdout for the screen...), and while there are probably workarounds (in Python, juggling the I/O streams), it hasn't been addressed in any of the answers on this forum.

A: As suggested, juggling input streams. This is not well tested, but appears to be on the right track...
import os

# back up the piped stdin
mystdin_fd = os.dup(0)

# open the terminal for reading keyboard events
termin = open("/dev/tty")

# replace stdin with the terminal, so curses initscr() and getch() work
os.dup2(termin.fileno(), 0)

# initialise curses - https://docs.python.org/3/howto/curses.html
...

# read from the piped stdin
mystdin = open(mystdin_fd, 'r')
for line in mystdin:
    ...


text:
Q: gcc -o how to name object file This command
gcc file.c -c

outputs me this
file.o

how to run above command so it outputs me object file with specified name for example file.dbg.o ?

A: That's it:
    gcc -o file.dbg.o -c file.c


text:
Q: Parsing XML with custom schema/ namespace I wrote an XSD for an XML configuration file like so:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:t="http://www.foo.com/schemas/datatransfer"
           targetNamespace="http://www.foo.com/schemas/datatransfer"
           attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xs:element name="transferGroups">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="transferGroup" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="connectionString" type="xs:string" />
              <xs:choice minOccurs="1" maxOccurs="1">
                <xs:element name="script" minOccurs="0" maxOccurs="1">
                  <xs:complexType>
                    <xs:attribute name="path" type="xs:string" use="required" />
                    <xs:attribute name="fileName" type="xs:string" use="required" />
                    <xs:attribute name="useCompression" type="xs:boolean" use="required" />
                  </xs:complexType>
                </xs:element>
                <xs:element name="table" minOccurs="0" maxOccurs="1">
                  <xs:complexType>
                    <xs:attribute name="name" type="xs:string" use="required" />
                    <xs:attribute name="fileName" type="xs:string" use="required" />
                    <xs:attribute name="useCompression" type="xs:boolean" use="required" />
                  </xs:complexType>
                </xs:element>
                <xs:element name="tables" minOccurs="0" maxOccurs="1">
                  <xs:complexType>
                    <xs:sequence>
                      <xs:element name="table" maxOccurs="unbounded" minOccurs="1">
                        <xs:complexType>
                          <xs:attribute name="name" type="xs:string" use="required" />
                          <xs:attribute name="fileName" type="xs:string" use="required" />
                          <xs:attribute name="useCompression" type="xs:boolean" use="required" />
                        </xs:complexType>
                      </xs:element>
                    </xs:sequence>
                  </xs:complexType>
                </xs:element>
              </xs:choice>
              <xs:element name="format">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="addHeaderRow">
                      <xs:complexType>
                        <xs:attribute name="value" type="xs:boolean" use="required" />
                      </xs:complexType>
                    </xs:element>
                    <xs:element name="columnsDelimitedBy">
                      <xs:complexType>
                        <xs:attribute name="value" type="xs:string" use="required" />
                      </xs:complexType>
                    </xs:element>
                    <xs:element name="rowsDelimitedBy">
                      <xs:complexType>
                        <xs:attribute name="value" type="xs:string" use="required" />
                      </xs:complexType>
                    </xs:element>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
              <xs:element name="transferSite">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="protocol">
                      <xs:complexType>
                        <xs:attribute name="value" type="xs:string" use="required" />
                        <xs:attribute name="address" type="xs:string" use="required" />
                        <xs:attribute name="port" type="xs:unsignedByte" use="required" />
                      </xs:complexType>
                    </xs:element>
                    <xs:element name="credentials">
                      <xs:complexType>
                        <xs:attribute name="userName" type="xs:string" use="required" />
                        <xs:attribute name="password" type="xs:string" use="required" />
                      </xs:complexType>
                    </xs:element>
                    <xs:element name="destinationFolder">
                      <xs:complexType>
                        <xs:attribute name="value" type="xs:string" use="required" />
                      </xs:complexType>
                    </xs:element>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="useCompression" type="xs:boolean" use="required" />
            <xs:attribute name="fileName" type="xs:string" use="optional" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

I generated (then modified) the schema from an XML file I designed in Visual Studio like so:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<transferGroups>
  <transferGroup useCompression="false" >
    <connectionString>DSN=MyDSN;uid=foo;password=bar;</connectionString>
    <tables>

    </tables>
    <format>
      <addHeaderRow value="true"/>
      <columnsDelimitedBy value="|" />
      <rowsDelimitedBy value="\r\n" />
    </format>
    <transferSite>
      <protocol value="FTP" address="localhost" port="21" />
      <credentials userName="anonymous" password="test@myserver.com" />
      <destinationFolder value="/" />
    </transferSite>
  </transferGroup>
</transferGroups>

In practice, I made a configuration file like so:
<transferGroups xmlns="http://www.foo.com/schemas/datatransfer">
  <transferGroup useCompression="false" >
    <connectionString>some connection string</connectionString>
    <tables>

    </tables>
    <format>
      <addHeaderRow value="true"/>
      <columnsDelimitedBy value="|" />
      <rowsDelimitedBy value="\r\n" />
    </format>
    <transferSite>
      <protocol value="FTP" address="ftp.someplace.com" port="21" />
      <credentials userName="foo" password="bar" />
      <destinationFolder value="subFolder1" />
    </transferSite>
  </transferGroup>
</transferGroups>

I did not realize, however, that specifying a namespace/ schema changed the way to parse the file in an XmlDocument.  For example, this segment of code would capture an XmlNodeList of one XmlNode if I didn't specify the schema, but once the schema is specified, no nodes match:
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(myXml);
var transferGroupNodes = xmlDoc.SelectNodes("//transferGroups/transferGroup")
    .OfType<XmlNode>();

How would I collect the transferGroup node for parsing in this situation? I cannot find a decent example online to show me how to do this.

A: Schema has nothing to do with your problem - you have nodes with namespaces, so need to change XPath's accordingly. As Jon Skeet points out LINQ to XML will make it easier to use, but still you need to select nodes with correct namespaces.
The question of using namespaces in XPath is covered multiple times - start with the FAQ answer - Using Xpath With Default Namespace in C#.
Cheating way of ignoring namespaces  with XPath: "//*[ local-name() = 'justName']".


text:
Q: Windows Kerberos application issues and Event 5071 We're experiencing issues with a third-party application running on Windows 2016 that uses Kerberos and SSPI (Windows Security Support Provider interface) where the vendor has suggested this could be related to Kerberos authentication failures. The service runs as a domain service account. In the Windows 2016 domain controller security logs we're seeing Event ID 5071 failure audits with the description:

Key access denied by Microsoft key distribution service

This all worked in the past and similar configuration works in other parts of our system (different service accounts, servers, domain controllers). In fact, we have a full hardware level clone of our setup as a test system and the issue doesn't exist there.
There is limited information online that we've been able to find on this particular event.  We are in the process of performing all the normal Kerberos advanced troubleshooting so don't need assistance from that angle. We have a ticket open with Microsoft so will post their response here.
Has anyone encountered this event previously and has any insight into the potential cause(s)?


text:
Q: Using the people picker how to get the typed/selected users to save them somewhere? Using the people picker how to get the typed/selected users to save them somewhere?
I already know how to create a people picker in an application page, however after the user types 10 users or groups, I need to know the ids or some important info so I can save it in an internal list or something.
I should be able to know if he typed a user or a group also

A: //First you should validate users (myppl is the people editor control id)
myppl.Validate();

if(myppl.IsValid)
{
 // Get list (we will create new list item and add these people to one field of that list item)
 SPList myList = SPContext.Current.Web.GetList("site/myListURL");

 // Create list item
 SPContentType itemtype = myList.ContentTypes["MyContentType"];
 SPListItem newItem = myList.Items.Add();
 newItem["ContentTypeId"] = itemtype.Id;

 // This is where we shall gather all principals, to be added later to the list item
 SPFieldUserValueCollection userPrincipals = new SPFieldUserValueCollection();

 foreach (PickerEntity person in myppl.ResolvedEntities)
 {
  // Add everyone to the site with full permissions
  SPPrincipal pr = mySPWeb.EnsureUser(person.Key) as SPPrincipal;
  AddPrincipalRoleToSite(pr, SPRoleType.Administrator, myList.ParentWeb);

  // Populate userPrincipals so we can use it below
  SPUser usr = newItem.Web.EnsureUser(person.Key) as SPUser;
  userPrincipals.Add(new SPFieldUserValue(newItem.Web, usr.ID, usr.Name));
 }

 // Finally set the value of the list item field that will contain all the users
 newItem["PersonColumnInternalName"] = ownerPrincipals;

 // All done, save item
 newItem.Update();
}

public static void AddPrincipalRoleToSite(SPPrincipal entity, SPRoleType role, SPWeb web)
{
    SPRoleAssignment roleAssignment = new SPRoleAssignment(entity);
    SPRoleDefinition byType = web.RoleDefinitions.GetByType(role);
    roleAssignment.RoleDefinitionBindings.Add(byType);
    web.RoleAssignments.Add(roleAssignment);
}

You might be able to optimize the code within for loop (cast SPPrincipal into SPUser or something), I combined the code from few different projects of mine so it might not be 100% optimal.


text:
Q: Detecting subset of high sensitivity corresponding to genotype Background
There is a data set from a clinical trial, involving about 1000 patients received an behavior intervention. The intervention is supposed to affect a variable x1, and the change in x1 results the change in the response variable y.
The data also contains the information of several(>10) snips for each patient.
Analysis planned
Given a subset of patients, fit y=beta1*x1+beta2*other variable+…
I would like to find certain combinations of genotype, such that the patients with these genotypes have significantly high beta1.
For each subset (i.e. one geno combination), the p-value of beta1 is calculated and I plan to perform some adjustment to them since all p's are correlated.
What I did below is intended to see if the linear model, with selected variables, is appropriate.

Original question (before comments and edits)
I performed thousands of tests and obtained p-values. Then I did two-sided uniform KS test of the p-values, the result claimed it's uniform. So does it mean that my model are wrong? Because I expect more small p-values near 0.
This is a preliminary step before correcting the multiplicity.

The ks test:
One-sample Kolmogorov-Smirnov test

D = 0.0493, p-value = 1.388e-06

alternative hypothesis: two-sided


text:
Q: How do you get the instance id from a TextInput in the on_text function? I am trying to make a sudoku game in Kivy 1.10.1.  I have a screen with 81 TextInputs that simulate the board in a screen like this
<NewGame>
    GridLayout:
        cols: 9
        rows: 9
        TextInput:
            id: "row_0_col_0"
            on_text: root.set_value(self)
        TextInput:
            id: "row_0_col_1"
            on_text: root.set_value(self)
        ....
        TextInput:
            id: "row_8_col_8"
            on_text: root.set_value(self)

My gamy.py is
class NewGame(Screen):
    new_board = Board(board_data=None)

    def set_value(self, instance):
        Logger.info(f"Self.id is {self.id}")
        Logger.info(f"Instance.id is {instance.id}")

However these print Self.id is None Instance.id is None.  Ultimately I want to store some data in the text input labels, mainly what row/col they represent as I need that to interact with the Board class I created.  How can I get the id?  Or, perhaps add a custom property representing the row and column number of each label to be used in my on_text callback function?

A: You can add row and col attributes to the TextInputs like this:
<NewGame>
    GridLayout:
        cols: 9
        rows: 9
        TextInput:
            id: row_0_col_0
            row: 0
            col: 0
            on_text: root.set_value(self)
        TextInput:
            id: row_0_col_1
            row: 0
            col: 1
            on_text: root.set_value(self)
        TextInput:
            id: row_8_col_8
            row: 8
            col: 8
            on_text: root.set_value(self)

Then the set_value() method can be:
def set_value(self, instance):
    id = "row_" + str(instance.row) + "_col_" + str(instance.col)
    print('id =', id)

Note that the id values are typically not surrounded by "".


text:
Q: during install pod i am getting this error Failed to extract git version from git --version. Instead I see:
xcrun: error: active developer path ("/Users/mcbook/Downloads/Xcode.app/Contents/Developer") does not exist
Use `sudo xcode-select --switch path/to/Xcode.app` to specify the Xcode that you wish to use for command line developer tools, or use `xcode-select --install` to install the standalone command line developer tools.
See `man xcode-select` for more details.

A: Like all macOS apps, the Xcode app is represented in the file system as a folder, even though in Finder we see it as an icon.
In Xcode's case its main app folder contains subdirectories that include some command line development tools that are necessary when installing apps that need to be compiled.
When you first run Xcode, it registers the location of this subfolder for you. Unfortunately, it looks like you first ran Xcode when it was still sitting in your Downloads folder, and so all your command line tools are still looking for it there.
I'm assuming that in the mean time you've moved Xcode – which, as you'd expect, moves all the application folder's files and subfolders as well – to your /Applications folder.
You should be able to redirect all your tools to look in the new, correct location by using the following command line command:
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer


text:
Q: Recursive CTE in hive I have a recursive CTE written in SQL server which i need to migrate to HIVE.
As hive does not support recursion in CTE, i am stuck here. i am advised to write a java UDF for this but i am not expert in java. If anyone could help here, i would be great.
Code(SQL server) :
            WITH CTE_CATEGORY_TREE AS
            (
                                            SELECT CT.seq
                                                            , CT.[name]
                                                            , CT.pseq
                                                            , convert(varchar(255), CT.seq) AS [sort]
                                                            , convert(nvarchar(255), CT.[name]) AS [depth_fullname]
                                            FROM [dbo].[table1] AS CT WITH(NOLOCK)
                                            WHERE CT.pseq = 0
                            UNION ALL
                                            SELECT PC.seq
                                            , PC.[name]
                                            , PC.pseq
                                            , convert(varchar(255), convert(nvarchar,CT2.sort) + N' > ' + convert(varchar(255), PC.seq)) AS [sort]
                                            , convert(nvarchar(255), convert(nvarchar,CT2.depth_fullname) + N' > ' + convert(nvarchar(255), PC.[name])) AS [depth_fullname]
                                            FROM [dbo].[table1] AS PC WITH(NOLOCK)
                                            JOIN CTE_CATEGORY_TREE AS CT2 ON PC.pseq = CT2.seq
            )

            SELECT          seq
                            , [name]
                            , pseq
                            , sort
                            , depth_fullname
            FROM CTE_CATEGORY_TREE


text:
Q: Extract the substrings under certain conditions I have the following string in Excel: C37S25FF0000TD.
In 7 different cells, I need to extract 7 substring according to these directions:

*

*The first cell must contain the letters up to the first number. In this case it must contain only C.

*The second cell must contain the first number that appears (this number can also have more than two digits). In this case it must contain only 37.

*The third cell must contain the following letters, up to the next number. In this case only S.

*The fourth cell must contain the next two digits (they are always two digits). In this case 25.

*The fifth cell must contain the next 6 characters. In this case FF0000.

*The sixth cell must contain the next character. In this case T.

*The seventh cell must contain the last character. In this case D.

Can someone help me? Since substrings can have variable length I don't know how to use the function MID() correctly. Thanks in advance.

A: Reminded me of this UDF that can come in handy if you'd change the pattern:
Function GetData(inp As String, grp As Long) As String

With CreateObject("VBScript.RegExp")
    .Pattern = "^([A-Z]+)(\d+)([A-Z]+)(\d\d)(.{6})(.)(.)$"
    If .Test(inp) Then
        GetData = .Execute(inp)(0).Submatches(grp - 1)
    Else
        GetData = "No Data Found"
    End If
End With

End Function

Here is an online demo. It would match:

*

*^ - Start-line anchor;

*([A-Z]+) - A 1st capture group to match 1+ uppercase alpha-chars;

*(\d+) - A 2nd capture group to match 1+ digits;

*([A-Z]+) - A 3rd group identical to 1st;

*(\d\d) - A 4th group matching exactly two digits;

*(.{6}) - A 5th group matching exactly 6 characters other than newline;

*(.) - A 6th group capturing the 2nd to last character;

*(.) - A final 7th group matching the last character;

*$ - End-line anchor.

Call through =GetData(A1,1) where the 2nd parameter can be 1-7.

Also thought it's fun to see how to mimic this with a single formula:

Formula in B1:
=LET(A,A1,B,LEFT(A,LEN(A)-8),C,TEXTSPLIT(B,SEQUENCE(10,,0),,1),D,TEXTSPLIT(B,C,,1),E,MID(RIGHT(A,8),{1,7,8},{6,1,1}),HSTACK(TOROW(VSTACK(C,D),,1),E))

A: Edited to allow for leading zero's in second substring
Here is a set of formulas that take into account the fact that some of the substrings may be of varying length.
Some of the formulas use functions only found in Office 365. However, substitutes for earlier versions are also available:
Letters up to first number: = LEFT(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A1&"0123456789"))-1)

Next first full number (variable number of digits:
    =LET(s,MID(A1,LEN(B1)+1,LEN(A1)),
       arr, MID(s,SEQUENCE(LEN(s)),1),
       len, MATCH(TRUE,ISERR(-arr),0),
       LEFT(s,len-1))

Subsequent letter(s):
        =LET(s,MID(A1,SUM(LEN(B1:B2))+1,LEN(A1)),
           pos,MIN(FIND({0,1,2,3,4,5,6,7,8,9},s&"0123456789")),
           LEFT(s,pos-1))

Next two characters: =MID(A1,SUM(LEN(B1:B3))+1,2)

For the subsequent substrings, we can count from the right:
   First 6 of the last 8 characters: =MID(A1,LEN(A1)-7,6)

    Penultimate character: =MID(A1,LEN(A1)-1,1)

    Last character:  =RIGHT(A1)

A: So, based on the single example you gave and making no assumptions about changing positions:

You can edit to deal with any of the numbers that may contain extra digits etc by expanding on the technique using len() and find() as necessary.


text:
Q: Choosing a software licence I want to release some javascript libraries under an open source license, but am having some difficulty picking one.  I want a license that meets the following requirements:

*

*Credit must be given to the original author

*Modification to the source code must be released open source

*Software can be sold, modified, or bundled with propriety software.

Are there any open source licenses that fit this bill well?
I have considered the MPL but I don't know if it requires that credit be given to authors.

A: CC BY-SA seems to follow your "rules": http://creativecommons.org/licenses/by-sa/3.0/
MPL seems ok too


text:
Q: how can remove decimal place after value in C#? Let I have decimal value of 14.8447 and I need this value 8447 in string.
Can any one find any way for me using window Forms C#.

A: You could use something like:
decimal d = 14.8447m;
string s = d.ToString(CultureInfo.InvariantCulture);
string t = s.Substring( s.IndexOf('.')+1);

(Although I think my code is a bit of a hack)
To make it a little bit more error-proof, you could write:
decimal d = 14.8447m;
string s = d.ToString(CultureInfo.InvariantCulture);

int index = s.IndexOf('.');
string t = index >= 0 && index + 1 < s.Length
       ? s.Substring(index + 1)
       : string.Empty;

This works well with e.g. the following numbers:
decimal d = 14m; // Returning empty string.
decimal d = .3m; // Returning "3".

Here is a short online version at Ideone.com.

A: string.Format("{0:0.0000}", 14.8447m).Split(',', '.').Last()

A: Could be so:
decimal Numero = 8.24M;
string r = (Numero - Math.Floor(Numero)).ToString().Replace("0.", "");

Easy I guess;