text:
Q: How to add child nodes to parent using TreeView How can I add child nodes to a parent node, using a TreeView?
I can Add Parent with this code.
 WordPressWrapper ww = new WordPressWrapper(textBox2.Text, textBox3.Text, textBox4.Text);
                var cat = ww.GetCategories();
                for (int i = 0; i < cat.Count; i++)
                {
                    if (cat[i].parentId == "0")
                    {
                        TreeNode tn = new TreeNode(cat[i].categoryName);
                        tn.ForeColor = Color.Blue;
                        tvCat.Nodes.Add(tn);

this is working good . (i have not any problem for add parent) . for add child i writhe this code .
for (int i = 0; i < cat.Count; i++)
                {
                    if (cat[i].parentId != "0")
                    {
                        for (int j = 0; j < cat.Count; j++)
                        {
                            if (cat[i].parentId == cat[j].categoryId)
                            {
                                tvCat.Nodes[i].Nodes.Add(cat[j].categoryName);
                            }
                        }
                    }
              }

but i catch error (Specified argument was out of the range of valid values.parameter name: index) .how i can solve it ?


text:
Q: AbstractAuthenticationProcessingFilter: doFilter gets hit, but `attemptAuthentication` does not I have the following filter definition:
@Component
public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    @Autowired
    private UserDetailsService customUserDetailsService;
    @Autowired
    private AuthenticationManager authenticationManager;

    private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);
    private final static UrlPathHelper urlPathHelper = new UrlPathHelper();

    public JWTAuthenticationFilter() {
        super("/**"); // what should I pass here ?
        setAuthenticationManager(new NoOpAuthenticationManager());
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request, customUserDetailsService);
        return authentication;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(request, response);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,FilterChain chain, Authentication authentication) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authentication);
        logger.debug("successful authentication while attempting to access " + urlPathHelper.getPathWithinApplication((HttpServletRequest) request));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
        logger.debug("failed authentication while attempting to access " + urlPathHelper.getPathWithinApplication((HttpServletRequest) request));
    }
}

and the following two configure methods in web configuration for my Spring security:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .csrf().disable()
        .authorizeRequests()
            .anyRequest().authenticated()
        .and()
        .addFilterBefore(jwtAuthenticationFilter,
            UsernamePasswordAuthenticationFilter.class);
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers("/login**", "/signup**");
}

There are a couple of problems with this code:

*

*I don't want the filter to exectue when calls are made to /login and /signup endpoints, but doFilter still gets hit even when a call is made to these two endpoints.

*attemptAuthentication, successfulAuthentication and unsuccessfulAuthentication don't get hit, but doFilter does. Why? why these methods are not called ?

What is happening here ? and why ?

A: Try this(but not tested!):
public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    @Autowired
    private UserDetailsService customUserDetailsService;
    @Autowired
    private AuthenticationManager authenticationManager;

    private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);
    private final static UrlPathHelper urlPathHelper = new UrlPathHelper();

    public JWTAuthenticationFilter() {
        super("/**"); // what should I pass here ?
        setAuthenticationManager(new NoOpAuthenticationManager());
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request, customUserDetailsService);
        return authentication;
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,FilterChain chain, Authentication authentication) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authentication);
        logger.debug("successful authentication while attempting to access " + urlPathHelper.getPathWithinApplication((HttpServletRequest) request));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
        logger.debug("failed authentication while attempting to access " + urlPathHelper.getPathWithinApplication((HttpServletRequest) request));
    }
}

In your configuration file:
@Bean("jwtAuthenticationFilter")
    public LoginRequestFilter jwtAuthenticationFilter(){
        LoginRequestFilter filter = new LoginRequestFilter();
        filter.setAuthenticationManager(authenticationManager);
        filter.setAuthenticationSuccessHandler(successHandler);
        filter.setAuthenticationFailureHandler(failureHandler);
        //filter.setAuthenticationFailureHandler(failureHandler);
        return filter;
    }

and add this as well
http.authorizeRequests().and()
                .addFilterAt(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

A:

*

*I don't want the filter to exectue when calls are made to /login and /signup endpoints, but doFilter still gets hit even when a call is made to these two endpoints.

While I can't explain the relationship betweeh the two configure() methods you've written, you can remove configure(WebSecurity) and include all path expressions in configure(HttpSecurity), like this:
    .authorizeRequests()
        .antMatchers("/login", "/signup")
        .permitAll()
        .and()
    .authorizeRequests()
        .antMatchers("/**")
        .authenticated();

*attemptAuthentication, successfulAuthentication and unsuccessfulAuthentication don't get hit, but doFilter does. Why? why these methods are not called ?

AbstractAuthenticationProcessingFilter.doFilter() would normally invoke your overridden attemptAuthentication() (and other methods, as appropriate).  Your overridden implementation effectively turns this filter into a "no op" by handing the request down to the remainder of the filter chain unconditionally.

A: Probably too late, however, I've given this answer to a similar question, so it can also be useful here:
Your custom implementation extends the UsernamePasswordAuthenticationFilter (which in its turn extends the AbstractAuthenticationProcessingFilter). The UsernamePasswordAuthenticationFilter, by default, is used for .formLogin authentication, handling the default AntRequestMatcher "/login". If you use a different protected endpoint, the filter's attemptAuthentication() method never gets action. So, if you want to use a different matcher (a different protected endpoint), you have to override the default AntRequestMatcher. For instance, you can do so within your custom filter constructor, by using something like that:
super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/auth/signin", "GET"));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как в Андроид Студио сделать так, чтобы приложение в заданных странах запускалось на русском языке? Т.е. чтобы values-ru использовался для них Как в Андроид Студио сделать так, чтобы приложение в заданных странах  запускалось на русском языке (сейчас запускается на Английском)? Т.е., чтобы ресурс values-ru использовался в телефоне (устройстве), если в нем настроен например, Украинский язык.
Я знаю, что в папку values-uk можно скопировать содержимое из папки values-ru и это работает. Но это же не серьезное решение. ) Нужно решать через какие-то настройки (ссылки)...
По умолчанию в приложении, как Вы понимаете, настроен Английский язык.


text:
Q: PHP issue after getting fragment from url. I have some page, it's url is like http://www.domainname.com/m1.php?#m2.php?more=apple&starting=1.
I want get the value $_GET['more'] & $_GET['starting'].
I use this code
<script type="text/javascript">
var parts = location.href.split('#');
if(parts.length > 1)
{
    var params = parts[0].split('?');
    var mark = '?';
    if(params.length > 1)
    {
        mark = '&';
    }
    location.href = parts[0] + mark + 'fragment=' + parts[1] ;
}
</script>
<?php
if(isset($_GET['fragment']))
{
    echo $_GET['fragment'];
}
?>

but I still get the m2.php?more=apple and lost starting=1. How to get 2 of them? and then divide into $_GET['more'] & $_GET['starting']? Thanks.

A: Your code really isn't even close to getting those two values.  I'm not sure what to make of it since it is so far off.
If your PHP code is running after setting the new location, then you will want the values more and starting to be before the hash (#) as the hash part does not get sent to the server.
If you want to get the more and starting values in JavaScript, then it can be either place, but you need to know what stage you are at to get it the right way.
Examples
URL: http://www.domainname.com/m2.php?more=apple&starting=1
Query string: more=apple&starting=1
Hash: none
<?php
echo $_GET['more']; // apple
echo $_GET['starting']; // 1

URL: http://www.domainname.com/m1.php?#m2.php?more=apple&starting=1
Query string: none
Hash: m2.php?more=apple&starting=1
<?php
echo count($_GET) // 0

Javascript:
var hash = location.hash; // m2.php?more=apple&starting=1
var hashparts = hash.split("?");
var urlhashpart = hashparts[0]; // m2.php
var querystringhashpart = hashparts[1]; // more=apple&starting=1
var params = querystringhashpart.split("&");
for (var i in params) {
    var param = params[i].split("=");
    document.write(param[0] + ": " + param[1]); // outputs 'more: apple', 'starting: 1'
}

A: Alternatively, if you're looking to get this information for use in PHP, a simple combination of parse_url() and parse_str() will also do the trick:
$url = parse_url('http://www.domainname.com/m1.php?#m2.php?more=apple&starting=1');
$anchorparts = explode('?',$url['fragment']);
parse_str($anchorparts[1],$vars);

A dump of $vars then yields:
array(2) {
  ["more"]=>
  string(5) "apple"
  ["starting"]=>
  string(1) "1"
}


text:
Q: 'An entry has been added to the Windows event log of the server.' error upon InfoPath submission I've build a simple form in InfoPath 2007 with 'Submit' button using Custom Data Connection to send form data via Email. When I preview form in InfoPath form is sent correctly to email box, however once Published to SharePoint and embedded on website as Web Part, same form returns below error upon submission.
Please advice.
error:
An error occurred while using the form. For more information, contact the site administrator.
An entry has been added to the Windows event log of the server.
Log ID:5567
Correlation ID:1529c69a-32ec-407d-84bc-02b86a19cc5e

A: This issue was caused by the fact that SMTP service wasn't set up correctly.


text:
Q: Joining another database into SQL query I was able to join another database into my query in access as shown
LEFT JOIN  [X:\Zodds and Ends\Emer\T2Data.MDB].tblContacts
ON EeDetails.BankCode = tblContacts.FirstName)

I am changing this query over to SQL Server but I cant find a way of linking the database I have also tried this but it doesn't work.
LEFT JOIN T2Ddata..tblContacts ON EeDetails.BankCode = tblContacts.FirstName)

A: The syntax is LEFT JOIN databasename.schemaname.tablename
The default schema is dbo. So it is usually: databasename.dbo.tablename
Also, it is a good idea to use an alias
LEFT JOIN T2Ddata.dbo.tblContacts c ON c.id = e.ContactId)

I doubt if you would be joining on FirstName?


text:
Q: How to get the real uri address in spring boot? @RequestMapping("/test")
public String test() {
    return "test";
}

I wrote an interface  I want to get the URI of the interface to do different authentication according to the uri.
But I visit localhost / test / can also be routed to / test
How do i set
What I get using getServletPath () method is also with /
enter image description here

A: you can get using below:
@RequestMapping(value ="/test")
public String test(HttpServletRequest request){
String test = request.getRequestURI();
return test;
}


text:
Q: Filter items from list while iterating, without a list comprehension Say I have a list of items, and I'd like to iterate over them, performing actions on them and removing them if some criterion is not met.
I can do this really easily via a list comprehension:
selection = [...]
selection = [node for node in selection
             if True in [prop['value'] for prop in node.properties
                         if prop['name'] == 'some_name']]

But in my case that's a fairly lengthy comprehension, and I need to stick some state-checking statements and assertions in there. I can't do that with a list comprehension. It's a shame, because using list comprehensions feels so good.
What's the best way to iterate through and filter this list?


