text:
Q: User authentication; PAM or Radius? At college I'm part of a group of students that keep a server infrastructure running for the students. Lately we've been having a lot of trouble with the servers, and we decided that it's probably better to start from scratch and reinstall everything.
Currently we use PAM (libpam-mysql) for user authentication. Users need to be able to use their accounts to login over SSH, FTP, SMB (Samba), mail servers, our website, and maybe in future also ownCloud. Most of the user management happens through the website (PHP, MySQL), which is also where users can configure their hosting packages (including vhosts). All the servers are running Debian.
One of the newcomers pointed out to me that if we're going to reinstall everything anyway, it's probably better for us to use Radius in stead of PAM. I myself (being relatively new) am not experienced with either two, and Google proved to be surprisingly unhelpful when doing some research on the matter.
For our use case, but also in general, which would be more suited? Does one have any big advantages over the other?
Thanks in advance.

A: It would be very hard to use RADIUS without using PAM. PAM defines an API for accessing credentials providers (and other session related stuff) which can be the usual files, NIS, LDAP, RADIUS....
The bit you're talking about changing is the credentials provider. There are places that PAM can't go - and to handle these cases it might be worth looking at whether the credentials providers which are supported are also supported under PAM (and note that in some cases it's possible to stack providers e.g. CAS on top of LDAP). Furthermore, PAM can use multipe credential providers.
You need to look at the estate for which you are trying to manage and identify what providers it could support, then think about how much effort is involved in configuring, coding and migrating.
(IME RADIUS never got much beyond authentication for network infrastructure - it's probably still worth considering if you need to implement EAP)


text:
Q: Retrieve only specific properties with REST GET API I need to define a REST API which is supposed to take the object's unique identifier and return back the content. The content is retrieved from the database and is of JSON type.
So, I have a REST URL like this -
GET /data/{typename}/{objectid}

This would return  the entire object content.
However, the content of the object could be large in size and so caller may like to specify only some or few of the properties to be sent as a response.
The natural thought that comes to me is to add a BODY to the GET API where user could specify the list of property names on that object to be retrieved.
But on doing some further research, it appears that a GET API with BODY is not recommended.
The other option that I can think of is to pass the property names in query string -
GET /data/{typename}/{objectid}?property=prop1&property=prop2...

But the list could easily become large.
Any suggestion on how should my API look like? Do I have to use POST?

A: Technically, using POST will work but is not preferred. If you are reading, use GET. Facebook, for example, has a similar use case where the /me endpoint has many filters, and the call is GET.
The final URL would be,
/me?fields=id,name,about,age_range,devices,currency,education
You can try it yourself from here,
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=me%3Ffields%3Did%2Cname%2Cabout%2Cage_range%2Cdevices%2Ccurrency%2Ceducation&version=v2.8
I recommend reading more about GraphAPI https://developers.facebook.com/docs/graph-api/overview/ and GraphQL https://graphql.org/

A: I would recommend using POST, because GET has a length limit.
What is the maximum length of a URL in different browsers?
otherwise you could make your query string look like this (for array)
so close :)
GET /data/{typename}/{objectid}?property[]=prop1&property[]=prop2...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Call code per click button can someone help me and tell me where I can put my xml code to be called when it's clicked on this button. Thank you all for the answer. Attached is my xml code and code for the button.

    <?php wp_nonce_field('woocommerce-register', 'woocommerce-register-nonce'); ?>
    <input type="submit" class="woocommerce-Button button" name="register" value="<?php esc_attr_e('Register', 'woocommerce'); ?>" />

<?php
//rest/customers
$xml = "<customer><activation-code>" . rand(100000, 999999) . "</activation-code>
    <area-code-id type=\"integer\"></area-code-id>
    <billing-failure-date type=\"datetime\" nil=\"true\"/>
    <created-at type=\"datetime\"></created-at>
    <email>" . $current_user->user_email . "</email>
    <first-name>" . $resultVorname->value . "</first-name>
    <id type=\"integer\"></id>
    <language-id type=\"integer\">2</language-id>
    <last-name>" . $resultNachname->value . "</last-name>
    <npvr-limit type=\"integer\" nil=\"true\"/>
    <npvr-quota type=\"integer\">360000</npvr-quota>
    <other-than-stb-devices-limit type=\"integer\">1</other-than-stb-devices-limit>
    <phone>" . $resultTelefon->value . "</phone>
    <pin>" . rand(1000, 9999) . "</pin>
    <pvr-limit>NO_LIMIT</pvr-limit>
    <secondary-pin>" . rand(1000, 9999) . "</secondary-pin>
    <status>enabled</status>
    <stb-devices-limit type=\"integer\">1</stb-devices-limit>
    <updated-at type=\"datetime\"></updated-at>
    <uuid></uuid>
    <external-id nil=\"true\"/>
    <npvr-quota-used type=\"integer\">1</npvr-quota-used>
    <npvr-limit-used type=\"integer\">1</npvr-limit-used>
    <area-code-external-id nil=\"true\"/>
    <language-external-id nil=\"true\"/>
    <address-attributes>
    <city>" . $resultOrt->value . "</city>
    <street>" . $resultStrasse->value . "</street>
    <postal-code>" . $resultPostleitzahl->value . "</postal-code>
    <province-id>119</province-id>
    </address-attributes>
    </customer>";

$url = 'https://xxx.xxx.xx.xx:xxxx/rest/customers';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', 'Authorization: Basic QTFDVjVsaGl5d1d2NXh3UWJ0OFE6'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

$data = curl_exec($ch);
//print $data;
//var_dump($data);
$xml = simplexml_load_string($data);
$json = json_encode($xml);
$arr = json_decode($json, true);
//print_r($arr['id']);

if (curl_errno($ch))
    print curl_error($ch);
else
    curl_close($ch);
?>

The code should be executed when it is clicked on the registration button, so I want to send this xml to the server immediately.
and this is from the whole action where I noticed that this button is called..

<?php do_action( 'woocommerce_register_form' ); ?>

    <?php wp_nonce_field( 'woocommerce-register', 'woocommerce-register-nonce' ); ?>
    <input type="submit" class="woocommerce-Button button" name="register" value="<?php esc_attr_e( 'Register', 'woocommerce' ); ?>"/>

   <?php


text:
Q: Close a file handle opened by .NET I'm working on a script to rename files based on EXIF data.
param([string]$path)

# http://blogs.technet.com/b/jamesone/archive/2007/07/13/exploring-photographic-exif-data-using-powershell-of-course.aspx
[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll") | out-null

function MakeString {
    $s=""
    for ($i=0 ; $i -le $args[0].value.length; $i ++) {
        $s = $s + [char]$args[0].value[$i]
    }
    return $s
}

$files = Get-ChildItem -Path $path
foreach ($file in $files) {
    if ($file.Extension -ne ".jpg") { continue }
    if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
    $exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
    $captureDate = MakeString $exif.GetPropertyItem(36867)
    $captureDate = ($captureDate -replace ":", '-').Substring(0,19)
    $newFilename = $captureDate + " " + $file.Name.Trim()
    $file.Name + " -> " + $newFilename
    $file |Rename-Item -NewName $newFilename
}

Reading the date from EXIF is no problem, but when I try to rename the file I get this error message:
Rename-Item : The process cannot access the file because it is being used by another process.
At D:\Norwegen\RenamePhotos.ps1:25 char:12
+     $file |Rename-Item -NewName $newFilename
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Norwegen\P1270465 (1920x1433).jpg:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

When I monitor the directory in ProcMon I can see that the files are closed rather late:

(look at the highlighted line, it's from an earlier file in the middle of the entries from the file currently being processed)
So, how can I close the file (which is probably still open from the EXIF read) so I can rename it?
What I already tried to close the open file:
Remove-Variable exif
$file.Close()

A: Since you only read from the the file, then a call to Dispose() should do the trick. Ex.
    foreach ($file in $files) {
    if ($file.Extension -ne ".jpg") { continue }
    if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
    $exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
    $captureDate = MakeString $exif.GetPropertyItem(36867)

    #Disposing object as soon as possible
    $exif.Dispose()

    $captureDate = ($captureDate -replace ":", '-').Substring(0,19)
    $newFilename = $captureDate + " " + $file.Name.Trim()
    $file.Name + " -> " + $newFilename
    $file |Rename-Item -NewName $newFilename
}


text:
Q: Using GetAtt in inline Lambda nodejs code I have created a simple cloud formation template that holds together a "message splitter" for one SQS queue, with the messages being distributed into 4 other queues.
The relevant parts of the Cloudformation template are
ProdSqsDistributor:
  Type: 'AWS::Lambda::Function'
  Properties:
    Code:
      ZipFile: |
        var AWS = require('aws-sdk');
        var sqs = new AWS.SQS({region : 'us-east-1'});
        var sns = new AWS.SNS({region : 'us-east-1'});

        exports.handler = async (event) => {
          //console.log('Received event:', JSON.stringify(event, null, 2));
          const promises = event.Records.map( async message => {
              var messageId = message.messageId;
              var body = message.body;
              console.log('SQS message %s: %j', messageId, body);
              if (body.indexOf('App\\\\Jobs\\\\CNC\\\\ConvertFile') !== -1){
                console.log('cnc1 matched');

                await sqs.sendMessage({MessageBody: body, QueueUrl: '!GetAtt ProdCnc.Arn'})

...

ProdCnc:
  Type: 'AWS::SQS::Queue'
  Properties:
    DelaySeconds: 0
    VisibilityTimeout: 120
    ReceiveMessageWaitTimeSeconds: 20

As per the template, I want to embed the arn of the target queue into the inline Lambda nodejs code.
The Cloudformation template runs successfully, however the queue splitting does not work. When I look at the created lambda function, it appears as if the GetAtt call has not been resolved:

I'm looking for a way to resolve/execute the GetAtt call inside the inlined Lambda code.

A: Try !Sub:
ProdSqsDistributor:
  Type: 'AWS::Lambda::Function'
  Properties:
    Code:
      ZipFile: !Sub
        - |
          var AWS = require('aws-sdk');
          var sqs = new AWS.SQS({region : 'us-east-1'});
          var sns = new AWS.SNS({region : 'us-east-1'});

          exports.handler = async (event) => {
            //console.log('Rcvd event:', JSON.stringify(event, null, 2));
            const promises = event.Records.map( async message => {
              var messageId = message.messageId;
              var body = message.body;
              console.log('SQS message %s: %j', messageId, body);
              if (body.indexOf('App\\\\Jobs\\\\CNC\\\\ConvertFile') !== -1){
                console.log('cnc1 matched');

                await sqs.sendMessage({MessageBody: body, QueueUrl: '${ProdCncArb}'})
        - ProdCncArb: !GetAtt ProdCnc.Arn

A: I think you might need to write it thus:
...
ZipFile: !Sub |
  ...


text:
Q: Spring Boot stuck at Initializing Spring DispatcherServlet I'm new to Spring Boot and I'm trying to develop a user registration and login system.
After I run the program on Eclipse, it starts successfully; Started CustomerApplication in 2.318 seconds (JVM running for 2.938).
But the problem is when I try to access the page from the browser it keeps loading my Thymeleaf page.
In the console it says: Initializing Spring DispatcherServlet 'dispatcherServlet'
My useraccountcontroller.java controller class:
@Controller
public class UserAccountController {

    @Autowired
    private CustomerRepository userRepository;

    @Autowired
    private ConfirmationTokenRepository confirmationTokenRepository;

    @Autowired
    private EmailSenderService emailSenderService;

    @RequestMapping(value="/register", method = RequestMethod.GET)
    public ModelAndView displayRegistration(ModelAndView modelAndView, Customer user)
    {
        modelAndView.addObject("user", user);
        modelAndView.setViewName("register");
        return modelAndView;
    }

    @RequestMapping(value="/register", method = RequestMethod.POST)
    public ModelAndView registerUser(ModelAndView modelAndView, Customer user)
    {

        Customer existingUser = userRepository.findByEmailIdIgnoreCase(user.getEmailId());
        if(existingUser != null)
        {
            modelAndView.addObject("message","This email already exists!");
            modelAndView.setViewName("error");
        }
        else
        {
            userRepository.save(user);

            ConfirmationToken confirmationToken = new ConfirmationToken(user);

            confirmationTokenRepository.save(confirmationToken);

            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setTo(user.getEmailId());
            mailMessage.setSubject("Complete Registration!");
            mailMessage.setFrom("rukshan033@gmail.com");
            mailMessage.setText("To confirm your account, please click here : "
            +"http://localhost:8082/confirm-account?token="+confirmationToken.getConfirmationToken());

            emailSenderService.sendEmail(mailMessage);

            modelAndView.addObject("emailId", user.getEmailId());

            modelAndView.setViewName("successfulRegisteration");
        }

        return modelAndView;
    }

    @RequestMapping(value="/confirm-account", method= {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView confirmUserAccount(ModelAndView modelAndView, @RequestParam("token")String confirmationToken)
    {
        //System.out.println("tokkon issa0: "+confirmationToken);
        ConfirmationToken token = confirmationTokenRepository.findByConfirmationToken(confirmationToken);

        if(token != null)
        {
            //System.out.println("tokkon issa1: "+token);
            Customer user = token.getCustomer();
            //Customer user = userRepository.findByEmailIdIgnoreCase(token.getCustomer().getEmailId());
            user.setEnabled(true);
            userRepository.save(user);
            modelAndView.setViewName("accountVerified");
        }
        else
        {
            //System.out.println("tokkon issa2: "+token);
            modelAndView.addObject("message","The link is invalid or broken!");
            modelAndView.setViewName("error");
        }

        return modelAndView;
    }

    @RequestMapping(value="/login", method= {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView login(ModelAndView modelAndView, @RequestParam("emailID")String email, @RequestParam("password")String password)
    {
        Customer user = userRepository.findByEmailIdIgnoreCase(email);

        if(user == null) {
            modelAndView.addObject("message1","Invalid E-mail. Please try again.");
            modelAndView.setViewName("login");
        }
        /*else if (user != null && user.getPassword()!=password) {
            modelAndView.addObject("message1","Incorrect password. Please try again.");
            modelAndView.setViewName("login");
        }
        else if (user != null && user.getPassword()==password && user.isEnabled()==false) {
            modelAndView.addObject("message1","E-mail is not verified. Check you inbox for the verification link.");
            modelAndView.setViewName("login");
        }*/
        else if (user != null && user.getPassword()==password) { //////////////////////////////////////////////////////////////
            modelAndView.addObject("message1","Welcome! You are logged in.");
            modelAndView.setViewName("customerAccount");
        }
        return modelAndView;
    }
    // getters and setters
    public CustomerRepository getUserRepository() {
        return userRepository;
    }

    public void setUserRepository(CustomerRepository userRepository) {
        this.userRepository = userRepository;
    }

    public ConfirmationTokenRepository getConfirmationTokenRepository() {
        return confirmationTokenRepository;
    }

    public void setConfirmationTokenRepository(ConfirmationTokenRepository confirmationTokenRepository) {
        this.confirmationTokenRepository = confirmationTokenRepository;
    }

    public EmailSenderService getEmailSenderService() {
        return emailSenderService;
    }

    public void setEmailSenderService(EmailSenderService emailSenderService) {
        this.emailSenderService = emailSenderService;
    }

}

My register.html Thymeleaf page:

        <meta charset="utf-8" />
        <title>Registration</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <link rel="stylesheet" th:href="@{fonts/material-design-iconic-font/css/material-design-iconic-font.min.css}" ></link>

        <link th:href="@{img/favicon.ico}" rel="shortcut icon"></link>

        <link th:href="@{https:fonts.googleapis.com/css?family=Josefin+Sans:300,300i,400,400i,700,700i}" rel="stylesheet" ></link>

        <link th:href="@{/css/regstyle.css}" rel="stylesheet" ></link>
        <link th:href="@{/css/style.css}" rel="stylesheet" ></link>
        <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet" ></link>
        <link th:href="@{/css/font-awesome.min.css}" rel="stylesheet" ></link>
        <link th:href="@{/css/flaticon.css}" rel="stylesheet" ></link>
        <link th:href="@{/css/slicknav.min.css}" rel="stylesheet" ></link>
        <link th:href="@{/css/jquery-ui.min.css}" rel="stylesheet" ></link>
        <link th:href="@{/css/owl.carousel.min.css}" rel="stylesheet" ></link>
        <link th:href="@{/css/animate.css}" rel="stylesheet" ></link>

                        <form class="header-search-form">
                            <input type="text" placeholder="Search on divisima ...." /></input>
                            <button></button>
                        </form>

                                Sign In or Create Account

                                    0

                                Shopping Cart

Home

Women

Men

Jewelry
                        New

Shoes

Sneakers

Sandals

Formal Shoes

Boots

Flip Flops

Pages

Product Page

Category Page

Cart Page

Checkout Page

Contact Page

Blog

                <form action="#" th:action="@{/register}" th:object="${user}" method="post">

Registration Form

                            First Name
                            <input th:field="*{firstName}" type="text" name="firstName" class="form-control" ></input>

                            Last Name
                            <input th:field="*{lastName}" type="text" name="lastName" class="form-control" ></input>

                        Date of Birth
                        <input th:field="*{dob}" type="date" name="dob" class="form-control" ></input>

                        Telephone
                        <input th:field="*{telephone}" type="text" name="telephone" class="form-control" ></input>

                        Email
                        <input th:field="*{emailId}" type="email" name="emailId" class="form-control" ></input>

                            Street
                            <input th:field="*{street}" type="text" name="street" class="form-control" ></input>

                            City
                            <input th:field="*{city}" type="text" name="city" class="form-control" ></input>

                            District
                            <input th:field="*{district}" type="text" name="district" class="form-control" ></input>

                            Province
                            <input th:field="*{province}" type="text" name="province" class="form-control" ></input>

                            Password
                            <input th:field="*{password}" type="password" name="password" class="form-control" ></input>

                            Confirm Password
                            <input type="password" class="form-control" ></input>

                            <input type="checkbox" ></input> I accept the Terms of Use & Privacy Policy.

                    <button>Register Now</button>

                </form>

About

Donec vitae purus nunc. Morbi faucibus erat sit amet congue mattis. Nullam frin-gilla faucibus urna, id dapibus erat iaculis ut. Integer ac sem.

Questions

About Us

Track Orders

Returns

Jobs

Shipping

Blog

Partners

Bloggers

Support

Terms of Use

Press

Questions

what shoes to wear

                                    Oct 21, 2018
                                    Read More

trends this year

                                    Oct 21, 2018
                                    Read More

Questions

                            C.

Your Company Ltd

                            B.

1481 Creekside Lane  Avila Beach, CA 93424, P.O. BOX 68

                            T.

+53 345 7953 32453

                            E.

office@youremail.com

                    instagram
                    g+plus
                    pinterest
                    facebook
                    twitter
                    youtube
                    tumblr

Copyright © All rights reserved | This template is made with  by Colorlib

Console:
2020-09-05 20:24:26.578  INFO 27384 --- [           main] c.O.customer.CustomerApplication         : Starting CustomerApplication on LAPTOP-D72B23NQ with PID 27384 (C:\Users\User\Desktop\customer\target\classes started by User in C:\Users\User\Desktop\customer)
2020-09-05 20:24:26.579  INFO 27384 --- [           main] c.O.customer.CustomerApplication         : No active profile set, falling back to default profiles: default
2020-09-05 20:24:27.468  INFO 27384 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-09-05 20:24:27.468  INFO 27384 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.36]
2020-09-05 20:24:27.575  INFO 27384 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2020-09-05 20:24:27.687  INFO 27384 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-09-05 20:24:27.690  WARN 27384 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2020-09-05 20:24:27.776  INFO 27384 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-09-05 20:24:27.849  WARN 27384 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
Hibernate: alter table confirmation_token add constraint FKpitnf1t12om2w2btrcd37gwpq foreign key (user_id) references customer (user_id)
2020-09-05 20:24:28.657  INFO 27384 --- [           main] c.O.customer.CustomerApplication         : Started CustomerApplication in 2.318 seconds (JVM running for 2.938)
2020-09-05 20:24:37.951  INFO 27384 --- [nio-8082-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'


text:
Q: Drawing text in .NET with native look & feel I'm using .NET1 and I want to draw text as native. Is it possible by configuring graphics?
I need to render the text as the System.Windows.Forms.Label does when the FlatStyle is set to System.
I have configured the SmoothingMode and the AntiAliasGridFit, but unfortunately the result is not the same:

I'm using the same font in both cases (Segoe UI 9pt).
Any ideas?

A: Have you tried using the TextRenderer class instead of the Graphics.DrawString routine? It was introduced into the framework precisely because there is a discrepancy between the default rendering of Windows Forms and .NET's GDI+ wrapper.
The MSDN says:

The TextRenderer class provides a set of static methods that can be used for measuring and drawing text on a Windows Form control.


text:
Q: How generalize classes and access properties? I want to generalize a class A and create an object of class A having properties of class A and B. This is the code I have done but I am not able to access properties in B, only A type properties are accessible. How to do it?
And please tell me what this concept is called (A test = new B();)
Class Programe
{
    Main()
    {
        A test = new B();
    }
}

Class A
{
    int aint;
}

Class B:A
{
    int bint;
}

Class test:A
{
    int testint;
}

A: The concept is called inheritance.
A test = new B();
B bReference = test as B;
System.Console.WriteLine(bReference.bint);

with new B() you create an instance of class B and save the reference to it in the variable test. The variable test is a variable that can hold references to instances of class A. B is a subclass of A, so your new instance can be treated like an instance of A, so it is possible to store it in your variable test.
If you want to access your instance's members, which are specific to B, you have to treat your reference as a reference to an instance of B. You can do that by using the as operator.


text:
Q: concentration inequality for maximum Im looking for a good concentration inequality that bounds the following probability:
$$
P\left(\max_{M\in\{1,... ,n\}}\left| \sum_{i=1}^M(Z_i^2-1)\phi_{M,i}\right|>\delta\right),
$$
where $Z_i$ are iid standard normal variables and $\phi_{M,i}$ is a non stochastic Term depending on $M$ and $i$.
Unfortunately, just bounding the max with the sum over all n is not enough... so i would be verry glad for  any suggestion.


text:
Q: Access Azure Active Directory secured site from other web application We have a separate web application secured with Azure Active Directory that exposes some (internal) services.
Now we want to access these services from within our site, but this fails off course because of the authentication that is not yet done.
This site doesn't use Active Directory for authentication.
Is it possible to configure this site as a trusted client (through token, key) in the web.config? So that we don't need any code modifications?
Or has this to be done through code?
Kind regards,

A: It looks like you have a WebAPI secured using Azure AD (what you refer to as web application)  and a WebApp (what you refer to as site) that needs to access the WebAPI. If this is indeed the case, you can register both the WebApp and WebAPI as applications in Azure AD (the WebApi is presumably already registered, as it is secured using Azure AD). Then, your WebApp can access your WebAPI using its own identity (client credential OAuth flow sample code) or on behalf of the signed-in user (auth code grant OAuth flow sample code).
In either case, the WebApp (site) needs to acquire an access token to access the WebApi and send this access token in the Authorization header in every call that it makes to the WebApi - this will require code changes to the WebApp. In theory you can build a proxy application that acquires tokens and injects headers in all outgoing calls - however I doubt it would be worth the effort.
Hope this helps.


text:
Q: Uninstalling and Deleting plug-ins from eclipse I am uninstalling a plugin named X from eclipse uninstall option.
Now to make a clear approach I went to the eclipse plugins directory and delete the plugin jar file from there.
Now I am trying to reinstall the same plug-in and eclipse prompts an error saying

An error occurred during the
  org.eclipse.equinox.internal.p2.engine.phases.CheckTrust
  phase. session context
  was:(profile=epp.package.jee,
  phase=org.eclipse.equinox.internal.p2.engine.phases.CheckTrust,
  operand=, action=). Error reading
  signed content. The file
  "D:\Testing\eclipse-jee-helios-SR1-win32\eclipse\plugins\x_1.1.3.jar"
  does not exist

Now how to resolve the above issue

A: You should never delete plugins you installed using the Eclipse installer under Help>Install New Software. Now there is directory used to drop in plugins as jars, which I am assuming you used, if so deleting it would result in the desired behavior assuming you shut down eclipse before hand. If not then you need clean your configuration area. In the future when removing go to Help>Install New Software>Already Installed software, there should be a remove once your there. :)
Goodluck.

A: As per eclipse documentation

You should not remove plug-ins from Eclipse. Plug-ins should be
  installed as features using the Update Manager. The same Update
  Manager can be used to disable plug-ins by disabling the feature they
  belong to. Run Help > About Eclipse > Installation Details, select the
  software you no longer want and click Uninstall. (On Macintosh it is
  Eclipse > About Eclipse > Installation Details.) In older versions,
  you might need to Run Help > Software Updates > Manage
  Configuration..., select the feature of interest, and disable it with
  the task shown in the right window.
When a feature is disabled, all its plug-ins will be disabled also.
  They are still available on disk, and they can be enabled at any time
  in the future.
To physically remove the feature and its plug-ins, you will have to
  manually remove the feature from the eclipse/features directory and
  its plug-ins from the eclipse/plugins directory. We advise extreme
  caution here. Remove the wrong ones, and you may have quite some
  trouble restoring your Eclipse to a stable state. Unless you care a
  lot about hard disk use, we recommend leaving the plug-ins where they
  are.
Note that when manually removing plugins as described above, some
  metadata is still cached by Eclipse, which can lead to problems later
  on. Running Eclipse with the -clean option can help with that, as it
  causes Eclipse to clean the cached metadata

A: I have similar issue. I deleted those plugins related files from eclipse/plugins and eclipse/features directory. The reason why I did that is because I have already uninstalled the plugins from eclipse but the files remain in both directories.
I solved it by editing the eclipse/artifact.xml. I search all the artifacts with the id of my plugins and remove them. And I am able to reinstall the plugins again :)

A: Thanks .. I am not sure what action actually fixed the exact problem i had.
I removed the plugin related files from plugins and features folder, removed entries from the artifact.xml file and opened eclipse with -clean option.

A: *

*Run eclipse

*Rename eclipse exe to eclipse.exe.back

*Run updates

*Updates executed successfully


text:
Q: Type checking on Nullable If have the following method:
static void DoSomethingWithTwoNullables(Nullable<int> a, Nullable<int> b)
{
    Console.WriteLine("Param a is Nullable<int>: " + (a is Nullable<int>));
    Console.WriteLine("Param a is int          : " + (a is int));
    Console.WriteLine("Param b is Nullable<int>: " + (b is Nullable<int>));
    Console.WriteLine("Param b is int          : " + (b is int));
}

When i call this method with null as a parameter, the type check returns false for this parameter. For example this code
DoSomethingWithTwoNullables(5, new Nullable<int>());

results in this output:
Param a is Nullable<int>: True
Param a is int          : True
Param b is Nullable<int>: False
Param b is int          : False

Is there any way to preserve the type information when using a Nullable and passing null? I know that checking the type in this example is useless, but it illustrates the problem. In my project, I pass the parameters to another method that takes a params object[] array and tries to identify the type of the objects. This method needs to do different things for Nullable<int> and Nullable<long>.

A: Going straight to the underlying problem, no, you can't do this. A null Nullable<int> has exactly the same boxed representation as a null Nullable<long>, or indeed a 'normal' null. There is no way to tell what 'type' of null it is, since its underlying representation is simply all-zeros. See Boxing Nullable Types for more details.

A: conceptually, new Nullable<int> is null.
If we generalise, forgetting about Nullable<T>:
string s = null;
bool b = s is string;

we get false. false is the expected value for a type-check on a null value.

A: You can try using Reflection to achieve this. Relevant article here.

A: Unfortunately, null does not point to any specific memory location, and thus there is no metadata that you can associate with it to lookup the type. Thus, you cannot gain any additional information about the variable.

A: Unless I'm misunderstanding the question, you can get the type using GetType(). For example,
int? myNullableInt = null;
Console.WriteLine(myNullableInt.GetValueOrDefault().GetType());

If myNullableInt is null, a default value will be returned. Check the type of this returned value and, in this case, it will return System.Int32. You can do an If..else/Switch check on the returned type to perform the relevant action.
(int? is the same as Nullable<int>)

A: You can't do this, nor should you want to.  Since Nullable<T> is a struct, value-type variables of this type have all the type information you need at compile time.  Just use the typeof operator.
On the other hand, you might have a Nullable instance whose type you don't know at compile time.  That would have to be a variable whose static type is object or some other reference type.  Howver, because a Nullable<T> value boxes to a boxed T value, there's no such thing as a boxed Nullable<T>.  That instance whose type your checking will just be a T.
This is why you get the same result for is int and is Nullable<int>.  There's no way to distinguish between a boxed int and a boxed int?, because there is no boxed int?.
See Nulls not missing anymore for details.

A: As it has already been pointed out null has no type. To figure out if something is int? vs long? you need to use reflection to get information about something storing the type. Here is some code that you may be able to use as inspiration (not knowing exactly what you try to achieve the code is a bit weird):
class Pair<T> where T : struct {

  public Pair(T? a, T? b) {
    A = a;
    B = b;
  }

  public T? A { get; private set; }

  public T? B { get; private set; }

}

void DoSomething<T>(Pair<T> pair) where T : struct {
  DoMore(pair);
}

void DoMore(params object[] args) {
  Console.WriteLine("Do more");
  var nullableIntPairs = args.Where(IsNullableIntPair);
  foreach (Pair<int> pair in nullableIntPairs) {
    Console.WriteLine(pair.A);
    Console.WriteLine(pair.B);
  }
}

bool IsNullableIntPair(object arg) {
  var type = arg.GetType();
  return type.IsGenericType
    && type.GetGenericTypeDefinition() == typeof(Pair<>)
    && type.GetGenericArguments()[0] == typeof(int);
}

If you execute the following code
DoSomething(new Pair<int>(5, new int?()));
DoSomething(new Pair<long>(new long?(), 6L));

you get the following output:

Do more
5
null
Do more

A: You can use typeof :
a == typeof(Nullable<int>) //true
a == typeof(int) //false


text:
Q: SQL Server Recursive CTE - Why this behavior? Given these tables...
CREATE TABLE tblEmployees (
    EmployeeID  SMALLINT,
    ReportsTo   SMALLINT,
    IsBigBoss   BIT);

CREATE TABLE tblTargetEmployees (
    EmployeeID SMALLINT);

INSERT INTO tblEmployees VALUES
(1,NULL,NULL),
(2,1,1),
(3,1,1),
(4,1,1),
(5,1,1),
(6,2,0),
(7,6,0),
(8,6,0),
(9,3,0),
(10,4,0),
(11,10,0),
(12,10,0),
(13,5,0),
(14,2,0),
(15,10,0);

INSERT INTO tblTargetEmployees VALUES
(8),
(9),
(10),
(11),
(12),
(14);

And this query...
WITH cte AS (
    SELECT e.EmployeeID, BigBossID=e.EmployeeID, e.ReportsTo
        FROM tblEmployees e
        WHERE e.IsBigBoss=1

    UNION all

    SELECT e.EmployeeID, cte.BigBossID, e.ReportsTo
        FROM tblEmployees e
            JOIN cte ON e.ReportsTo=cte.EmployeeID
)

SELECT *
    FROM cte
    WHERE EXISTS (SELECT * FROM tblTargetEmployees te WHERE te.EmployeeID=cte.EmployeeID)
    ORDER by EmployeeID

I get the results expected.  All six employees from my target table are returned.  However, if I move the filter into the cte instead, I drop an employee (#8).
WITH cte AS (
    SELECT e.EmployeeID, BigBossID=e.EmployeeID, e.ReportsTo
        FROM tblEmployees e
        WHERE e.IsBigBoss=1

    UNION all

    SELECT e.EmployeeID, cte.BigBossID, e.ReportsTo
        FROM tblEmployees e
            JOIN cte ON e.ReportsTo=cte.EmployeeID
        WHERE EXISTS (SELECT * FROM tblTargetEmployees te WHERE te.EmployeeID=e.EmployeeID)
)

SELECT *
    FROM cte
    ORDER by EmployeeID

Now, I understand why my extra "Big Boss" rows come across when I move the filter into the cte, but I'm having a hard time wrapping my head around why employeeID 8 gets filtered out.
Any assistance with helping me wrap my simple mind around this behavior is much appreciated.

A: Because EmployeeId 6 doesn't Exist in the tblTargetEmployees so when it gets to the recursion and starts adding employee id 6 it looks up if it exists in the tblTargetEmployees table.  It doesn't so that line of recursion stops if and never gets to employee id 8.
So to use the data

*

*2 is bigboss and is represented in anchor table

*6 is direct boss but doesn't exist so it doesn't call the recursion again after that.

*8 is waiting to be found.....

move your WHERE statement outsde of the cte and you will see the results you want
;WITH cte AS (
    SELECT e.EmployeeID, BigBossID=e.EmployeeID, e.ReportsTo
        FROM tblEmployees e
        WHERE e.IsBigBoss=1

    UNION all

    SELECT e.EmployeeID, cte.BigBossID, e.ReportsTo
        FROM tblEmployees e
            JOIN cte ON e.ReportsTo=cte.EmployeeID
)

SELECT *
    FROM cte e
    WHERE EXISTS (SELECT * FROM tblTargetEmployees te WHERE te.EmployeeID=e.EmployeeID)
    ORDER by EmployeeID


text:
Q: South django table already exists I'm experiencing the same problem as with: django - "manage.py test" fails "table already exists"
The schemamigration / migration worked fine (although did have some problems that required me to --fake, but all subsequent migrations with south work). But when I run a unit test I get:
(1050, "Table '{tablename}' already exists")

I'm just curious how I can get round this, and why this happens. The only answer given in the question linked above was that south could be excluded from unit tests, if I do this does it mean I can't unit test with tables managed by south?
Explanations much appreciated :)
Adam

A: No, it doesn't mean that. Don't forget that Django already knows what your tables should look like if you create them from scratch now - it just uses the model definitions. South is useful because it allows you to easily transform your table structure when you change your models, but when you're running tests you don't care about that: you just want the tests run on the current versions of the tables.
So yes, disable South when running tests, via SOUTH_TESTS_MIGRATE = False, and Django will automatically create the tables for you.


text:
Q: Preprocess node from a module: not getting same vars as template.php I'd like to preprocess and theme my nodes from a module instead of template.php.  Before, I'd have a giant switch statement in theme_preprocess_node().  But this only ever applied to my primary tab - subtabs were being templated from the modules they were defined in.  So I like the idea of consolidating all my preprocess functions and templates into one organized module.
The structure I want is essentially like this (pulling out details for a summary):
function foomodule_menu()
{
    $items['foo/%node'] = array(
        'page callback' => 'page_foo_overview',
        'page arguments' => array(1),
        'type' => MENU_NORMAL_ITEM,
    );
        $items['foo/%node/overview'] = array(
            'type' => MENU_DEFAULT_LOCAL_TASK,
        );
        $items['foo/%node/details'] = array(
            'page callback' => 'page_foo_details',
            'page arguments' => array(1),
            'type' => MENU_LOCAL_TASK,
        );
}

function foomodule_theme()
{
    return array(
        'page_foo_overview' => array(
            'arguments' => array('node' => NULL),
            'template' => 'templates/page-foo-overview'
        ),
        'page_foo_details' => array(
            'arguments' => array('node' => NULL),
            'template' => 'templates/page-foo-details'
        ),
    );
}

function page_foo_overview($node)
{
    // Used to do this, and themed it from template.php
    // return node_view($node, FALSE, TRUE);

    // Instead, I'd like to theme all pages directly in this module:
    return theme('page_foo_overview', $node);
}

function template_preprocess_page_foo_overview(&$vars)
{
    // But $vars doesn't contain the same data as when I themed from template.php
    // Specifically the ['view'] element of CKK fields, and flags like $teaser
    // What do I need to do to get at the same data?
    dsm($vars);
}

All works great, but the $vars available in my preprocess are not what I'm used to in the template.php's theme_preprocess_node() function.  For one, it looks like CCK fields haven't been run through content_format() (no ['view'] element), and flags like teaser and page are missing.
What's being called before theme_preprocess_node() that I could invoke here?
Am I asking for trouble by doing this?  It makes so much more sense to me to have it organized like this and be in control of each step: menu > page callback > theme > preprocess > template, and to be able to organize this across multiple modules as I see fit.

A: AK,
My suggestion is to execute the following code to check the available variables
<?php
$arr = get_defined_vars();
dsm($arr);
?>

If that doesn't help you can check the weight of your module on the system table. Maybe changing it (to make your module run after other modules) can help you.


text:
Q: Eclipse android error Everytime I start the emulator from eclipse, I get the following error in my console.
[2010-09-13 17:04:51 - DeviceMonitor]Sending jdwp tracking request failed!
[2010-09-13 17:18:49 - DeviceMonitor]Sending jdwp tracking request failed!
The application works fine, but I am concerned as to why I see this error. Please help

A: I believe this is coming from the Usage Stats option. I just installed ADT, did a test run and got this error, as well. I went to Window >> Preferences >> Android >> Usage Stats then checked it on. Tried another test and voila! No error!
Kind of annoying, I can imagine...

A: This is caused after the emulator is closed while eclipse is still running.
When you first run the emulator after starting eclipse, a connection is established between it and eclipse. This connection is used to send messages back and forth between the two programs, and so eclipse can track the progress of the emulator.
When the emulator is closed, the connection is lost, and any attempt by eclipse to send a message results in the error messages you describe.

A: As Koby said this message comes if you close the emulator after running an application. First of all between successive application running on emulator you don't need to close the emulator. First before running the application you start the emulator by clicking window-->Android SDK and AVD Manager and click on the emulator you want to launch and click on 'start' button and then click on 'Launch' to launch the emulator. After the emulator launches unlock the emulator and keep that emulator minimized. And if you want to run an application go for 'run as android app' and you can see that on the emulator when maximized. After running that application if you want to make some changes in the application you don't need to close the emulator. you press the home button after running the application and keep the emulator minimized. Make the changes on the code and again go for running the application. Thus you can avoid that error message and save time for launching the emulator. if you got that error message then also the application will work properly but you cannot see the messages like uploading app-->installing .apk-->and the success messages. But these will be happening on the background. One way to overcome this is to restart the eclipse.


text:
Q: R - Dropped rows I have a dataset which gives the  number of relatives who help a senior in his everyday life. I have an other part of the survey focusing on the senior.
Some seniors are not helped at all by relatives, so my first dataset has less rows than the second.
I would like to count the number of hours given by relative to each senior (a senior can be helped by numerous relatives), and for every senior who is not helped, NA should be displayed.
Rows go from 1 to 10628.
Here is my first dataset:
head(relative)
id_senior    id_relative    hours_care
  1              1             3
  1              2             6
  3              1             5
  3              2             0
  3              3             1
  4              1             3
  ...
 10628          1             34

Here is my second one :
head(senior)

id_senior
   1
   2
   3
   4
  ...
 10628

And I would like something like this:
head(senior) #or whatever the name
id_senior    nbr_relative      sum_hours
  1            2                  9
  2            0                  NA
  3            3                  6
  4            1                  3
 ...
 10638         1                  34

I tried something like this:
library(dplyr)

#To count the number of relatives
nbr_relatives <- relatives %>%
  group_by(id_senior = factor(id_senior, levels = min(id_senior):max(id_senior)), .drop = FALSE) %>%
  summarise(relatives = n_distinct(id_relatives))

#The value 0 is given to every relatives which has no care hours value
subset_caregivers$hours_recoded[is.na(subset_caregivers$hours_recoded)] <- 0

nbr_relatives <-  relative %>%
  group_by(id_senior = factor(id_senior, levels = min(id_senior):max(id_senior))) %>%
  count(hours = sum(hours_care), na.rm = TRUE)

But the number of rows in the dataset nbr_relatives become 4564, the number of senior helped, not 10628!
Where am I mistaken?

A: in Base-R,
merge(senior, aggregate(hours_care ~ id_senior, relative, sum), by = "id_senior", all.x=T)

   id_senior hours_care
1          1          9
2          2         NA
3          3          6
4          4          3
5          5         NA
         ...
20        20         NA

Edit:
to get the extra column in
    merge(senior, merge(aggregate(id_relative ~ id_senior, relative, length),aggregate(hours_care ~ id_senior, relative, sum)), by = "id_senior", all.x=T)

   id_senior id_relative hours_care
1          1           2          9
2          2          NA         NA
3          3           3          6
4          4           1          3
5          5          NA         NA
6          6          NA         NA
              ...

Data:
relative <- structure(list(id_senior = c(1L, 1L, 3L, 3L, 3L, 4L), id_relative = c(1L,
2L, 1L, 2L, 3L, 1L), hours_care = c(3L, 6L, 5L, 0L, 1L, 3L)), class = "data.frame", row.names = c(NA,
-6L))

senior <- data.frame(id_senior = 1:20)


text:
Q: Retrieving the last non-empty value and display it for each day I am new to SSAS and more so with MDX and I need your help with the following scenario please.
In my cube, there is a measure called WIP Hours (Work In Progress Hours).
This measure is from a measure group called WIP, which is based on a fact table, namely facWIP.
facWIP table gets its data from a source table.
Each time a user enters a WIP entry to the front-end system, that entry is stored in this table.
However, users don't always put an entry everyday.
For example, there is an entry for 16 Aug 2013 and the WIP value = 47.
The next entry is on 26 Aug 2013 of WIP = 42
There are no entries for 17 Aug - 25 Aug 2013 in the source table, hence the same in the fact table.
This is reflected in the cube that I build.
The requirement is that if there are no entries for a particular date, then need to use / display the last number available.
So in this case, in the cube there should be entries for 17 - 25 August with WIP = 47, etc.
I have no idea how to do this, if it is possible at all.
I tried using the following MDX
CREATE MEMBER CURRENTCUBE.[Measures].[WIP Hours_2]
AS
(TAIL(NONEMPTY(DESCENDANTS([Calendar].[Calendar].CURRENTMEMBER,[Calendar].[Calendar].[Calendar Date]), [Measures].[WIP Hours]),1).ITEM(0), [Measures].[WIP Hours]),
//NON_EMPTY_BEHAVIOR = { [Measures].[WIP Hours] },
VISIBLE = 1 , ASSOCIATED_MEASURE_GROUP = 'WIP' ;

but it doesn't do what I want.

UPDATE 8 Sept 2013:
I am also trying another alternative approach, that is to Cross Join the table with the calendar table so that every task WIP combination has entries for each day.
For the entries which actually does not have actual WIP value, it will be WIP = NULL.
The downside of this approach is that the fact table becomes much bigger and longer ETL process, from 1.5M to ~17M records!
I am thinking by doing it this way, somehow in the cube calculated measure using MDX, I can say something like:
"If the WIP for current date is NULL, then get/use the last non-NULL WIP value"
How can I write this logic in MDX, if it makes sense at all?
Also, at the moment, in the cube, the date entries which actually have WIP = NULL, their WIP is showing = 0..
Any assistance are very much appreciated.
Thanks!

A: I would try a recursive approach:
// intermediate measure, makes the code more readable:
CREATE MEMBER CURRENTCUBE.[Calendar].[Calendar].[last day in period] AS
       Tail(Descendants([Calendar].[Calendar].CURRENTMEMBER,
                        [Calendar].[Calendar].[Calendar Date]
            )
       ).Item(0).Item(0),
VISIBLE = 0;

// final measure, defined using recursion:
CREATE MEMBER CURRENTCUBE.[Measures].[WIP Hours_2]
AS
IIf(IsEmpty( ( [Calendar].[Calendar].[last day in period], [Measures].[WIP Hours] )),
    ( [Calendar].[Calendar].[last day in period].PrevMember, [Measures].[WIP Hours_2] ),
    ( [Calendar].[Calendar].[last day in period], [Measures].[WIP Hours] )
),
VISIBLE = 1 , ASSOCIATED_MEASURE_GROUP = 'WIP' ;

The true case of the IIf is the recursion, the second case the termination of the recursion. SSAS should be able to end the recursion itself as soon it reaches the start of the Calendar hierarchy, avoiding an infinite recursion.
If the above does not give you the correct answer, maybe using <> 0 instead of IsEmpty will get better results.


text:
Q: How to access files in subdirectories? I have several subdirectories beneath in a main directory, and each subdirectory contains one or two text files. I need to copy these text files to another directory.
Here's how I coded. But it doesn't seem to work. What can I do? And is there a direct way of doing this?
#!/usr/bin/perl
use File::Copy;
my $directorypath;
opendir (DIR, '/d/work/abc') or die "cannot open path $!";
my @maindirectory = readdir (DIR);
closedir (DIR);

foreach my $subdirectorypath (@maindirectory)
{
    $subdirectorypath = join '', '/d/work/abc', $directorypath;
    chdir '$directorypath';
    my @textfile = glob "*.txt";
    foreach (@textfile)
    {
     $copiedfile = "/d/work/abcd/$_.txt."; #destination path
     copy($_, $copiedfile) or die "File cannot be copied.";
    }
}

A: This is simple in a one-line Perl program
perl -MFile::Copy=copy -e'copy($_, "/d/work/abcd") for </d/work/abc/*/*.txt>'


text:
Q: Getting the scenario name of the parent calling scenario I have a feature file that has a scenario that is used to generate a token for our api.  We have the ability to pass in a claim that we can used to log which test created the token.  Without passing in the name to the called feature (and updating 3000 tests) how can we get the name of the calling feature so that we can log that in the token?  We would like to be able to make the change in the token scenario to centralize the change.  I can get the scenario name via karate.info.scenarioName but this gives me the called scenario name and not the parent calling scenario.

A: I think the best option is you to define an extra variable something like this  in the calling feature:
* def caller = karate.feature.fileName

And make use of the principle that variables are always "visible" within called features. If you want to do a "safe" get, use karate.get()
* def whoCalledMe = karate.get('caller')

What you ask for is possible, but I'm reluctant to share this as these are like internal API-s not designed for use:
* def caller = karate.engine.runtime.caller.parentRuntime.scenario.feature

That will give you a reference to a Karate Java object com.intuit.karate.core.Feature.
The karate.scenario and karate.feature APIs are available in 1.0 onwards and karate.info is not recommended any more: https://github.com/karatelabs/karate/wiki/1.0-upgrade-guide#karateinfo-deprecated


text:
Q: Javascript convert date format from "yyyy-mm-dd" to "December 11th, 2013"? How I make a sintax to convert date format from default format (yyyy-mm-dd) to english format like December 11th, 2013 using Javascript function?
Thank you

A: You could use moment.js
Moment.js 2.7.0

Moment was designed to work both in the browser and in Node.JS.
  Parse, validate, manipulate, and display dates in javascript.

and it is also available on cdnjs.com.

A: var str_date = "1983-24-12",
    arr_date = str_date.split('-'),
    months   = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

var new_date=months[arr_date[2]] + ' ' + arr_date[1] + ', ' + arr_date[0]);

http://jsfiddle.net/TN7NE/
Edit
You can add an ordinal using the following:
function addOrdinal(n) {
    var ord = [,'st','nd','rd'];
    var a = n%100;
    return n + (ord[a>20? a%10 :a] || 'th');
}

e.g.
addOrdinal(1); // 1st

A: You can use a function like this:
function formatDate(date) {
  months = ['January', 'February', 'March', 'April',
            'May', 'June', 'July', 'August',
            'September', 'October', 'November', 'December'];
  dateSplit = date.split('-');
  year = dateSplit[0];
  month = months[parseInt(dateSplit[1]) - 1];
  day = parseInt(dateSplit[2]);
  switch(day) {
    case 1:
    case 21:
    case 31:
      day += 'st';
      break;
    case 2:
    case 22:
      day += 'nd';
      break;
    case 3:
    case 23:
      day += 'rd';
      break;
    default:
      day += 'th';
  }
  return month + ' ' + day + ', ' + year;
}


text:
Q: In r, how would you code to get a value based on the combinations of two binned value? I want to Calculate median pop density for every possible combination of temp and precipitation values. For example, the pop density for places that have:
Mean annual temp of 4 to 6 C and 500 to 510 mm precip
Mean annual temp of 4 to 6 C and 510 to 520 mm precip
Mean annual temp of 4 to 6 C and 520 to 530 mm precip
Mean annual temp of 6 to 8 C and 500 to 510 mm precip
Mean annual temp of 6 to 8 C and 510 to 520 mm precip
Mean annual temp of 6 to 8 C and 520 to 530 mm precip and so on...

My data is situated like so:
 Pp    Pmm    t
21.18  83.81  31.24
14.81 174.49  30.80
14.81 129.59  30.72
52.04 230.53  30.59
8.56  206.69  30.57
5.06  194.85  30.55

So far I have only binned these data: using the following code:
# MAKING precipitation BINS
# set up cut-off values
breaks <- seq(0,7010,10)
# specify interval/bin labels
tags <- paste(seq(0,7000,10),"-",seq(10,7000,10),sep="")
# bucketing values into bins
group_tags <- cut(test$Pmm ,

       breaks=breaks,
                  include.lowest=TRUE,
                  right=TRUE,
                  labels=tags)
# inspect bins
summary(group_tags)

# Temperature Bins
# set up cut-off values
breaks1<- seq(0,32,2)
# specify interval/bin labels
tags1 <- paste(seq(0,30,2),"-",seq(2,32,2),sep="")
# bucketing values into bins
group_tags1 <- cut(test$t ,
                  breaks=breaks1,
                  include.lowest=TRUE,
                  right=FALSE,
                  labels=tags1)
# inspect bins
summary(group_tags1)

I have tried a couple of four loops, but could not get them to work. Any ideas?

A: You can try :
breaks <- seq(0,7010,10)
tags <- paste0(seq(0,7000,10),"-",seq(10,7010,10))
test$group_tags <- cut(test$Pmm , breaks=breaks,
                       include.lowest=TRUE, right=TRUE,labels=tags)

breaks1<- seq(0,32,2)
tags1 <- paste0(seq(0,30,2),"-",seq(2,32,2))
test$group_tags1 <- cut(test$t ,breaks=breaks1,
                        include.lowest=TRUE, right=FALSE, labels=tags1)

#Create all possible combination of group_tags and group_tags1
all_combns <- expand.grid(group1 = test$group_tags, group2 = test$group_tags1)

#For each combination calculate average value of `Pp`.
do.call(rbind, Map(function(x, y) data.frame(Pmm_group = x, temp_group = y,
       average = mean(test$Pp[test$group_tags == x & test$group_tags1 == y])),
       all_combns$group1, all_combns$group2)) -> result

result


text:
Q: Form not closing when I click send I have a form I am trying to get to close when the user clicks the submit button but it just stays up saying "sending"
Here is the entire form

Request a Quote

        <form id="contact" name="contact" action="#" method="post" style="width:600px">

                    *Your Name:

                        <input type="text" id="Form_Name" name="Form_Name" />

                    Company Name:

                        <input type="text" id="Form_Company" name="Form_Company" />

                    *Your E-Mail:

                        <input type="text" id="Form_Email" name="Form_Email" />

                    *Phone Number:

                        <input type="text" id="Form_Number" name="Form_Number" />

                    Comments:

                        <textarea id="Form_Comments" name="Form_Comments" cols="25" rows="3"></textarea>

                        <button id="send">Request Quote</button>

                        <?php echo $itemname; ?>

 Manufacturer:
                        <?php echo $manufactuer;?>

 Model:
                        <?php echo $model;?>

 Category:
                        <?php echo $category;?>

        </form>

I have looked everywhere and I cannot seem to get it working. Any help would be greatly appreciated.
*****EDIT****
Here is the new code I have adding Nicks advice.

A: The server will expect a json string, not json object. Please update this,
From
data: {name: $("#Form_Name").val(),email: $("#Form_Email").val(),eid: $("#Form_ID").val(),company: $("#Form_Company").val(),number: $("#Form_Number").val(),comments: $("#Form_Comments").val()},

To
data: JSON.stringify({name: $("#Form_Name").val(),email: $("#Form_Email").val(),eid: $("#Form_ID").val(),company: $("#Form_Company").val(),number: $("#Form_Number").val(),comments: $("#Form_Comments").val()}),

A: Looks like there are multiple ways based on the version being used. Not sure of your version.
Some one has suggested using: $.fancybox.close(true)
Check comments in these links:
LINK 1,   LINK 2

A: I was able to get itworking by changing this
success: function () {
                            {

                                $("#contact")
                                    .fadeOut("fast", function () {
                                        $(this).before("
Success! Your feedback has     been sent, thanks :)
");
                                        setTimeout(function () { $.fancybox.close(); }, 50)
                                    });
                            }

to this
success: setTimeout(function () { parent.$.fancybox.close(); }, 2000)


text:
Q: Custom bridge table in playframework ebean I am unsuccessfuly trying to create bridge table that would resolve two @ManyToMany relations. However this table have to contain additional field. For example:
Course: -course_id - pk

Student: -student_id -pk

Bridge: -(course_id, student_id) - pk
        -additional_field

My student class looks like this:
@Entity
public class Student extends Model {

    @Id
    @OneToMany
    public List<Bridge> student_id;
}

Course class is basicaly the same.
Bridge table looks like this:
@Entity
public class Bridge extends Model{

    @EmbeddedId
    public compound_key student_course;

    public String additional_field;

    @Embeddable
    public class compound_key{

        @ManyToOne
        public Student student_id;

        @ManyToOne
        public Student course_id;

    }

}

Thank you for help.

A: I have found the following solution. This is a solution without a composite key in Bridge. I added normal @Id field in Bridge class and relations to Student and Course are normal relations.
This solution contains an additional 'id' field in the 'bridge' table in the database.
Here is the code:
Student.java:
@Entity
public class Student extends Model {

    @Id
    public Integer id;

    @OneToMany(mappedBy="student")
    public List<Bridge> bridges;

    public static Finder<Integer,Student> find = new Finder<Integer,Student>(
        Integer.class, Student.class
    );
}

Course.java:
@Entity
public class Course extends Model {

    @Id
    public Integer id;

    @OneToMany(mappedBy="course")
    public List<Bridge> bridges;

    public static Finder<Integer,Course> find = new Finder<Integer,Course>(
        Integer.class, Course.class
    );
}

Bridge.java:
@Entity
public class Bridge extends Model {

    @Id
    public Integer id;

    @ManyToOne public Student student;

    @ManyToOne public Course course;

    public String additional_field;

    public static Finder<Integer,Bridge> find = new Finder<Integer,Bridge>(
        Integer.class, Bridge.class
    );
}

EDIT
After many attempts I have found solution with composite key in Bridge class. Classes Student and Course are the same as in previous solution.
Bridge.java changed to following:
@Entity
public class Bridge extends Model {

    Bridge() {
        bridgeId = new BridgeId();
    }

    @EmbeddedId
    protected BridgeId bridgeId;

    @ManyToOne
    @JoinColumn(name = "student_id", insertable = false, updatable = false)
    private Student student;

    @ManyToOne
    @JoinColumn(name="course_id", insertable = false, updatable = false)
    private Course course;

    public String additional_field;

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student aStudent) {
        student=aStudent;
        bridgeId.student_id = aStudent.id;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course aCourse){
        course=aCourse;
        bridgeId.course_id = aCourse.id;
    }
}

And there is additional BridgeId.java:
@Embeddable
public class BridgeId implements Serializable
{
    public Integer student_id;

    public Integer course_id;

    public int hashCode() {
        return student_id + course_id;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        BridgeId b = (BridgeId)obj;
        if(b==null)
            return false;
        if (b.student_id == student_id && b.course_id == course_id) {
            return true;
        }
        return false;
    }
}

What is more important in this code is:

*

*Fields of embedded id are mapped to the same columns as ManyToOne relations.

*Value to 'student_id' and 'course_id' columns are inserted from embedded id and not from relations. This is because relations have attributes 'insertable' and 'updatable' set to false.

*I had to add getters and setters to 'student' and 'course' fields. In setters I am updating fields of embedded key.

Above solution has several workarounds. But I wasn't ableto find easier and cleaner one.


text:
Q: Creating concatenative summary data in SAS (PROC SQL) I have a SAS dataset (change_detail) that maintains change variables and looks like this (except there are over 200 change variables in the actual table):
Reference Chg1Code Chg1Desc Chg2Code Chg2Desc Chg3Code Chg3Desc
--------- -------- -------- -------- -------- -------- --------
1234                        C        Change2
1234      C        Change1  C        Change2
1234      C        Change1                    C        Change3
2345      C        Change1                    C        Change3
2345                                          C        Change3
3456                        C        Change2  C        Change3
3456      C        Change1  C        Change2
3456      C        Change1
3456      C        Change1                    C        Change3

I need to distill this information into a summary of the changes that have occurred to each reference number. When I used the following PROC SQL in SAS:
proc sql;
create table work.changedata_summary as
select distinct
      a.Reference,
      catx(',',a.Chg1Desc,a.Chg2Desc,a.Chg3Desc) as Changes length=1000
from
      work.change_detail a
;
quit;

It concatenates the individual Change Description variables, but maintains the original number of observations per Reference Number. The results I get are:
Reference Changes
--------- -------
1234      Change2
1234      Change1,Change2
1234      Change1,Change3
2345      Change1,Change3
2345      Change3
3456      Change2,Change3
3456      Change1,Change2
3456      Change1
3456      Change1,Change3

I need some help in flattening this data out (using either PROC SQL or a DATA step) to show just the summary results by distinct Reference number. The expected result is:
Reference Changes
--------- -----------------------
1234      Change1,Change2,Change3
2345      Change1,Change3
3456      Change1,Change2,Change3

Any help provided will be appreciated! Thanks!

A: if your data is something like this then adding a group by and max to your code should work
  proc sql;
  create table work.changedata_summary as
  select
        Reference,
  catx(',',max(chg1Desc),max(Chg2Desc), max(Chg3Desc)) as Changes length=1000
  from
  have
  group by Reference
  ;
  quit;

A: I wouldn't even try to do such a thing in PROC SQL.  If you just want to see the last non-empty change for each variable then use a data step with an UPDATE statement to collapse the data to one observation per group.
data want ;
  update have (obs=0) have ;
  by reference ;
  length changes $500 ;
  changes=catx(',',of change1-change3);
run;

A: I would use Data step for this kind of operation
Try this out
data want;

length change_tot $200.;

   do until (last.Reference);

      set have;

        by Reference notsorted;

      change_tot=catx(',',change_tot,Chg1Desc, Chg2Desc, Chg3Desc);

   end;

   Keep reference change_tot;

run;


text:
Q: Delete attribute in XML I want to completely remove the size="id" attribute from every <door> element.
<?xml version="1.0" encoding="UTF-8"?>
<doors>
<door id="1" entry="3249" size="30"/>
<door id="1041" entry="6523" size="3094"/>
-- and 1000 more....
</doors>

The PHP code:
$xml = new SimpleXMLElement('http://mysite/doors.xml', NULL, TRUE);
$ids_to_delete = array( 1, 1506 );
foreach ($ids_to_delete as $id) {
    $result = $xml->xpath( "//door[@size='$id']" );
    foreach ( $result as $node ) {
        $dom = dom_import_simplexml($node);
        $dom->parentNode->removeChild($dom);
    }
}

$xml->saveXml();

I get no errors but it does not delete the size attribute. Why?

A:
I get no errors but it does not delete the size attribute. Why?

There are mulitple reasons why it does not delete the size attribute. The one that popped first into my mind was that attributes are no child nodes. Using a method to remove a child does just not fit to remove an attribute.

Each element node has an associated set of attribute nodes; the element is the parent of each of these attribute nodes; however, an attribute node is not a child of its parent element.

From: Attribute Nodes - XML Path Language (XPath), bold by me.
However, you don't see an error here, because the $result you have is an empty array. You just don't select any nodes to remove - neither elements nor attributes - with your xpath. That is because there is no such element you look for:
//door[@size='1']

You're searching for the id in the size attribute: No match.
These are the reasons why you get no errors and it does not delete any size attribute: 1.) you don't delete attributes here, 2.) you don't query any elements to delete attributes from.
How to delete attributes in SimpleXML queried by Xpath?
You can remove the attribute nodes by selecting them with an Xpath query and then unset the SimpleXMLElement self-reference:
// all size attributes of all doors
$result = $xml->xpath("//door/@size");
foreach ($result as $node) {
    unset($node[0]);
}

In this example, all attribute nodes are queried by the Xpath expressions that are size attributes of door elements (which is what you ask for in your question) and then those are removed from the XML.
//door/@size

(see Abbreviated Syntax)
Now here the full example:
<?php
/**
 * @link https://eval.in/215817
 */

$buffer = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<doors>
<door id="1" entry="3249" size="30"/>
<door id="1041" entry="6523" size="3094"/>
-- and 1000 more....
</doors>
XML;

$xml = new SimpleXMLElement($buffer);

// all size attributes of all doors
$result = $xml->xpath("//door/@size");
foreach ($result as $node) {
    unset($node[0]);
}

$xml->saveXml("php://output");

Output (Online Demo):
<?xml version="1.0" encoding="UTF-8"?>
<doors>
<door id="1" entry="3249"/>
<door id="1041" entry="6523"/>
-- and 1000 more....
</doors>

A: You can do your whole query in DOMDocument using DOMXPath, rather than switching between SimpleXML and DOM:
$dom = new DOMDocument;
$dom->load('my_xml_file.xml');

# initialise an XPath object to act on the $dom object
$xp = new DOMXPath( $dom );

# run the query
foreach ($xp->query( "//door[@size]" ) as $door) {
    # remove the attribute
    $door->removeAttribute('size');
}

print $dom->saveXML();

Output for the input you supplied:
<?xml version="1.0" encoding="UTF-8"?>
<doors>
    <door id="1" entry="3249"/>
    <door id="1041" entry="6523"/>
</doors>

If you do want only to remove the size attribute for the IDs in your list, you should use the code:
foreach ($ids_to_delete as $id) {
    # searches for elements with a matching ID and a size attribute
    foreach ($xp->query("//door[@id='$id' and @size]") as $door) {
        $door->removeAttribute('size');
    }
}

Your code wasn't working for several reasons:

*

*it looks like your XPath was wrong, since your array is called $ids_to_delete and your XPATH is looking for door elements with the size attribute equal to the value from $ids_to_delete;

*you're converting the nodes to DOMDocument objects ($dom = dom_import_simplexml($node);) to do the deletion, but $xml->saveXml();, which I presume you printed somehow, is a SimpleXML object;

*you need to remove the element attribute; removeChild removes the whole element.


text:
Q: How to link to google chromes downloads page from html? I am making my own personal homepage for my chrome web browser. I want to add a link on this page to go to my downloads page. Such as if I were to hit ctrl+j or just type in "chrome://downloads" in my address bar. I have a link set up and I set the href attribute to "chrome://downloads" but it will not open. It does nothing at all.
Before anyone says to search for an answer, I have been searching for about an hour now.
example of my link:
Downloads

A: Chrome isn't allowing this for security reasons.
The JavaScript console says:

a JSFiddle is here.
It's unlikely that there is a workaround, although you could try having the file on a local file:/// URL and seeing whether the restrictions are less strict there.


text:
Q: how can I repeat monadic instructions inside kind's monads? I know that I can run monadic instructions sequentially inside monads in Kind language, like this:
Test: _
  IO {
   IO.print(Nat.show(2))
   IO.print(Nat.show(3))
   IO.print(Nat.show(4))
  }

output:
2
3
4

But is it possible to run monadic instructions repeatedly, like this below?
Test: _
  a = [2,1,3,4,5]
  IO {
    for num in a:
      IO.print(Nat.show(num))
  }

If it is possible how can I do it correctly?

A: Monads are usually represented by only two operators :
  return :: a -> m(a) // that encapulapse the value inside a effectful monad
  >>= :: m a -> (a -> m b) -> m b
  // the monadic laws are omitted

Notice, the bind operator is naturally recursive, once it can compose two monads or even discard the value of one and the return can be thought of as a "base case".
m >>= (\a -> ... >>= (\b -> ~ i have a and b, compose or discard? ~) >>= fixpoint)

You just have to produce that sequence, which is pretty straightforward. For example, in Kind we represent monads as a pair which takes a type-for-type value and encapluse a polymorphic type.
type Monad <M: Type -> Type> {
  new(
    bind: <A: Type, B: Type> M<A> -> (A -> M<B>) -> M<B>
    pure: <A: Type> A -> M<A>
  )
}

In your example, we just have to trigger the effect and discard the value, a recursive definition is enough :
action (x : List<String>): IO(Unit)
  case x {
    nil : IO.end!(Unit.new) // base case but we are not worried about values here, just the effects
    cons : IO {
      IO.print(x.head) // print and discard the value
      action(x.tail) // fixpoint
    }
  }

test : IO(Unit)
  IO {
    let ls = ["2", "1", "3", "4", "5"]
    action(ls)
  }

The IO as you know it will be desugared by a sequence of binds!
Normally in case of list it can be generalized like the mapM function of haskell library :
Monadic.forM(A : Type -> Type, B : Type,
  C : Type, m : Monad<A>, b : A(C), f : B -> A(C), x : List<A(B)>): A(C)
  case x {
    nil : b
    cons :
      open m
      let k = App.Kaelin.App.mapM!!!(m, b, f, x.tail)
      let ac = m.bind!!(x.head, f)
      m.bind!!(ac, (c) k) // the >> operator
  }

It naturally discard the value and finally we can do it :
action2 (ls : List<String>): IO(Unit)
  let ls = [IO.end!(2), IO.end!(1), IO.end!(3), IO.end!(4), IO.end!(5)]
  Monadic.forM!!!(IO.monad, IO.end!(Unit.new), (b) IO.print(Nat.show(b)), ls)

So, action2 do the same thing of action, but in one line!.
When you need compose the values you can represent as monadic fold :
Monadic.foldM(A : Type -> Type, B : Type,
  C : Type, m : Monad<A>, b : A(C), f : B -> C -> A(C), x : List<A(B)>): A(C)
  case x {
    nil : b
    cons :
      open m
      let k = Monadic.foldM!!!(m, b, f, x.tail)
      m.bind!!(x.head, (b) m.bind!!(k, (c) f(b, c)))
  }

For example, suppose that you want to sum a sequence of numbers that you ask for the user in a loop, you just have to call foldM and compose with a simple function :
Monad.action3 : IO(Nat)
  let ls = [IO.get_line, IO.get_line, IO.get_line]
  Monadic.foldM!!!(IO.monad, IO.end!(0),
      (b, c) IO {
        IO.end!(Nat.add(Nat.read(b), c))
      },
   ls)

test : IO(Unit)
  IO {
    get total = action3
    IO.print(Nat.show(total))
  }

For now, Kind do not support typeclass so it make the things a little more verbose, but i think a new support to forM loops syntax can be thought in the future. We hope so :)


text:
Q: How does the Chrome Web Store page work? There are some oddities in the Chrome Web Store:

*

*It opens dialogs navigating to new URLs

*while this happens the screen doesn't flash

*and the original page is still shown behind the dialog with the same items and scroll position

I have a background in HTML4 where I couldn't do this and I don't know if it is possible to do the same in HTML5.
My guess is that this behavior is because the Chrome browser has special behavior when handling its store.

A: It uses the new HTML5 history.pushState(); method, as demoed here and explained here.

A: Read about jQuery, Dojo, MooTools, YUI, script.aculo.us, etc.
Javascript is pretty powerful these days, and can be used to do some advanced stuff in your browser.  For diaglogs, you can look at things like DOMWindow, FancyBox, etc.  You can place an entirely separate web page into the pop-up dialog.
This StackOverflow question gathered some other suggestions too.  There are many alternatives.


text:
Q: Python - Copy element I've been practicing Python watching tutorials and reading books and I'm struggling with the copy function. I'm trying to copy an ID that gets populated into an element box, so I locate the element and try to copy it but doesn't work. :(
alert = driver.switch_to_alert()
alert.accept()
driver.find_element_by_xpath('/html/body/form[2]/table[1]/tbody/tr[1]/td[3]').copy2.copy()

I receive this error -

AttributeError: 'WebElement' object has no attribute 'copy2'

I want to have my program copy the numbers in the 'Search ID' box.

A:
A WebElement instance has no copy2 attribute in Python selenium
  bindings. – alecxe 1 hour ago

Thank you Alexcxe for this answer
The resolution:
Originally what I had wanted to do was copy the text in an element field and save it for later use. What I have done now to resolve the issue is save the text.
for element in driver.find_elements_by_xpath('/html/body/form[2]/table[1]/tbody/tr[1]/td[3]'): print ("This is the shopID") print (element.text)

Now I have it saved when I run the program


text:
Q: Represent Number Line in iphone app I am looking to display number line in my application
How this can be done? I also want to control number like programatically

A: There's no easy standard component to do this. You will need to subclass UIView and override drawRect. Then you can use Core Graphics to draw the number line.

A: you can use views with different sizes and background colours. Use #define -s for the fixed sizes.
You should have 3 functions:
one that draws the horizontal red/blue rects
-(UIView *) drawHorizontal:(CGRect)frame withColor:(UIColor)theColor;

one that draws vertical spacers and labels underneath. Iterate for whole line width.
-(UIView *) drawVertical:(CGPoint)centerPosition withLabel:(int)number;

Your number line should be stored as an NSArray of NSDictionaries containing the position (index) and length of the horizontal red/blue lines.
Hope this helps.


text:
Q: Dynamic constructor name in js I want to do exactly the same as this question but use the function as a constructor.
> function nameFunction(name, body) {
   return {[name](...args) {return body(...args)}}[name]
}

> b = nameFunction('c', function () {})
[Function: c]
> typeof b
'function'

b is a function, yet it is not a constructor:
> new b()
Uncaught TypeError: b is not a constructor

If done in the standard way, it is a constructor:
> b = function() {}
[Function: b]
> new b()
b {}

But the name is b, not c.
How can I build a constructor with the given name and not using eval?

A: The answer provided by georg is correct but incomplete. In order to use the dynamically named function as a constructor, not only do you need to use an ordinary function but also you need to preserve the this context. We can do this by applying this and arguments to the body as follows.

function nameFunction(name, body) {
    const object = {
        [name]: function () {
            return body.apply(this, arguments);
        }
    };

    return object[name];
}

const Bar = nameFunction("Foo", function (foo) {
    this.foo = foo;
});

console.log(Bar.name, new Bar(42));

A: Methods are not constructors (see https://262.ecma-international.org/7.0/#sec-functioncreate and https://262.ecma-international.org/7.0/#sec-functionallocate). Just define it as an ordinary function:
function nameFunction(name, body) {
   return {[name]: function(...args) {return body(...args)}}[name]
}

b = nameFunction('c', function () {})

new b


text:
Q: C# Regex.Replace does not replace I've got a little problem for you geniuses.
I have tested a pattern with "RegexLab" for replacing/filtering text. It worked perfectly there, but my code didn't do well.
Pattern:

(.*?)
.*?

Replacement

$1

Input:
Title\n
\n

Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
\nTitle
\n

Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n

What the output should be like:
Title\n
\n

Text\n
\n
Text\n
\n
Text\n
\n
Text\n
\n
Text\n
\n
Text\n
\n
\nTitle
\n

Text\n
\n
Text\n
\n
Text\n
\n
Text\n
\n
Text\n
\n

My code:
string filteredText = Regex.Replace(Input, Pattern, Replacement);

Problem:
My output is wrong, I don't get the filtered text, I get the whole unfiltered Input. RegexLab shows me that everything is right.
Whole code (will look dirty here)
           string input = "Title\n
\n

Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
\nTitle
\n

Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
Text\n

Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
Trash
\n
\n
\n
";
        string pattern = @"
(.*?)
.*?
";
        string replacement = "
$1";
        string filteredText = Regex.Replace(input, pattern, replacement);

Working code in PHP (needed in C#):
preg_replace("/
(.*?)
.*?<\/ul>/s",'
$1',$input);

I need a solution without HtmlAgilityPack!

A: Try with:
Regex.Replace(input, pattern, replacement, RegexOptions.Singleline);

You need to have the interpreter to see to whole string as a single line text, otherwise . (dot) will not match the \n (line feed)


text:
Q: Передать переменную из одного метода в другой как сделать что бы в консоль выводился result?
namespace metodi
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] massiv;
            Console.Write(result);
            Console.ReadLine();
        }

        void rewenie()
        {
            int[] massiv = new int[] { 10, 23, 14, 5, 20, 10, 14, 5, 3, 23 };
            var result = massiv.Distinct().ToArray();
        }
    }
}

A: Объявить что rewenie возвращает не void, а int[]:
static int[] rewenie()

Вернуть результат:
int[] massiv = new int[] { 10, 23, 14, 5, 20, 10, 14, 5, 3, 23 };
var result = massiv.Distinct().ToArray();
return result;

Ну и использовать для вывода:
Console.Write(rewenie());

Как-то так в итоге:
static void Main(string[] args)
{
    Console.Write(rewenie());
    Console.ReadLine();
}

static int[] rewenie()
{
    int[] massiv = new int[] { 10, 23, 14, 5, 20, 10, 14, 5, 3, 23 };
    var result = massiv.Distinct().ToArray();
    return result;
}


text:
Q: Carbon PHP Loop through each month on date range I have a date range ($startDate, $endDate). Based on the range that is given I need to loop through each month and run a specific job.
Currently I am doing this as such:
    //Get startOf and endOf to cover entire month of range.
    $currentDate = Carbon::parse($startDate)->startOfMonth();
    $endDate = Carbon::parse($endDate)->endOfMonth();

    //Number of weeks helps with the for loop
    $numberOfMonths = $currentDate->diffInMonths($endDate);

    for ($x = 0; $x <= $numberOfMonths; $x++)
    {
        //something here

        $currentDate = $currentDate->addMonths(1);
    }

This is done with carbon and php. The problem with the current method is that diffInMonths apparently simply divides by 30 and some how skips February as it only has 28 days.
I need some sort of loop by each month. So for example if my date range was 2018-01-15 and 2018-04-25, it should loop through four times, 1/2/3/4 and stop. Currently it is going 1/3/4 and stop.
Is there some simple work around for this, that I can loop through the months within a date range?


text:
Q: Can't move a view to the center of the screen (programmatically, not with layout properties) - Android This might look like a very common problem but I can't seem to move a view to the center of the screen.
I have 3 views:

*

*a background image (center crop)

*a black/white grid to visualize the center of the screen, for debugging purpose. Also center crop

*a square that I want to move to the center, top left corner of the square at the center of the screen.

I first get the screen size in pixels, divide width and height by 2 to get the coordinates of the center. Then move my square view by center.x and center.y
I expect the square to be moves precisely to the center of the screen.
I also scale the square view so its size is always the same relative to the background image.
I want to solve this programmatically (not just centering with layout properties) because it is only a first step, I intend to be able to place the square anywhere I want on the screen. I try to place in the center here because it seems like the easiest thing to do.
The code
public class FullScreenActivity extends AppCompatActivity {

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                  View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            );
        }
    }

}

The class whit the logic
public class AnimalPopupActivity extends FullScreenActivity {

    private final String TAG = "AnimalPopup";

    ImageView backgroundView;
    ImageView square;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_animal_popup);

        backgroundView = (ImageView)findViewById(R.id.background);

        square = (ImageView) findViewById(R.id.square);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenWidthInPixels = metrics.widthPixels;
        int screenHeightInPixels = metrics.heightPixels;
        Log.i(TAG, "screen width pixels: "+screenWidthInPixels);
        Log.i(TAG, "screen height pixels: "+screenHeightInPixels);

        Point center = new Point(screenWidthInPixels/2, screenHeightInPixels/2);
        Log.i(TAG, "center: "+center);

        double ratioH = (double)screenWidthInPixels/100d;
        Log.i(TAG, "ratioH: "+ratioH);
        double ratioV = (double)screenHeightInPixels/100d;
        Log.i(TAG, "ratioV: "+ratioV);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)(10*ratioH), (int)(10*ratioV));
        layoutParams.leftMargin = center.x;
        layoutParams.topMargin = center.y;
        square.setLayoutParams(layoutParams);
    }
}

Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bentaye.app.games.AnimalPopupActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/background"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            app:srcCompat="@drawable/animal_popup_background" />

        <ImageView
            android:id="@+id/grid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            app:srcCompat="@drawable/animal_popup_grid" />

        <ImageView
            android:id="@+id/square"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/square" />

    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

Here is what I get on a Nexus 5 (1080*1920:420dpi)

With the following logs:

screen width pixels: 1080
screen height pixels: 1794
center: Point(540, 897)
ratioH: 10.8
ratioV: 17.94

Here is what I get on a Nexus 10 (2560*1600:xhdpi)

With the following logs:

screen width pixels: 1600
screen height pixels: 2464
center: Point(800, 1232)
ratioH: 16.0
ratioV: 24.64

The 2 are off by a few pixels, I am not an Android specialist and clearly I am doing something wrong but can't understand what.
Any help welcome. Cheers!
EDIT: I think that it is due the calculation taking the status bar into account. It also explains why the discrepancy is bigger on the Nexus5, as the status bar is bigger relatively to the screen height. And also why the discrepancy only affects the vertical alignment.
I'll come back and post the code once I sort it out.

A: Assuming the square you want centered is inside the RelativeLayout, add layout_gravity=center
For example:
<ImageView
    android:id="@+id/square"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity=center"
    app:srcCompat="@drawable/square"/>

A: Add this Line
android:layout_centerInParent="true"

this line is for RelativeLayout


text:
Q: I can't install ffmpegs (dependencies) - error with doxygen [mac 10.12.6 Sierra] It installed about 70% of the dependencies it needed to get ffmpegs going, but it got stuck at installing 'doxygen'.
This is the error I got:
==> Installing dependencies for ffmpeg: doxygen, little-cms2, openjpeg, opus, rust, libgit2, cargo-c, rav1e, flac, libsndfile, libsamplerate, rubberband, sdl2, swig, llvm, snappy, speex, srt, leptonica, libb2, lz4, libarchive, tesseract, theora, x264, x265, xvid, docbook, boost, source-highlight, asciidoc, docbook-xsl, libyaml, ruby, asciidoctor, gnu-getopt, xmlto, libsodium, zeromq and zimg
==> Installing ffmpeg dependency: doxygen
==> cmake ..
==> make
Last 15 lines from /Users/macbook/Library/Logs/Homebrew/doxygen/02.make:
In file included from /tmp/doxygen-20220723-61533-5m5mdv/doxygen-1.9.4/src/outputlist.h:25:
/tmp/doxygen-20220723-61533-5m5mdv/doxygen-1.9.4/src/searchindex.h:29:10: fatal error: 'variant' file not found
#include <variant>
         ^~~~~~~~~
1 error generated.
make[2]: *** [src/CMakeFiles/doxymain.dir/__/generated_src/code.cpp.o] Error 1
make[1]: *** [src/CMakeFiles/doxymain.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
[ 46%] Linking CXX static library ../lib/libvhdlparser.a
cd /tmp/doxygen-20220723-61533-5m5mdv/doxygen-1.9.4/build/vhdlparser && /usr/local/Cellar/cmake/3.23.2/bin/cmake -P CMakeFiles/vhdlparser.dir/cmake_clean_target.cmake
cd /tmp/doxygen-20220723-61533-5m5mdv/doxygen-1.9.4/build/vhdlparser && /usr/local/Cellar/cmake/3.23.2/bin/cmake -E cmake_link_script CMakeFiles/vhdlparser.dir/link.txt --verbose=1
/usr/bin/ar qc ../lib/libvhdlparser.a CMakeFiles/vhdlparser.dir/CharStream.cc.o CMakeFiles/vhdlparser.dir/ParseException.cc.o CMakeFiles/vhdlparser.dir/Token.cc.o CMakeFiles/vhdlparser.dir/TokenMgrError.cc.o CMakeFiles/vhdlparser.dir/__/generated_src/VhdlParser_adj.cc.o CMakeFiles/vhdlparser.dir/VhdlParserTokenManager.cc.o
/usr/bin/ranlib ../lib/libvhdlparser.a
[ 46%] Built target vhdlparser
make: *** [all] Error 2

Do not report this issue to Homebrew/brew or Homebrew/core!

Error: You are using macOS 10.12.
We (and Apple) do not provide support for this old version.
You will encounter build failures with some formulae.
Please create pull requests instead of asking for help on Homebrew's GitHub,
Twitter or any other official channels. You are responsible for resolving
any issues you experience while you are running this
old version.

Can someone please help me am not sure what it is, that I am supposed to do.

A: Looks like we're in the same boat. Fighting the "good fight", as it were.  We should probably both just bail to linux or even windows, because god knows they are going to keep making this hard for us....
However, probably like yourself, a combination of inertia and "good reasons" keeps us staying the course ;)
Basically, the issue is described correctly by the others here (lack of c++ 17 support) and in my case (and likely yours as well) is because gcc is a symlink to clang (9.0 if you are using the latest version compatible with our os)
Telling brew to use real gcc (I assume you have compiled it already, and if not - gcc 11.3.0 is a dependency for ffmpeg anyhow, so go ahead and build it; brew install gcc) can be done like this :
HOMEBREW_CC=gcc-11 HOMEBREW_CXX=g++-11 brew install doxygen

However, the above didn't work for me because - although it solved the c++ 17 issue, it exposed another problem :(
It seems that for some reason the minimum macos version number is messed up (I think because the sdk headers for 10.13 are installed with the latest version of xcode compatible with our os) and so the compilation fails.  Although there is almost certainly a better/cleaner way to deal with this issue, I solved it by manually compiling and installing doxygen after editing the code.
In the doxygen/filesystem/filesystem.hpp file around line 4491 you need to change the line
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 101300

to
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 111400

Then compile doxygen (extract the source from the brew cache), cd to the cmake folder then run
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local/Cellar/doxygen/1.9.4 -DCMAKE_INSTALL_LIBDIR=lib -DCMAKE_BUILD_TYPE=Release -DCMAKE_FIND_FRAMEWORK=LAST -DCMAKE_VERBOSE_MAKEFILE=ON -Wno-dev -DBUILD_TESTING=OFF -DCMAKE_C_COMPILER=gcc-11 -DCMAKE_CXX_COMPILER=g++-11

make
make install
brew link doxygen

Then continue the brew install ffmpeg.  I had trouble with nettle as well, and needed to compile and install that one manually too because the version of libcrypto packaged with macos (libressl) is incompatible.  I had to do the steps shown in "brew info openssl@1.1" in order to make sure the compiler used the openssl libcrypto that IS compatible and I couldn't figure out how to make brew do this for me.
Fun fun fun.  I am not all that hopeful that the rest of the compilation will go without issue, but it is chugging away again now.  I get the distinct impression that this is SO not worth the hassle/trouble.
Good luck!
** EDIT **
I'm still slogging through it, and it is taking a LONG time.  But as I encounter more issues I will try and detail them here with the hope that each issue I encounter is reasonably easy to overcome.

*

*llvm failed to compile with lots of missing header errors.  Directing brew to use gcc-11 like i did with doxygen worked to compile it further (27%) but still failed (it looks like because it is calling clang specific options as a result of the brew cmake config passed to it... i'm still working on this one...)

Conclusion - I gave up.  It isn't worth the time in my view.
Instead I installed macports and used "sudo port install ffmpeg-upstream" to install ffmpeg-5.  Unless you have some dying need to compile yourself, I recommend you do this as well.

A: I've spent quite some time to get around this issue as well and I ended up with another solution. I merely edited the formula to suit my needs :
brew edit doxygen

Once there, spot the "def install" block then edit the file so that it looks like this :
fails_with :clang
def install
  inreplace "CMakeLists.txt", "MACOS_VERSION_MIN 10.14", "MACOS_VERSION_MIN 10.11"

Save, exit.
In short, just add the "fails_with" line and the "inreplace" line. The first one causes brew to not use clang (so you need to have a gcc copy somewhere). This is to solve the C++17 issue. The second one patches the CMakeLists.txt file to allows cmake to do its magic. Once done, "brew install doxygen" should succeed.