text:
Q: Special case of Pieri-Rule is there an "elementary" (read: short combinatorial) proof for the rule
$$ s_\lambda \cdot s_{(1)} = \sum_{\mu} s_{\mu} $$
where $\mu$ ranges over all partitions obtained from $\lambda$ by adding a singe box?
Where the Schur-polynomial $s_\lambda$ is defined as the sum over all monomials one gets from semi-standard tableaux corresponding to the Young-diagram of $\lambda$.
The number of variables here is $n$ and $\lambda$ is a partition of $d\leq n-1$.
Basically, I would like to understand Schur-Weyl duality, that is, the decomposition of the d-fold tensor product as described in chapter 6 of Fulton, Harris "Representation theory".
So alternatively, if $W(\lambda)$ if the irreducible representation of $GL_n(\mathbb{C})$ corresponding to $\lambda$, then I want to understand the decomposition of $W(\lambda) \otimes \mathbb{C}^n$.
$\dim W(\lambda)$ is the number of semistandard tableaux filled with numbers from $[n]$.
The identity to be proved would then be
$$ \dim W(\lambda) \cdot n = \sum_{\mu} \dim W(\mu) $$


text:
Q: Cannot run adb command in ubuntu adb server is out of date when i run adb devices
    adb server is out of date.  killing...
    cannot bind 'tcp:5037'
    ADB server didn't ACK
    * failed to start daemon *
    error:

its the same as this error here
. some of the comments say that try to adb kill-server then start adb again but it does not work in my ubuntu machine.
I have also tried killall -9 adb which is the correct answer of this question. It is also stated in the correct answer is the best solution is to change genymotion settings and point to sdk but in my case i already did it.
can someone help me get rid of this error.

A: any way in case if someone will see this post i want to point how really simple the solution by closing all the genymotion devices then running the command
killall adb. By killing all the adb does kill it all then i did start-server maybe i have another adb running some times before and i forgot about it.


text:
Q: Dockerfile: How to run chsh for non root user I have the following Dockerfile. The aim is to install zsh and add a non root user and change its shell
FROM amazon/aws-cli:latest

RUN yum -y update && yum install shadow-utils.x86_64 zsh util-linux-user -y

# explanation of above packages
# shadow-utils.x86_64 required to get addgroup / adduser
# util-linux-user required to get chsh
# zsh to install zsh

RUN useradd -m -r -u 1000 -g users simha

WORKDIR /home/simha

USER simha

RUN chsh -s /usr/bin/zsh

But I get
Changing shell for simha.
Password: chsh: Authentication failure
chsh: changing user attribute failed: Permission denied
The command '/bin/sh -c chsh -s /usr/bin/zsh' returned a non-zero code: 1

Can anyone help how to change the shell to zsh for non root

A: You can set the default shell for simha at user creation by providing useradd the -s /usr/bin/zsh argument.
Example:
FROM amazon/aws-cli:latest

RUN yum -y update && yum install shadow-utils.x86_64 zsh util-linux-user -y

# explanation of above packages
# shadow-utils.x86_64 required to get addgroup / adduser
# util-linux-user required to get chsh
# zsh to install zsh

RUN useradd -m -r -u 1000 -g users simha -s /usr/bin/zsh

WORKDIR /home/simha

RUN echo Before: $SHELL
USER simha
RUN echo After: $SHELL

I am not sure why chsh doesn't work here. Maybe it depends on the configuration of the Docker image.


text:
Q: SOAP Web Service Client in Borland C++ Builder 6 Here below is the step-by-step attempt to developp a Web Service client in an application developped in Borland C++ Builder 6.
Help is welcome to correct this code or to suggest any other solution (though I now try to use a dll developped in C++ Builder XE3).
Here is my attempt to use Soap in Borland 6 C++ Builder. Untill now I conclude that I cannot succeed because Borland 6 does not manage SOAP header (absent of InvokeRegistry.hpp) and the SOAP server to whom we send requests needs cookies to be passed after the login of this interface :
    __interface INTERFACE_UUID("{B0F412ED-AC6A-42C3-8730-DD0D9680F16D}") AuthenticationSoap : public IInvokable
    {
    public:
      virtual LoginResult*    Login(const AnsiString username, const AnsiString password) = 0;
      virtual AuthenticationMode Mode() = 0;
    };
    typedef DelphiInterface<AuthenticationSoap> _di_AuthenticationSoap;

this login first sends a :
    500 Server Internal Error

then is ok if I add this call :
    InvRegistry()->RegisterInvokeOptions(__interfaceTypeinfo(AuthenticationSoap), ioDocument);

then I pass the User Name to a HTTPRIO :
    MyHTTPRIO->HTTPWebNode->UserName = AnsiString("xxx...");

And this HTTPRIO is passed to the second interface :
    __interface INTERFACE_UUID("{1E5B3820-A40E-FD40-326D-95A9F6B7A5F0}") OrganizerWS_1_1Soap : public IInvokable
    {
    public:
    ...
    virtual void            findHorse(const ArrayOfString FEIIDs, const AnsiString Name, const AnsiString SexCode, const bool IsPony, const AnsiString AthleteFEIID, ArrayOfHorseOC& findHorseResult, ArrayOfMessage& Messages) = 0;
    ...
    };
    typedef DelphiInterface<OrganizerWS_1_1Soap> _di_OrganizerWS_1_1Soap;
    _di_OrganizerWS_1_1Soap GetOrganizerWS_1_1Soap(bool useWSDL=false, AnsiString addr="", Soaphttpclient::THTTPRIO* HTTPRIO=0);

But we get an error "AuthHeader is missing" because we have used Borland 6's WSDL importer which does not generates code for Headers and headers are not defined in Invokeregistry.hpp.
So in the "BeforeExecute" of our HTTPRIO we have this request :
    <?xml version="1.0"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <SOAP-ENV:Body>
        <findHorse xmlns="http://fei.org/">
            <FEIIDs/>
            <Name></Name>
            <SexCode></SexCode>
            <IsPony>false</IsPony>
            <AthleteFEIID>10002254</AthleteFEIID>
            <findHorseResult/>
            <Messages/>
        </findHorse>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

whereas Borland XE3 generates this request which is ok and brings the expected response from the server :
    <?xml version="1.0"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <SOAP-ENV:Header>
        <NS1:AuthHeader xmlns:NS1="http://fei.org/">
            <UserName xmlns="http://fei.org/">xxx...</UserName>
            <Language xmlns="http://fei.org/">en</Language>
        </NS1:AuthHeader>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
        <findHorse xmlns="http://fei.org/">
            <IsPony>false</IsPony>
            <AthleteFEIID>10002254</AthleteFEIID>
        </findHorse>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>

So I first replaced
    <SOAP-ENV:Body>

by
    <SOAP-ENV:Header><NS1:AuthHeader xmlns:NS1="http://fei.org/"><UserName xmlns="http://fei.org/">xxx...</UserName><Language xmlns="http://fei.org/">en</Language></NS1:AuthHeader></SOAP-ENV:Header><SOAP-ENV:Body>

then added options as for example "<< xoHolderClass << xoInlineArrays" :
    RemClassRegistry()->RegisterSerializeOptions(__classid(findHorse), (TSerializationOptions() << xoHolderClass << xoInlineArrays));

here I obtain the same request but the answer of the server is a NULL array whereas there are three items in the answer to a test written in borland xe3.
Or with other manipulations (without xo... options) I get access violation in delphi interfaces destructor :
    __fastcall ~DelphiInterface<T>()
      {
            if (intf != 0)
            {
              intf->Release();
              intf = 0;
            }
      }

I explored other solutions (such as using indySOAP which is available only in Delphi sources (no C++ sources), thought about creating the XML and sending with Indy components (but expect I would encounter a same authentication header issue ?), using CAPICOM, or windows SDK ? ...) but without success until now and as said before I now try to use a dll developped in C++ Builder XE3 :
https://stackoverflow.com/questions/15485276/embarcadero-c-xe3-dll-imported-in-c-xe3-project-library-loads-but-access-v


text:
Q: How to repair grub after moving ubuntu to separate disk? Previous setup:

*

*windows 10 + ubuntu 16.04 dual boot with grub on ssd1(/dev/nvme0n1).
Current setup:

*

*ssd2(/dev/nvme1n1) contains only windows 10 cloned from above. Boots
fine.

*ssd1(/dev/nvme0n1) contains only ubuntu, all other partitions removed.
Can't boot here.
I want to be able to dual boot again and select either windows 10 or ubuntu from the menu.
This is what the terminal shows in the live usb:
ubuntu@ubuntu:~$ sudo fdisk -l
Disk /dev/loop0: 1.5 GiB, 1601015808 bytes, 3126984 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/nvme0n1: 238.5 GiB, 256060514304 bytes, 500118192 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: F6F46D18-D629-4D34-9F1A-0900B2600555

Device         Start       End   Sectors Size Type
/dev/nvme0n1p1  2048 104859647 104857600  50G Linux filesystem

Disk /dev/nvme1n1: 465.8 GiB, 500107862016 bytes, 976773168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 4C872172-3D07-4489-B670-6FB593A31318

Device            Start       End   Sectors   Size Type
/dev/nvme1n1p1     2048   1026047   1024000   500M EFI System
/dev/nvme1n1p2  1026048   1288191    262144   128M Microsoft reserved
/dev/nvme1n1p3  1288192   3033087   1744896   852M Windows recovery environment
/dev/nvme1n1p4  3033088  23244799  20211712   9.7G Windows recovery environment
/dev/nvme1n1p5 23244800 976773119 953528320 454.7G Microsoft basic data

Disk /dev/sda: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: F7921471-F857-4820-9356-237BF02CAD38

Device          Start        End    Sectors   Size Type
/dev/sda1          34     262177     262144   128M Microsoft reserved
/dev/sda2      264192 1919969279 1919705088 915.4G Microsoft basic data
/dev/sda3  1919969280 1953523711   33554432    16G Linux swap

Partition 1 does not start on physical sector boundary.

Disk /dev/sdb: 7.3 GiB, 7813988352 bytes, 15261696 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xf5e34067

Device     Boot Start      End  Sectors  Size Id Type
/dev/sdb1  *     8064 15124991 15116928  7.2G  c W95 FAT32 (LBA)
ubuntu@ubuntu:~$

lsblk:
ubuntu@ubuntu:~$ lsblk -f -o +PARTLABEL /dev/nvme1n1
NAME        FSTYPE LABEL      UUID                                 MOUNTPOINT PARTLABEL
nvme1n1
├─nvme1n1p4 ntfs   Image      C66E65726E655BE5
├─nvme1n1p2                                                                   Microsoft reserved partition
├─nvme1n1p5 ntfs   OS         01D238F37C836540                                Basic data partition
├─nvme1n1p3 ntfs   WINRETOOLS AEFA63D2FA63957D
└─nvme1n1p1 vfat   ESP        9AB9-9DEA                                       EFI system partition
ubuntu@ubuntu:~$ lsblk -f -o +PARTLABEL /dev/nvme0n1
NAME        FSTYPE LABEL UUID                                 MOUNTPOINT                                         PARTLABEL
nvme0n1
└─nvme0n1p1 ext4         1e27d729-df08-4d63-ad19-402e4c3340cf /media/ubuntu/1e27d729-df08-4d63-ad19-402e4c3340cf
ubuntu@ubuntu:~$

blkid:
ubuntu@ubuntu:~$ blkid
/dev/nvme0n1p1: UUID="1e27d729-df08-4d63-ad19-402e4c3340cf" TYPE="ext4" PARTUUID="97c73deb-1ad6-4fa9-bc50-7dad24f84a68"
/dev/nvme1n1p1: LABEL="ESP" UUID="9AB9-9DEA" TYPE="vfat" PARTLABEL="EFI system partition" PARTUUID="ac04e9de-aeb3-4595-9498-7e088a2178f7"
/dev/nvme1n1p3: LABEL="WINRETOOLS" UUID="AEFA63D2FA63957D" TYPE="ntfs" PARTUUID="162446b1-0911-41bf-8b91-6e92609105fe"
/dev/nvme1n1p4: LABEL="Image" UUID="C66E65726E655BE5" TYPE="ntfs" PARTUUID="8d16423b-2a17-45f3-ab56-95652bcb47af"
/dev/nvme1n1p5: LABEL="OS" UUID="01D238F37C836540" TYPE="ntfs" PARTLABEL="Basic data partition" PARTUUID="f8fe17da-3179-4c3e-98b0-ba7d0e8ad7ad"
/dev/sda2: LABEL="Data" UUID="86F26B62F26B5609" TYPE="ntfs" PARTLABEL="Basic data partition" PARTUUID="ff2d059c-108b-4e4a-9ef1-1d5645bf4e70"
/dev/sdb1: LABEL="UUI" UUID="0CDF-DB24" TYPE="vfat" PARTUUID="f5e34067-01"
ubuntu@ubuntu:~$

/etc/fstab:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/nvme0n1p6 during installation
UUID=1e27d729-df08-4d63-ad19-402e4c3340cf /               ext4    errors=remount-ro 0       1
# /boot/efi was on /dev/nvme0n1p1 during installation
#UUID=9AB9-9DEA  /boot/efi       vfat    umask=0077      0       1
# swap was on /dev/sda3 during installation
UUID=74c15561-f026-4824-bc85-32e3ee9b5d90 none            swap    sw              0       0
UUID=9AB9-9DEA  /boot/efi   vfat    defaults    0   1

This is grub.cfg : https://pastebin.com/cL1KFY5c

A: The best way of cloning Ubuntu from one drive to another, or one partition to another, is with a script that resets UUID's in /boot/grub/grub.cfg and /etc/fstab like this one:

*

*Bash script to backkup/clone Ubuntu to another partition
If you simply clone with a tool that doesn't change UUID's you need to use boot-repair as demonstrated here:

*

*How to make grub menu appear instead grub minimal bash-like in booting?
After running boot-repair you can get 7 entries for Windows so use this method to remove the extra entries:

*

*Boot Repair created too many Grub menu entries for Windows
With multiple Operating Systems you will get generic names created in grub such as:

*

*Ubuntu

*Windows Boot Manager (on /dev/nvme0n1p2)

*Windows Boot Manager (on /dev/sda1)

*Ubuntu 18.04 LTS (18.04) (on /dev/nvme0n1p6)

To get user friendly or more meaningful OS names for yourself use:

*

*how to tell GRUB to show the user preferred names of OS'es. Ubuntu 18.04
Disclaimer I wrote all the above links.


text:
Q: ConflictingBeanDefinitionException with obfuscated classes I am trying to obfuscate a Spring Boot application using Proguard.
Proguard rename the packages and classes alphabetically, so I'll be having classes like a.a, a.b, a.c, b.a and b.b...
My problem is that @RestController, @Configuration, @Service annotated classes with the same name (even though in different packages) generate the following exception

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.test.sirh.CoreApp]; nested exception is
org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'c' for bean class [com.test.sirh.g.a.c] conflicts with existing, non-compatible bean definition of same name and class [com.test.sirh.b.c]

Keeping the classes with those annotations would solve the problem, but I'll end up with almost half the classes not obfuscated.
Is there anyway so Proguard generates the classes alphabetically (that doesn't change) but without returning from "a" in each package? In way that I end up with a.a, a.b, a.c and b.d (instead of b.a).
And yes I am keeping the annotations. Just obfuscating the name of classes/classmembers.
My options :
<options>
    <option>-injar ${project.build.directory}/classes</option>
    <option>-outjar ${project.build.directory}/proguard-obf-classes </option>
    <option>-target 1.8</option>
    <option>-dontshrink</option>
    <option>-dontoptimize</option>
    <option>-dontusemixedcaseclassnames</option>
    <option>-keepattributes Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,LocalVariable*Table,*Annotation*,Synthetic,EnclosingMethod</option>
    <option>-keepparameternames</option>
    <option>-keepclasseswithmembers public class * {public static void main(java.lang.String[]);}</option>
    <option>-keep @org.springframework.context.annotation.Configuration public class *</option>
    <option>-keepclassmembers enum * { *; } </option>
</options>

Thank you.


text:
Q: tag postgres image used in docker-compose? I have the following docker-compose file:
version: "3.7"

services:
  bejebeje-identity:
    build:
      context: ./Bejebeje.Identity
      labels:
        com.bejebeje.description: "Bejebeje's Identity Server"
    image: bejebeje/identity:latest
    ports:
      - "5006:443"
      - "5005:80"
    env_file:
      - ./variables.env
    depends_on:
      - database
    volumes:
      - ~/.aspnet/https:/root/.aspnet/https/
  database:
    image: postgres:13.0
    ports:
      - "8001:5432"
    volumes:
      - data-volume:/var/lib/postgresql/data
    env_file:
      - ./variables.env

volumes:
  data-volume:

When I run docker-compose build . the images are built, I then run docker image ls and I get:

I suspect the <none> image is the postgres database? In my docker-compose file, how can I tag the database image with something like database/bejebeje/identity?

A: The 'none' was not postgres image but related to bejebeje-identit and only lead by dockerfile.
There is multistage build mode in docker. It will create multi stage docker images.
You can find below line from the project dockerfile.
# copy the contents of /app/out in the `build-env` and paste it in the
# `/app` directory of the new runtime container.
COPY --from=build-env /app/out .

that's reason.
Just rewrite your dockerfile, and remove the previous stage image. Then you will not see 'non' tagged image again.


text:
Q: Find the radius of convergence and convergence interval Find the radius of convergence and convergence  interval
$$\sum^\infty_{n=1}\frac{n^5\;(x+8)^n}{9^n\; n^\frac{17}{3}}$$
My attempt:
I'm computing $\lim_{n\to\infty}|\frac{a_{n+1}}{a_n}|$ and
I got the answer $|9(x+8)|$. So the radius  of convergence $R=\frac{1}{9}$ and interval =$(\frac{-73}{9},\frac{-71}{9})\,$.
Am I right ?

A: The basic term,
ignoring the shift by 8,
is
$(x/9)^n$.
Comparing this to
$z^n$,
which has radius of convergence
(roc) 1,
the original converges when
$|x/9| < 1$
or
$|x| < 9$.
Therefore its
roc is 9
(not 1/9),
so the interval is
$(-8-9, -8+9)$
or
$(-17, 1)$.
What happens at the endpoints
does depend on
the power of $n$
involved.

A: Probably too complex as an answer but too long for a comment.
$$u_n=\frac{n^5\;(x+8)^n}{9^n\; n^\frac{17}{3}}=\frac{9^{-n} (x+8)^n}{n^{2/3}}$$ Defining $y=\frac {x+8} 9$ makes $$u_n=\frac{y^n}{n^{2/3}}\implies S=\sum_{n=1}^\infty u_n=\text{Li}_{\frac{2}{3}}(y)$$ where appears the polylogarithm function  which has a branch cut discontinuity in the complex  plane running from $1$ to $\infty$ (see here). It is defined as long as $|y|<1$.
In fact, it is even convergent for $y=-1$ since $\text{Li}_k(-1)=-\left(1-2^{1-k}\right) \zeta (k)$.
So, back to $x$, $S$ is convergent for $-17\leq x <1$ as marty cohen answered.

A: The series is a power series around $x = -8$, that is, it is of the form
$$ \sum_{n=1}^{\infty} a_n (x - (-8))^n $$
where $a_n = \frac{n^5}{9^n n^{\frac{17}{3}}} = \frac{1}{9^n n^{\frac{2}{3}}}$. The radius of convergence is given by $R = \lim_{n \to \infty} \frac{a_n}{a_{n+1}}$ (if it exists) and not by $\lim_{n \to \infty} \frac{a_{n+1}}{a_n}$! In our case, we have
$$ \frac{a_{n+1}}{a_n} = \frac{9^n n^{\frac{2}{3}}}{9^{n+1}(n+1)^{\frac{2}{3}}} = \frac{1}{9} \left( \frac{n}{n+1} \right)^{\frac{2}{3}}  \to \frac{1}{9} $$
and so the radius of convergence is $R = 9$ and you are guaranteed that the series will converge in $(-17, 1)$. Now you also need to check the end points of the interval to determine the full domain of convergence.
At $x = 1$ we get the series
$$ \sum_{n=1}^{\infty} \frac{1}{n^{\frac{2}{3}}} $$
which diverges by the $p$ criterion.
At $x = -17$ we get the series
$$ \sum_{n=1}^{\infty} \frac{(-1)^n}{n^{\frac{2}{3}}} $$
which converges using the alternate series test. Thus, the full interval of convergence is $[ -17, 1)$.


text:
Q: Saleor-Storefront Error when running 'npm start' Trying to install saleor storefront on ubuntu.
After running

npm start
  getting the following error

npm start

> saleor-site@2.10.0-rc.1 start /home/nsola/storefront
> cross-env NODE_ENV=develop webpack-dev-server --history-api-fallback --watch --port 3000 --mode development --hotOnly

Starting type checking and linting service...
Using 1 worker with 2048MB memory limit
ℹ 「wds」: Project is running at http://localhost:3000/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: 404s will fallback to /index.html
ℹ 「wdm」: wait until bundle finished: /
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! saleor-site@2.10.0-rc.1 start: `cross-env NODE_ENV=develop webpack-dev-server --history-api-fallback --watch --port 3000 --mode development --hotOnly`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the saleor-site@2.10.0-rc.1 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

Have tried:
Step 1: $ npm cache clean --force
Step 2: Delete node_modules by $ rm -rf node_modules package-lock.json folder or delete it manually by going into the directory and right-click > delete / move to trash. Also, delete package-lock.json file too.
Step 3: npm install
To start again, $ npm start
But did not help.
Node version: v12.16.3
NPM version: 6.14.4
nginx version: nginx/1.14.0 (Ubuntu)
When I installed it locally its running fine with no issues

A: For anyone trying to solve this - the solution for me was to increase the memory size. I was running 1GB RAM on my ubuntu 18.04x64 droplet. But after increasing it to 4GB RAM. Everything was complying with no error.
Another solution could be by splitting "npm run  build-assets into smaller steps  where it would require low-memory systems.

A: Build it by your laptop and then deploy to remote server.
https://github.com/mirumee/saleor-storefront/issues/654#issuecomment-601150996

... but I would say you should rather compile everything locally with npm run build and then push the dist directory to Heroku and serve the app from there.


text:
Q: How to save as into a customized destination on macOS? When I try to saveAs a file on macOS (like in a browser such as Safari or Chrome), the only destinations I see are "devices", "favorites" or "recent places". However, how to save in a different location?
Is there a short key to go inside folders? Or what is the trick?

A: By default the Save As sheet is in, for the lack of the proper term, compact view. To expand the sheet click the down arrow to the right of the Save As: text box (Export As: in Safari)

*

*Clicking the down arrow, the one the red arrow is pointing to, opens up the sheet showing additional controls, as in the image below

A: I use Cmd-Shift-G often in these situations.
Works in any file dialog or Finder window.
This allows you to type in any custom path, or better yet, cut/copy/paste any custom path.
It also keeps track of any recent paths you used.


text:
Q: XCode 4.5.2 Linker Errors I am unable build an iOS app out of XCode due to Apple Mach-O Linker Errors. Here are XCode screenshots and also my workflow:
Unity 4

*

*I have pro version of both Unity and the iOS extension

Vuforia 1.5.10 unity extension
XCode 4.5.2

*

*Architectures and Valid Architectures all set to armv7 under Build Settings (Resolved, Unity-Iphone, Unity-Iphone). However, iOS Default is grayed out and I cannot change. It is set to Standard (armv7, armv7s)

*

*Keep receiving "Apple Mach-O Linker Errors" with regard to Vuforia features

Undefined symbols for architecture armv7:
"_markerGetId", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_qcarSetFrameFormat", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_rendererGetVideoBackgroundCfg", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_imageTrackerDestroyDataSet", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_imageTrackerActivateDataSet", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_cameraDeviceSetFlashTorchMode", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_imageTargetCreateVirtualButton", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_getProjectionGL", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_dataSetGetTrackablesOfType", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_trackerManagerDeinitTracker", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_trackerManagerInitTracker", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_rendererSetVideoBackgroundCfg", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_qcarRequiresAlpha", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_cameraDeviceStartCamera", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_rendererIsVideoBackgroundTextureInfoAvailable", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_dataSetGetNumTrackableType", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_virtualButtonIsEnabled", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_isRendererDirty", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

"_rendererGetVideoBackgroundTextureInfo", referenced from:
  RegisterMonoModules() in RegisterMonoModules.o

A: I just went with the same problem and, after couple days, I've finally solved it! Made it work with latest Unity 4.2 and Vuforia 2.6.7
Few probable things that could be causing the issue:

*

*Folder hierarchy: This is the biggest most likely point. Leave it as it is when imported from the packagefile. If you move a single file out of its original place, with a few exceptions, you will get many errors as you've described.

*Folder naming: Although I apparently had no issues here, use no spaces. It's advised everywhere (despite the package itself unpacking folders with spaces on it...).

*Build Settings / Player Settings: Again, I had no issues here. And I've tried changing them a little on an empty project, which worked with no issue. But, having the wrong setting here can cause such linker errors. Create an open project and try around.
To try again after changing any configuration, use CMD + SHIFT + B and press on Build and Run. It will ask where to save and, if saving on top, select Replace.
And good luck!


text:
Q: Dynamic form fields in Rails3 with jquery I am using rialscasts #74 as a guide.
I am trying to dynamically add form fields via a text-link. In the railscast episode he achieves it very nicely using the following code:

<%= javascript_include_tag :defaults %>

  <%= render :partial => 'task', :collection => @project.tasks %>

<%= add_task_link "Add a task" %>

<% fields_for "project[task_attributes][]", task do |task_form| %>

    Task: <%= task_form.text_field :name %>
    <%= link_to_function "remove", "$(this).up('.task').remove()" %>

<% end %>

 # projects_helper.rb

 def add_task_link(name)
    link_to_function name do |page|
      page.insert_html :bottom, :tasks, :partial => 'task', :object => Task.new
    end
 end

content within projects_help.rb is what I am most interested in. The problem is he is doing this via prototype. I am looking for an exact duplicate implementation using jquery (and rails3). What do you think? Thanks!

A: The current RailsCasts/ASCIICasts are #196 (see http://asciicasts.com/episodes/196-nested-model-form-part-1) & 197 which have been updated for Rails3.
Ryan Bates has also created a gem called nested_form (see https://github.com/ryanb/nested_form) which handles much of this for you. He has has also created examples of complex nested forms using Prototype, jQuery, and his nested form gem; you can find a link on the nested_forms page.
Good stuff!

A: ya I was going to say --  that is a very old railscast and is using both outdated practices and an old framework.  I'm gonna try to help you out.
layouts/application.erb
<%= javascript_include_tag :defaults %>

projects/new.erb

  <%= render :partial => 'task', :collection => @project.tasks %>

<%= add_task_link "Add a task" %>

projects/_task.erb

<%= fields_for "project[task_attributes][]", task do |task_form| %>

    Task: <%= task_form.text_field :name %>

    <%= link_to "remove", "#", :class => 'remove_task'

<% end %>

projects_helper.rb
def add_task_link(name)
  # This is a trick I picked up... if you don't feel like installing a
  # javascript templating engine, or something like Jammit, but still want
  # to render more than very simple html using JS, you can render a partial
  # into one of the data-attributes on the element.
  #
  # Using Jammit's JST abilities may be worthwhile if it's something you do
  # frequently though.
  link_to name, "#", "data-partial" => h(render(:partial => 'task', :object => Task.new)), :class => 'add_task'
end

public/javascripts/application.js
$(function(){
  // Binds to the remove task link...
  $('.remove_task').live('click', function(e){
    e.preventDefault();
    $(this).parents('.task').remove();
  });

  // Add task link, note that the content we're appending
  // to the tasks list comes straight out of the data-partial
  // attribute that we defined in the link itself.
  $('.add_task').live('click', function(e){
    e.preventDefault();
    $('#tasks').append($(this).data('partial'));
  });
});


text:
Q: In datetime, (change) doesn't work and (ngModelChange) called at page load too I use this plugin for Angular 2. I want to call a function when the date changes on input. If I use (change), it doesn't trigger the function, but if I use (ngModelChange) it triggers the function but also it is triggered on page load.
So, I either need to make (change) works or make the (ngModelChange) not to fire at page load. Any idea?

     date
     <datetime [timepicker]="false" [datepicker]="datepickerOpts" [(ngModel)]="mymodel.date" (ngModelChange)="callAFunction()" name="datetimepicker2i" id="datetimepicker2i"></datetime>


text:
Q: Which way of arranging fields in structure is better? I have two ways to arrange the fields in a structure
  struct foo {
    float   a;
    double  b;
    float   c;
    double  d;
    short   e;
    long    f;
    short   g;
    long    h;
    char    i;
    int     j;
    char    k;
    int     l;
  };

  struct foo {
    double  b;
    double  d;
    long    f;
    long    h;
    float   a;
    float   c;
    int     j;
    int     l;
    short   e;
    short   g;
    char    i;
    char    k;
  };

Which one should be practiced and why?

A: The best way to arrange members of a structure is to put them in increasing order, by their size. Doing this, you reduce the padding, required for data alignment.
Also, using some preprocessor directives you modify the alignment, for example:
#define packed_data __attribute__((__packed__))

turns it off. Using this, the member order doesen't matter anymore, but I strongly discourage this, as the memory alingnment is optimised for performance.

A: The Second arrangement is preferable.
In structs, to minimise the loss of bit storage due to padding
(the  boundary alignment of various variables in the memory) , it is preferable to start
the structure with variables of the largest size. Go from higher to lower size.

*

*See Padding in structures

*Size of variable types in C
(http://www.cquestions.com/2011/02/size-of-data-types-in-c.html)

A: One sensible way of ordering fields is by their similarity of purpose.
For instance:
struct window {
    MENU   *menu ;
    int    width ;
    char   *name ;
    WINDOW *child ;
    int    xpos ;
    int    height ;
    void   *info ;
    WINDOW *next ;
    CLASS  *class ;
    int    ypos ;
    WINDOW *parent ;
    }

would look better as
struct window {
    CLASS  *class ;
    void   *info ;
    char   *name ;
    int    xpos ;
    int    ypos ;
    int    width ;
    int    height ;
    WINDOW *parent ;
    WINDOW *next ;
    WINDOW *child ;
    MENU   *menu ;
    }

A: Padding is one reason to favor one arrangement over another. Another option is to sort the fields by their frequency or by their memory access pattern. This is of course micro-optimization, but it can pay off in extreme cases.
Many, or most CPU architectures encode smaller offsets in pointers with smaller opcodes; Putting the most frequently accessed element to offset zero can in especially RISC architectures reduce the number of instructions, as well as make the code run faster.
If 'x' is used at the same time as 'y', it's beneficial to put them in the same cache line instead of face the risk of two or more cache misses per structure.


text:
Q: Resolving urls on a Wordpress server using React I'm working on creating a new React-based site to replace an old WordPress site. I have been creating directories within the wordpress server for the new sections I have been making. domain.org/about, for example, will go to the react files stored in the about directory. No problems there. The issue I am having now is for more complicated urls. I have set up react-router to handle lots of events by using an id to pull in information on a specific event. domain.org/events/event123, for example, should display information on event123. In development this works fine, localhost:3000/events/event123 will display event123. On the wordpress server, however, I get an error. I realize that this is because there is no event123 directory within the events directory on the wordpress server.
How can I configure wordpress to handle these urls? I realize I need to set something up so that any url that begins with domain.org/events will go to the react files in the events directory, but how I go about doing this while still passing along the event123 I do not know. Any help is appreciated. Apologies if my description is a bit confusing.
EDIT: I should add that the old parts of the site and new parts of the site have no connection to each other, other than the fact that they are hosted on the same server. Once the new site has enough content on it it will be moved to a new server and the wordpress site will be shut down.


text:
Q: VB.NET Error: "The ConnectionString property has not been initialized." Dim Current As String
Current = Directory.GetCurrentDirectory()
con.ConnectionString = "PROVIDER = Microsoft.Jet.OLEDB.4.0;Data Source = " & Current & "\SchoolMaticsDatabase.mdb"
con.Open()
TabSelect()
con.Close()

Private Sub TabSelect()
        Select Case TabControl1.SelectedIndex
            Case Is = 0
                TabDay = "Monday"
            Case Is = 1
                TabDay = "Tuesday"
            Case Is = 2
                TabDay = "Wednesday"
            Case Is = 3
                TabDay = "Thursday"
            Case Is = 4
                TabDay = "Friday"
            Case Is = 5
                TabDay = "Saturday"
            Case Is = 6
                TabDay = "Sunday"
        End Select
        ds.Clear()
        sql = "SELECT [Forename],[Surname],[Subject Speciality 1],[Subject Speciality 2],[Subject Speciality 3],[Subject Speciality 4],[Subject Speciality 5],[Subject Speciality 6]," & StartTime & "," & EndTime & ",[Spec1],[Spec2],[Spec3],[Spec4],[Spec5],[Spec6] FROM [Staff] WHERE " & TabDay & " LIKE 'T'"
        da = New OleDb.OleDbDataAdapter(sql, con)
        da.Fill(ds, "SchoolMaticsDatabase")
End Sub

da.fill(ds,"SchoolMaticsDatabase")>>> Errors occurs on this line of code.
If tab index is changed the sub TabSelect() is called also. One other thing is that the program checks the day of the week and correctly displays the tab corresponding to that day. On Monday this code was working fine, as soon as it hit Tuesday this error cropped up.

A: Try passing conn as a parameter into the TabSelect() function. TabSelect(ByRef OleDbConnection conn) It could be an issue of scope since you are playing with global variables


text:
Q: How to get last week sunday date using jquery I am trying to get last week sunday date with "mm-dd-yyyy" format using jquery. Is there an easy solution out there for this?

A: get latest sunday with one sentence:
var latestSunday = new Date(new Date().setDate(new Date().getDate() - new Date().getDay()));

get last sunday with one sentence:
var lastSunday = new Date(new Date().setDate(new Date().getDate() - (new Date().getDay()==0?7:new Date().getDay())));

it seems verbose, you can divide the answer as you wish. then, you can use other date format plugins to format the date, like jQuery dateFormat

A: You can parse the string then subtract the day value to get the previous sunday

var string = '01-31-2015';
var date = new Date(string);
date.setDate(date.getDate() - date.getDay())
snippet.log(date)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

If the simple parsing of date is not working then

var string = '01-31-2015';
var parts = string.split('-'),
  date = new Date(parts[2], parts[0] - 1, parts[1]);
date.setDate(date.getDate() - date.getDay());

snippet.log(date)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

A: var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week

var firstday = new Date(curr.setDate(first)).toUTCString();

firstday
"Sun, 18 OCT 2015 12:25:40 GMT"


text:
Q: Property List not saving iOS I have a property list in my application and I have it change the values of all the different fields but when the app is closed all the settings are removed. Here is the code I'm using:

NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *path = [mainBundle pathForResource:@"Settings" ofType:@"plist"];
    //NSNumber *str = [dict objectForKey:@"Auto_Save"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
        [data setObject:[NSNumber numberWithBool:sender.on] forKey:@"Auto_Save"];
        [data writeToFile:path atomically:YES];

A: You can't write back to a file stored in the application bundle.  You need to write it to 'disk'.


text:
Q: Using file content as arguments multiple times I have one text file with names of a bunch of .txt files (not full path names) that exist in a directory. Each of the files, have a (full) path to another file which I would like to delete.
Suppose I have a file named "list.txt" and in it there are names of text files
pathtodelete1.txt
pathtodelete2.txt
something else that is the same as pathtodelete.txt

Each one of these files has a one path stored inside, for example pathtodelete1.txt contains /directory/randomfilename.txt
I have tried putting together xargs in many ways with no success.

A: In a limited test, this worked for me:
cat list.txt | xargs cat | xargs rm

Since you are using this to delete files, you might want to test it with a non-destructive command first, e.g.
cat list.txt | xargs cat | xargs echo

A: This script should do what you want. You can comment the echo statements (or omit them entirely) if you don't want a report on what it is doing.
Remove the : from the beginning of the rm statement when you are satisfied it will do what you want, and then it really will delete the named files.
#!/bin/bash
# Look in list.txt for files containing items to delete
while IFS= read -r file
do
    echo "Considering $file" >&2

    # Read the path to delete from the file
    path="$(cat "$file" 2>/dev/null)"

    # If it looks like a pathname try to delete it
    if [[ "$path" =~ ^/ ]] && [[ -f "$path" ]]
    then
        echo "> $path" >&2
        : rm -f "$path"
    fi
done <list.txt

A: while read TXT; do head -1 $TXT | xargs rm; done < list.txt


text:
Q: Browsers stick with old html and JS cache I am working on a very simple demo on .net MVC4, very simple, html page code less than 100 lines, with about 30 lines of JavaScript code in a separate JS file, no server side call. Also use jQuery 1.12 and bootstrap libs.
However I had trouble since last night, I added onclick() trigger to a button, but it never work. From developer tool I can see all the changes were gone even I had saved changes in HTML and JS file, and rebuild everything, elements from developer tool window shows old html and js file, without my change.
So below are what I did: (Note I did these in both IE 11 and Chrome)
1) "F5", not work
2) Ctrl + R, not work
3) Went to setting, cleared everything(history, cache, etc..), not work
4) Disabled JS cache in developer tool, not work
5) Add version number as other person mentioned in Stack Overflow
<script type="text/javascript" src="myfile.js?1500"></script>

not work
6)Then I created another js file with different name, copied all the js code to new file, deleted old one, re-add new one's reference to HTML.
let's say the old JS file is named "renderControl.js", then the new one I called it "fkTest.js"
Then I cleared everything I could. Then guess what? From developer tool, the html code remained in old one, I clicked tab "Sources", then I found old "renderControl.js" still under "Scripts" folder, which I had physically deleted.

A: (Posted on behalf of the OP.)
I resolved this by search the JS file name through my drive, deleted all the found.


text:
Q: Loading NPAPI plugin in Chrome I have a NPAPI API based (scriptable) plugin developed using Gecko SDK 1.9.2. This plugin works fine on FF3.6 & FF4 beta, but it fails to get detected on chrome.
Also I cannot see the plugin listed - when I do a "about:Plugins" in chrome.
I've registered the plugin as described in the "Windows Installation Using the Registry".
When monitored the chrome startup using Sysinternals tool Procmon.exe, I could find that the chrome tries to do a LoadImage on my Plugin dll, whoever it quickly unloads it.
Any ideas why this plugin is not detected by chrome will help.

A: It would be helpful to have an example of exactly what keys you used and where you put them; FireBreath plugins (works on all npapi and activex browsers) register themselves in the registry using that method and they work fine on chrome.
Depending on your needs, might even be worth looking into building your plugin in FireBreath instead of using npapi directly -- it's a lot less work and workarounds for various browsers have already been done.
One thing to try is to make sure you have the file name correct in the registry; Many versions of firefox just use the directory specified in the registry and search for any plugin files (this isn't documented, AFAIK, it's just my observations), whereas Chrome actually uses the path and file.  It's also possible you could have a permissions issue.

A: The issue was that the plugin dll didn't have the resource like file description, MIME type and language set. Adding the proper resource strings fixed the issue.


text:
Q: Скрыть input при нажатии на textarea

const isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
const isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

const copy = document.querySelector("#copy");
const clear = document.querySelector("#clear");
const spellcheck = document.querySelector("#spellcheck");
const textarea = document.querySelector("textarea");
const highlights = document.querySelector("#highlights");
const length = document.querySelector("#length");
const output = document.querySelector("output");
const list = document.querySelector("#list");
const template = document.querySelector("template");

let hiddens = [];
let duplicates = {};

// Text analysis
const count = (text, minLength) => {
  // https://mathiasbynens.be/notes/es-unicode-property-escapes#word
  const wordRegex = isChrome || isSafari
  ? new RegExp(`([\\p{Alphabetic}\\p{Mark}\\p{Decimal_Number}\\p{Connector_Punctuation}\\p{Join_Control}]+){${minLength},}`, 'gu')
  : new RegExp(`(\\w+){${minLength},}`, 'g');
  let result;
  const words = {};
  while ((result = wordRegex.exec(text)) !== null) {
    const word = result[0].toLowerCase();
    if (!words[word]) {
      words[word] = [];
    }
    words[word].push(result.index);
    words[word].push(result.index + word.length);
  }
  return words;
};

// Array manipulation
const duplicatePass = ([key, value]) => 2 < value.length;

const occurrenceComparator = ([keyA, valueA], [keyB, valueB]) =>
  valueB.length - valueA.length;

const numberComparator = (numberA, numberB) => numberA - numberB;

const differ = (object, [key, value], index) => {
  object[key] = {
    action: object[key] ? "KEEP" : "ADD",
    word: key,
    occurrences: value,
    index
  };
  return object;
};

const cleaner = (object, [word, details]) => {
  if (details.action) {
    delete details.action;
    object[word] = details;
  }
  return object;
};

const flattener = (array, details) => [...array, ...details.occurrences];

// DOM manipulation
const update = (item, details) => {
  item.style.zIndex = details.occurrences.length / 2;
  item.style.top = `${0.6 + details.index * 3}rem`;
  item.querySelector(".count").textContent = details.occurrences.length / 2;
};

const add = (word, details) => {
  const node = document.importNode(template.content, true);
  list.appendChild(node);
  const item = list.lastElementChild;
  item.id = `word-${word}`;
  const hidden = item.querySelector(".hidden");
  hidden.name = word;
  hidden.checked = hiddens.includes(word);
  hidden.addEventListener("change", handleToggle);
  item.querySelector(".word").textContent = word;
  update(item, details);
};

const keep = (word, details) => {
  const item = document.querySelector(`#word-${word}`);
  update(item, details);
};

const markObsolete = word => {
  document.querySelector(`#word-${word}`).classList.add("obsolete");
};

const remove = item => item.remove();

const removeObsolete = () => {
  document.querySelectorAll(".obsolete").forEach(remove);
};

const render = ([word, details]) => {
  if (details.action === "ADD") {
    add(word, details);
  } else if (details.action === "KEEP") {
    keep(word, details);
  } else {
    markObsolete(word);
  }
};

const getHue = word => {
  return (
    360 -
    360 / Object.keys(duplicates).length * duplicates[word.toLowerCase()].index
  );
};

const getHSL = word => {
  const hue = getHue(word);
  return `hsl(${hue + 20}, 100%, ${180 < hue && hue < 360 ? 80 : 50}%)`;
};

const colorize = word => {
  const color = getHSL(word);
  const count = document.querySelector(`#word-${word} .count`);
  const wordElement = document.querySelector(`#word-${word} .word`);
  count.style.borderColor = color;
  count.style.backgroundColor = color;
  wordElement.style.borderColor = color;
  wordElement.style.backgroundColor = color;
};

const highlight = (occurrence, index, occurrences) => {
  let node;
  if (index < occurrences.length - 1) {
    if (index % 2) {
      const word = textarea.value.substring(occurrence, occurrences[index + 1]);
      node = document.createElement("mark");
      node.textContent = word;
      if (!hiddens.includes(word.toLowerCase())) {
        const color = getHSL(word);
        node.style.background = color;
        node.style.border = `0.2rem solid ${color}`;
      }
    } else {
      const text = textarea.value.substring(occurrence, occurrences[index + 1]);
      node = document.createTextNode(text);
    }
  } else {
    const text = textarea.value.substring(occurrence);
    node = document.createTextNode(text + "\r\n\r\n");
  }
  highlights.appendChild(node);
};

const handleChange = () => {
  // Count words
  const words = count(textarea.value, length.value);

  // Diff word stats with previous
  const diff = Object.entries(words)
    .filter(duplicatePass)
    .sort(occurrenceComparator)
    .reduce(differ, duplicates);

  // Render items
  Object.entries(diff).forEach(render);

  // Clean obsolete from duplicates
  duplicates = Object.entries(diff).reduce(cleaner, {});

  // Adjust height of list
  list.style.height = `${1.2 + Object.keys(duplicates).length * 3}rem`;

  // Colorize items
  Object.keys(duplicates).forEach(colorize);

  // Flatten occurrences
  const occurrences = Object.values(duplicates)
    .reduce(flattener, [0])
    .sort(numberComparator);

  // Highlight
  while (highlights.firstChild) {
    highlights.removeChild(highlights.firstChild);
  }
  occurrences.forEach(highlight);

  // Remove
  window.setTimeout(removeObsolete, 400);
};

const handleToggle = event => {
  const word = event.target.name;
  if (event.target.checked) {
    if (!hiddens.includes(word)) {
      hiddens.push(word);
    }
  } else {
    const index = hiddens.indexOf(word);
    if (0 <= index) {
      hiddens.splice(index, 1);
    }
  }
  handleChange();
};

copy.addEventListener("click", () => {
  textarea.select();
  document.execCommand("copy");
});

clear.addEventListener("click", () => {
  textarea.value = "";
  textarea.focus();
  handleChange();
});

spellcheck.addEventListener("change", event => {
  textarea.setAttribute("spellcheck", event.target.checked.toString());
  const { value } = textarea;
  textarea.value = value + " ";
  textarea.value = value;
});

textarea.addEventListener("scroll", event => {
  highlights.scrollTop = event.target.scrollTop;
});

textarea.addEventListener(
  "focus",
  () => {
    textarea.value = "";
    handleChange();
  },
  {
    once: true
  }
);

textarea.addEventListener("input", handleChange);
length.addEventListener("input", handleChange);
length.addEventListener("input", () => (output.textContent = length.value));

handleChange();
html {
  font-family: Roboto, Helvetica, Arial, sans-serif;
  font-size: 62.5%;
  font-weight: normal;
}

body {
  margin: 0;
}

header {
  padding: 1.2rem 2.4rem;
  background-color: #2196f3;
}

h1 {
  margin: 0;
  font-size: 4.8rem;
  font-weight: normal;
  color: white;
}

main {
  display: flex;
  flex-flow: row wrap;
  padding: 0 1.2rem;
}

button {
  margin: 0 12px;
}

#actions {
  flex: 3 0 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 1.2rem;
}

#actions > label {
  margin-right: 0.6rem;
}

#options {
  flex: 1 0 0;
  padding: 1.2rem;
  min-width: 20rem;
}

#options > label {
  width: 100%;
}

hr {
  margin: 0;
  border: none;
  width: 100%;
  height: 0;
}

mark {
  margin: -0.2rem;
  border: 0.2rem solid transparent;
  border-radius: 0.4rem;
  color: transparent;
  background: transparent;
}

#text {
  position: relative;
  flex: 3 0 0;
  padding: 0 1.2rem;
  transition: height 0.3s;
}

textarea,
#highlights {
  position: absolute;
  top: 0;
  bottom: 0;
  margin: 0;
  border: solid 0.1rem rgba(0, 0, 0, 0.54);
  border-radius: 0.4rem;
  padding: 1.3rem;
  font-family: Roboto, Helvetica, Arial, sans-serif;
  font-size: 1.6rem;
  font-weight: normal;
  line-height: 2rem;
  outline: none;
  transition: height 0.3s;
}

textarea {
  box-sizing: border-box;
  width: calc(100% - 2.4rem);
  height: 100%;
  background: transparent;
  resize: none;
}

textarea:focus {
  border: solid 0.2rem #2196f3;
  padding: 1.2rem;
}

#highlights {
  z-index: -1;
  box-sizing: border-box;
  width: calc(100% - 2.4rem);
  white-space: pre-wrap;
  word-wrap: break-word;
  color: transparent;
  overflow-x: hidden;
  overflow-y: auto;
}

ol {
  margin: 0;
  padding: 0;
  list-style: none;
}

#list {
  position: relative;
  flex: 1 0 0;
  padding: 0 1.2rem;
  min-width: 20rem;
  min-height: calc(100vh - 24rem);
  transition: height 0.3s;
}

.item {
  position: absolute;
  transition: top 0.3s, opacity 0.3s;
  animation: add 0.3s;
}

.item > label {
  cursor: pointer;
}

.hidden {
  display: none;
}

.count,
.word {
  display: inline-block;
  border: solid 0.2rem;
  box-shadow: inset 20rem 2rem transparent;
  transition: border 0.3s, background 0.3s, box-shadow 0.3s;
}

.hidden:checked ~ .count,
.hidden:checked ~ .word {
  box-shadow: inset 20rem 2rem white;
}

.count {
  border-radius: 50%;
  min-width: 1.8rem;
  text-align: center;
  font-size: 1.4rem;
  line-height: 1.8rem;
}

.word {
  padding: 0 0.2rem;
  border-radius: 0.4rem;
  font-size: 1.6rem;
}

.obsolete {
  opacity: 0;
}

footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 1.2rem;
  padding: 2.4rem 3.6rem;
  color: #555;
  background-color: #eee;
  font-size: 1.4rem;
}

footer > div:last-child {
  text-align: end;
}

a {
  color: black;
  text-decoration: none;
}

@keyframes add {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

Duplicate Word Finder

      <button id="copy" class="pure-material-button-contained">Copy</button>
      <button id="clear" class="pure-material-button-text">Clear</button>

            <input id="spellcheck" type="checkbox" checked>
            Spell Check

      <input id="length" type="range" min="1" max="10" value="4">
      Minimum Word Length: <output>4</output>

    <textarea>
Paste your text by pressing Ctrl+V or ⌘+V. (Once you click here, these instructions will be cleared for your convenience ;)

The slider on the top right can be used to adjust the minimum length of words to detect. The default setting is 4, so words like 'and', 'for', 'the', etc. won't pollute the analysis. The duplicate words can be found below the slider highlighted by various colors. The list is sorted by the number of occurrence starting with the highest. The highlighting for any individual word can be turned off by clicking on the word in the list.

You can edit your text here, duplicates are detected real time. When you're finished editing, you can copy or clear the result using the corresponding buttons. You can also turn off the spell checker if you don't need it.

~~~

I often find myself sending emails and messages consisting of two or three sentences. This is where I usually commit an unintentional word repetition, but only realize it after hitting send. This tool comes handy for such cases, and you're free to use it for your benefit as well! :)
</textarea>

    Created by Bence Szabó (finnhvman)

    Twitter   |
    LinkedIn   |
    CodePen

    Created with

    Pure CSS Material Components

<template>

            <input class="hidden" type="checkbox">

</template>

Народ подскажите пожалуйста. Есть скрипт который ищет дубли в контенте - проблема в том что при нажатии на поле ввода (textarea) демо текст исчезает, как добится такого же результата с <input id="length" type="range" min="1" max="10" value="4"> данным полем. Попробовала изменить ИД не помогло поле все ровно не исчезает. Подскажите пожалуйста.

A:

const isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
const isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

const copy = document.querySelector("#copy");
const clear = document.querySelector("#clear");
const spellcheck = document.querySelector("#spellcheck");
const textarea = document.querySelector("textarea");
const highlights = document.querySelector("#highlights");
const length = document.querySelector("#length");
const output = document.querySelector("output");
const list = document.querySelector("#list");
const template = document.querySelector("template");

let hiddens = [];
let duplicates = {};

// Text analysis
const count = (text, minLength) => {
  // https://mathiasbynens.be/notes/es-unicode-property-escapes#word
  const wordRegex = isChrome || isSafari
  ? new RegExp(`([\\p{Alphabetic}\\p{Mark}\\p{Decimal_Number}\\p{Connector_Punctuation}\\p{Join_Control}]+){${minLength},}`, 'gu')
  : new RegExp(`(\\w+){${minLength},}`, 'g');
  let result;
  const words = {};
  while ((result = wordRegex.exec(text)) !== null) {
    const word = result[0].toLowerCase();
    if (!words[word]) {
      words[word] = [];
    }
    words[word].push(result.index);
    words[word].push(result.index + word.length);
  }
  return words;
};

// Array manipulation
const duplicatePass = ([key, value]) => 2 < value.length;

const occurrenceComparator = ([keyA, valueA], [keyB, valueB]) =>
  valueB.length - valueA.length;

const numberComparator = (numberA, numberB) => numberA - numberB;

const differ = (object, [key, value], index) => {
  object[key] = {
    action: object[key] ? "KEEP" : "ADD",
    word: key,
    occurrences: value,
    index
  };
  return object;
};

const cleaner = (object, [word, details]) => {
  if (details.action) {
    delete details.action;
    object[word] = details;
  }
  return object;
};

const flattener = (array, details) => [...array, ...details.occurrences];

// DOM manipulation
const update = (item, details) => {
  item.style.zIndex = details.occurrences.length / 2;
  item.style.top = `${0.6 + details.index * 3}rem`;
  item.querySelector(".count").textContent = details.occurrences.length / 2;
};

const add = (word, details) => {
  const node = document.importNode(template.content, true);
  list.appendChild(node);
  const item = list.lastElementChild;
  item.id = `word-${word}`;
  const hidden = item.querySelector(".hidden");
  hidden.name = word;
  hidden.checked = hiddens.includes(word);
  hidden.addEventListener("change", handleToggle);
  item.querySelector(".word").textContent = word;
  update(item, details);
};

const keep = (word, details) => {
  const item = document.querySelector(`#word-${word}`);
  update(item, details);
};

const markObsolete = word => {
  document.querySelector(`#word-${word}`).classList.add("obsolete");
};

const remove = item => item.remove();

const removeObsolete = () => {
  document.querySelectorAll(".obsolete").forEach(remove);
};

const render = ([word, details]) => {
  if (details.action === "ADD") {
    add(word, details);
  } else if (details.action === "KEEP") {
    keep(word, details);
  } else {
    markObsolete(word);
  }
};

const getHue = word => {
  return (
    360 -
    360 / Object.keys(duplicates).length * duplicates[word.toLowerCase()].index
  );
};

const getHSL = word => {
  const hue = getHue(word);
  return `hsl(${hue + 20}, 100%, ${180 < hue && hue < 360 ? 80 : 50}%)`;
};

const colorize = word => {
  const color = getHSL(word);
  const count = document.querySelector(`#word-${word} .count`);
  const wordElement = document.querySelector(`#word-${word} .word`);
  count.style.borderColor = color;
  count.style.backgroundColor = color;
  wordElement.style.borderColor = color;
  wordElement.style.backgroundColor = color;
};

const highlight = (occurrence, index, occurrences) => {
  let node;
  if (index < occurrences.length - 1) {
    if (index % 2) {
      const word = textarea.value.substring(occurrence, occurrences[index + 1]);
      node = document.createElement("mark");
      node.textContent = word;
      if (!hiddens.includes(word.toLowerCase())) {
        const color = getHSL(word);
        node.style.background = color;
        node.style.border = `0.2rem solid ${color}`;
      }
    } else {
      const text = textarea.value.substring(occurrence, occurrences[index + 1]);
      node = document.createTextNode(text);
    }
  } else {
    const text = textarea.value.substring(occurrence);
    node = document.createTextNode(text + "\r\n\r\n");
  }
  highlights.appendChild(node);
};

const handleChange = () => {
  // Count words
  const words = count(textarea.value, length.value);

  // Diff word stats with previous
  const diff = Object.entries(words)
    .filter(duplicatePass)
    .sort(occurrenceComparator)
    .reduce(differ, duplicates);

  // Render items
  Object.entries(diff).forEach(render);

  // Clean obsolete from duplicates
  duplicates = Object.entries(diff).reduce(cleaner, {});

  // Adjust height of list
  list.style.height = `${1.2 + Object.keys(duplicates).length * 3}rem`;

  // Colorize items
  Object.keys(duplicates).forEach(colorize);

  // Flatten occurrences
  const occurrences = Object.values(duplicates)
    .reduce(flattener, [0])
    .sort(numberComparator);

  // Highlight
  while (highlights.firstChild) {
    highlights.removeChild(highlights.firstChild);
  }
  occurrences.forEach(highlight);

  // Remove
  window.setTimeout(removeObsolete, 400);

 if(textarea.value == ''){
    length.style.display = 'none';
  }else{
    length.style.display = 'inline-block';
  }

};

const handleToggle = event => {
  const word = event.target.name;
  if (event.target.checked) {
    if (!hiddens.includes(word)) {
      hiddens.push(word);
    }
  } else {
    const index = hiddens.indexOf(word);
    if (0 <= index) {
      hiddens.splice(index, 1);
    }
  }
  handleChange();
};

copy.addEventListener("click", () => {
  textarea.select();
  document.execCommand("copy");
});

clear.addEventListener("click", () => {
  textarea.value = "";
  textarea.focus();
  handleChange();
});

spellcheck.addEventListener("change", event => {
  textarea.setAttribute("spellcheck", event.target.checked.toString());
  const { value } = textarea;
  textarea.value = value + " ";
  textarea.value = value;
});

textarea.addEventListener("scroll", event => {
  highlights.scrollTop = event.target.scrollTop;
});

textarea.addEventListener(
  "focus",
  () => {
    textarea.value = "";
    handleChange();
  },
  {
    once: true
  }
);

textarea.addEventListener("input", handleChange);
length.addEventListener("input", handleChange);
length.addEventListener("input", () => (output.textContent = length.value));

handleChange();
html {
  font-family: Roboto, Helvetica, Arial, sans-serif;
  font-size: 62.5%;
  font-weight: normal;
}

body {
  margin: 0;
}

header {
  padding: 1.2rem 2.4rem;
  background-color: #2196f3;
}

h1 {
  margin: 0;
  font-size: 4.8rem;
  font-weight: normal;
  color: white;
}

main {
  display: flex;
  flex-flow: row wrap;
  padding: 0 1.2rem;
}

button {
  margin: 0 12px;
}

#actions {
  flex: 3 0 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 1.2rem;
}

#actions > label {
  margin-right: 0.6rem;
}

#options {
  flex: 1 0 0;
  padding: 1.2rem;
  min-width: 20rem;
}

#options > label {
  width: 100%;
}

hr {
  margin: 0;
  border: none;
  width: 100%;
  height: 0;
}

mark {
  margin: -0.2rem;
  border: 0.2rem solid transparent;
  border-radius: 0.4rem;
  color: transparent;
  background: transparent;
}

#text {
  position: relative;
  flex: 3 0 0;
  padding: 0 1.2rem;
  transition: height 0.3s;
}

textarea,
#highlights {
  position: absolute;
  top: 0;
  bottom: 0;
  margin: 0;
  border: solid 0.1rem rgba(0, 0, 0, 0.54);
  border-radius: 0.4rem;
  padding: 1.3rem;
  font-family: Roboto, Helvetica, Arial, sans-serif;
  font-size: 1.6rem;
  font-weight: normal;
  line-height: 2rem;
  outline: none;
  transition: height 0.3s;
}

textarea {
  box-sizing: border-box;
  width: calc(100% - 2.4rem);
  height: 100%;
  background: transparent;
  resize: none;
}

textarea:focus {
  border: solid 0.2rem #2196f3;
  padding: 1.2rem;
}

#highlights {
  z-index: -1;
  box-sizing: border-box;
  width: calc(100% - 2.4rem);
  white-space: pre-wrap;
  word-wrap: break-word;
  color: transparent;
  overflow-x: hidden;
  overflow-y: auto;
}

ol {
  margin: 0;
  padding: 0;
  list-style: none;
}

#list {
  position: relative;
  flex: 1 0 0;
  padding: 0 1.2rem;
  min-width: 20rem;
  min-height: calc(100vh - 24rem);
  transition: height 0.3s;
}

.item {
  position: absolute;
  transition: top 0.3s, opacity 0.3s;
  animation: add 0.3s;
}

.item > label {
  cursor: pointer;
}

.hidden {
  display: none;
}

.count,
.word {
  display: inline-block;
  border: solid 0.2rem;
  box-shadow: inset 20rem 2rem transparent;
  transition: border 0.3s, background 0.3s, box-shadow 0.3s;
}

.hidden:checked ~ .count,
.hidden:checked ~ .word {
  box-shadow: inset 20rem 2rem white;
}

.count {
  border-radius: 50%;
  min-width: 1.8rem;
  text-align: center;
  font-size: 1.4rem;
  line-height: 1.8rem;
}

.word {
  padding: 0 0.2rem;
  border-radius: 0.4rem;
  font-size: 1.6rem;
}

.obsolete {
  opacity: 0;
}

footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 1.2rem;
  padding: 2.4rem 3.6rem;
  color: #555;
  background-color: #eee;
  font-size: 1.4rem;
}

footer > div:last-child {
  text-align: end;
}

a {
  color: black;
  text-decoration: none;
}

@keyframes add {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

Duplicate Word Finder

      <button id="copy" class="pure-material-button-contained">Copy</button>
      <button id="clear" class="pure-material-button-text">Clear</button>

            <input id="spellcheck" type="checkbox" checked>
            Spell Check

      <input id="length" type="range" min="1" max="10" value="4">
      Minimum Word Length: <output>4</output>

    <textarea>
Paste your text by pressing Ctrl+V or ⌘+V. (Once you click here, these instructions will be cleared for your convenience ;)

The slider on the top right can be used to adjust the minimum length of words to detect. The default setting is 4, so words like 'and', 'for', 'the', etc. won't pollute the analysis. The duplicate words can be found below the slider highlighted by various colors. The list is sorted by the number of occurrence starting with the highest. The highlighting for any individual word can be turned off by clicking on the word in the list.

You can edit your text here, duplicates are detected real time. When you're finished editing, you can copy or clear the result using the corresponding buttons. You can also turn off the spell checker if you don't need it.

~~~

I often find myself sending emails and messages consisting of two or three sentences. This is where I usually commit an unintentional word repetition, but only realize it after hitting send. This tool comes handy for such cases, and you're free to use it for your benefit as well! :)
</textarea>

    Created by Bence Szabó (finnhvman)

    Twitter   |
    LinkedIn   |
    CodePen

    Created with

    Pure CSS Material Components

<template>

            <input class="hidden" type="checkbox">

</template>

В handleChange() добавил проверяющую функцию:
if(textarea.value == ''){
  length.style.display = 'none';
}else{
  length.style.display = 'inline-block';
}

Мне кажется тут лучше для всего #options применять это дело, а то остаются непонятные юзеру строки текста. Но думаю с этим уже разберешься.


text:
Q: How to monitor performance of servers on a different domain using Perfmon in Windows 7 We just upgraded our developer machines from 32 bit Windows XP to 64 bit Windows 7 Ultimate. With Windows XP we were able to do a live monitor of the CPU usage of servers that resided on a separate domain from our developer machines. We would use the following NET USE command to get authenticated to those servers.
NET USE server_ip /USER:domain\user_name password
Unfortunately we are unable to get Perfmon in combination with NET USE to work through Windows 7. The servers we are trying to monitor are running Windows Server 2008 R2 and Windows Server 2003. We receive the following error when trying to connect to these servers.
Unable to connect to machine
Does anyone know how to monitor the CPU usage of remote machines on different domains through Perfmon in Windows 7?

A: The key was to use the runas command in an elevated permissions command prompt using a login associated with the domain where the servers I want to monitor reside. The command is as follows:
runas /netonly /user:domain\username "mmc"
I run mmc and add the perfmon snap in rather than running perfmon so I can save my settings (I am pretty disapointed this can't be done directly through perfmon). After I have my settings saved I use this command to open those settings:
runas /netonly /user:domain\username "mmc \somepath\savesettings.msc"


text:
Q: How can I load and render an OBJ file that may include Triangles, Quads, or N-Gons in OpenGL? I have the following c++ code to load an object file, at least the vertices and the vertex indices.
 bool ObjMeshImporter::from_file(const std::string& filepath, nelems::Mesh* pMesh)
  {
    std::ifstream in(filepath, std::ios::in);
    if (!in)
    {
      return false;
    }

    std::vector<glm::vec3> t_vert;

    std::string line;
    while (std::getline(in, line))
    {
      if (line.substr(0, 2) == "v ")
      {
        // read vertices
        std::istringstream s(line.substr(2));
        glm::vec3 v; s >> v.x; s >> v.y; s >> v.z;

        // Add to temporary vertices before indexing
        t_vert.push_back(v);
      }
      else if (line.substr(0, 2) == "f ")
      {
        // TODO: Store UVs and Normals
        unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
        int count_found = sscanf_s(line.substr(2).c_str(),
          "%d/%d/%d %d/%d/%d %d/%d/%d\n",
          &vertexIndex[0], &uvIndex[0], &normalIndex[0],
          &vertexIndex[1], &uvIndex[1], &normalIndex[1],
          &vertexIndex[2], &uvIndex[2], &normalIndex[2]);

        if (count_found != 9) {
          return false;
        }

        pMesh->add_vertex_index(vertexIndex[0]-1);
        pMesh->add_vertex_index(vertexIndex[1]-1);
        pMesh->add_vertex_index(vertexIndex[2]-1);

      }
    }

    // Now use the indices to create the concrete vertices for the mesh
    for (auto v_idx : pMesh->GetVertexIndices())
    {
      glm::vec3 vertex = t_vert[v_idx];
      pMesh->add_vertex(vertex);
    }
    return true;
  }

It works pretty good for an object like this (Blender icosphere):

This model is made of triangles.
But when I load one which has quads, it doesnt work:

of course, because this is my face render method:
glDrawArrays(GL_TRIANGLES, 0, (GLsizei)mVertexIndices.size());

So I know, I have to extend the parser and for every line in "f" check how many indices I have got and best would be to store a VFace-class that knows how many vertices a face is made of - ok.
So I would render faces with tris as GL_TRIANGLE and faces with quads as GL_QUADS... but what about the NGONS? And also how to render the lines?
EDIT: I saw there is GL_POLYGON. But do I have to create separate vertexbuffers for these?

A:
No, I want to render faces with triangles, quads or ngons.

I believe that this question has no reasonable solution.
Modern graphics hardware renders only 3 types of primitives: points, lines segments and triangles. So that direct answer is that you have to generate a triangulation from any soup of non-triangle geometry (quads, n-polygons, B-Spline surfaces, analytical surfaces, etc.). This can be done by your own code or using existing library (the latter is preferred, as splitting polygons is not that trivial - I've seen several implementation working in general, but failing in one or another use case on some OBJ files).
There are good reasons why modern hardware operates only on triangles - they can be used for rendering any other geometry, they are perfectly parallelized (compared to geometry having variable number of nodes in element) and this makes hardware simpler.
Here are some approaches for rendering non-triangles in OpenGL with comments:

*

*GL_QUADS. Deprecated since OpenGL 3.0. It should be noted, though, that according to various publications and discussions, at least NVIDIA and probably AMD hardware still actually have hardware-accelerated support for these primitives. You will need two different draw passes for rendering triangles mixed with quads (e.g. split indices for each primitive type, although you may still share common vertex buffer). If you ever used GL_QUADS in application, you may also notice that non-flat quad passed to graphics hardware is split into triangles, and different GPU vendors do this in different order (e.g. produce different triangle pair).

*GL_POLYGON. Also Deprecated since OpenGL 3.0. This primitive existed in OpenGL at days, when vertex processing has been done not by graphics hardware but by CPU. So that this one probably never had any real hardware acceleration - OpenGL driver just split polygons into triangles in a slow and inefficient way. There is another reason why GL_POLYGON is practically useless for OBJ files - GL_POLYGON is only for convex polygons (trivially splittable into triangles), while OBJ files often contain concave polygons. You may find some OBJ specifications on internet requiring polygons being convex, while others not specifying polygon details at all - but practically you cannot ignore this, as real-world OBJ file do have complex polygons (as long as you care about reading arbitrary files).

*GL_PATCHES for Tessellation Shaders. These are designed for hardware-accelerated triangulation of patches of fixed size, which is a powerful mechanism for displaying smoothable surfaces. These, however, have nothing to do with n-polygons in OBJ file, as defining geometry for tessellation shader requires following very different patterns.

*Adjacency primitives for Geometry Shaders. Primitives like GL_TRIANGLES_ADJACENCY provide additional information about triangle surroundings, but they also has no direct relationship to n-polygons in OBJ file. Unlike Tesselation Shaders, Geometry Shader allows provoking variable number of new triangles with arbitrary specified node positions. This technically allows generating arbitrary n-polygon split into triangles within Geometry Shader. Although to achieve that, geometry data have to be provided not within main vertex data, but with additional structures (like TBO or similar). Practically, this approach makes no sense to implement (as long as you are not doing some research), as Geometry Shaders are proved to be very inefficient for tessellation-alike tasks, leading to very poor performance.

*Compute Shaders. These can be used for arbitrary tasks, including splitting polygons into triangles using custom data structures and/or rendering them, but this is unlikely a reliable way for rendering polygons - also a subject for research rather than practical solution.


text:
Q: Array only values in keys numeric order I've an array like this:
8:16, 9:8, 10:11, 11:5, 12:5, 13:13, 14:42

and I want it to be:
0:16, 1:8, 2:11 ....

in PHP.
I know I can do an own function. but I think it should be one built in.
I've tried: array_values

A: this function should do the trick:
$array = array_values($array);

see: http://php.net/array_values

A: Please try this i think  its your exact requirement.
$arr = array('8:16', '9:8','10:11');

$i=0;
foreach($arr as $val){

    $arr1 = explode(':',$val);
    $arr2[] = $i.":".$arr1[1];
    $i++;
}
print_r($arr2);

A: You can use natsort()
Documentation

A: Use
array_values($yourArray);

I think it should work properly.

A: I think @Praveenkalal sussed what you meant, but I'll just add another alternative:
$i = 0;
array_walk($array, function(&$v) use(&$i) {
  $v = preg_replace('/\d+:(\d+)/', ($i++).':$1', $v);
});

run code
Alternatively, if you're array is already zero-indexed like we have assumed this will work:
foreach($array as $key => &$val)
  $val = preg_replace('/\d+:(\d+)/', $key.':$1', $val);

run code

arrays... fun fun fun
Just to clarify - there's no built-in function because what you are doing is too specific - if your array values are key:value pairs then normally you'd have mapped them to an array as such - which is why we all thought array_values would be sufficient.
For example if your data was in a format like:
$array = array(
  8  => 16,
  9  => 8,
  10 => 11,
 ...
);

you'd have the full range of php's internal functionality available to you.


text:
Q: How do I log or trace using shinytest? I would like to be able to see what happens inside the reactive({...}) parts in my code. I thought that using shinytest could be a way to execute parts of my application which use Shiny Modules and learn about callModule.
I tried the following in my code to log/trace/print.
print("hello1")
message("hello2")
cat(file=stderr(), "hello3")
logging::loginfo("hello4")

runtest.R
library(shinytest)
testApp("/home/eddy/rwork/filters", "mytest")
viewTestDiff("/home/eddy/rwork/filters", interactive = FALSE)

output:
Rscript runtest.R
Running mytest.R
==== Comparing mytest... No changes.
==== mytest ====
No differences between expected and current results

How can I add some trace output to the test run?

A: I don't think there's a really convenient way to see app output in shinytest right now, but there is this method on ShinyDriver objects:

app$getDebugLog() queries one or more of the debug logs: shiny_console, browser or shinytest.
https://rstudio.github.io/shinytest/reference/ShinyDriver.html

You could use this with the shiny_console option to print app output in individual tests like:
# mytest.R

app <- ShinyDriver$new()

...

log <- app$getDebugLog("shiny_console")
print(log)

A: shinytest integrates with the shiny concept of export values while in test, so you can use the function, shiny::exportTestValues() to create a named expressions with the values, including the reactive, you want to export.
For example, if you had the reactive data.frame, scaledData, that used some sort of input binding in your app code, you could do the following:
scaledData <- reactive({
  dummyData[, "y"] <- dummyData[, "y"] * input$scale
  return(dummyData)
})

# The scaledData will be captured as a json object in the shinytest output
exportTestValues(scaledData = scaledData())

This will capture the reactive value in the snapshot under the exports key in the json file, so you can then use this in your test comparisons (as well as view the data if you'd like).
One last note is that these export values only get run when the app is in test mode, e.g. isTRUE(getOption("shiny.testmode")).
I wrote a blog post about how I use this to test DataTables in shiny, you can read that here: https://nadirsidi.github.io/Shinytest/.

A: You can alocate an print(), cat(), warning() inside your reactive function to check value o class of your object inside R prompt. This works for me using only Shinny in RStudio without shinytest.
Additioanlly, as you said its not working the previous options, you can place a write.myformat() function in order to write any kind of object and check it externally.


text:
Q: Selenium : NoSuchElementException in IE11 JAVA I am trying to execute selenium webdriver java code in IE11 , it throws "NoSuchElementException"  even after the page is loaded completely.

*

*Web driver : IEDriverServer_Win32_2.53.0

*IE version : 11

*selenium : selenium-server-standalone-2.53.0.jar

*java : jdk1.8

The application consists of LoginPage and home page. In Home Page, customers details can be added after clicking "Add customer" button.
Logging into the application is executing successfully in IE11. After log in, NoSuchElementException is thrown for "Add customer" button.
The following is the selenium Java code:
     driver.findElement(By.id("btnAddCustToQueue")).click();

The following is the jsp code :

Add
Customer

Below is the exception thrown :
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with id == btnAddCustToQueue (WARNING: The server did not provide any stacktrace information)

I have used explicit wait for the "Add customer" button to load. In this case, "TimeOutException" as show below:
     Exception in thread "main" org.openqa.selenium.TimeoutException: Timed out after 30 seconds waiting for element to be clickable: By.id: btnAddCustToQueue

The same code works fine with CHROME browser.
I am not sure whether there is problem with latest IE.
Thanks in advance.

A: Try this:
driver.findElement(By.xpath("//DIV[contains(@id,'btnAddCustToQueue')")).click();

It should work if the HTML you uploaded is this
Next time upload the webpage you are trying this on so we can try this out to and maybe find a better method like that.


text:
Q: Beagle Bone Black not retaining static IP I have a Beagle Bone Black to which I have assigned a static IP. My interfaces file is as follows.
auto eth0
allow-hotplug eth0
iface eth0 inet static
address 172.16.41.226
netmask 255.255.255.0
gateway 172.16.41.1

The BBB has the IP that I assigned after boot up, but the IP is lost when I unplug the LAN cable and plug it back.
ifconfig command does not show any ip against eth0 .