text:
Q: How to get top 1 from union tables I'm getting duplicate records. I was wondering how to just pull the top 1 with the highest "docdate- last date received" could anyone point me in the right direction. I am a novice to sql queries. I'm using MS sql sever 2016.
(
        select a.vendorid,
            max(a.DOCDATE) as [Last Date Received],
            max(b.VENDNAME) as [Vendor Name] --, b.VNDCLSID
            --  ,a.*
        from PM20000 a
        inner join PM00200 b on a.VENDORID = b.VENDORID
        where b.VNDCLSID in ('cb', '6')
        group by a.VENDORID
        )

union

(
    select a.VENDORID,
        max(a.DOCDATE) as [Last Date Received],
        max(b.VENDNAME) as [Vendor Name] --, b.VNDCLSID
        --,a.*
    from PM30200 a
    inner join PM00200 b on a.VENDORID = b.VENDORID
    where b.VNDCLSID in ('cb', '6')
    group by a.VENDORID
    )

A: For a single row with the latest [Last Date Received]:
select top 1 *
from (
    select a.vendorid,
        a.DOCDATE as [Last Date Received],
        b.VENDNAME as [Vendor Name]
    from PM20000 a
    inner join PM00200 b on a.VENDORID = b.VENDORID
    where b.VNDCLSID in ('cb', '6')
    union all
    select a.VENDORID,
        a.DOCDATE as [Last Date Received],
        b.VENDNAME as [Vendor Name]
    from PM30200 a
    inner join PM00200 b on a.VENDORID = b.VENDORID
    where b.VNDCLSID in ('cb', '6')
    ) u
order by [Last Date Received] desc

For the latest [Last Date Received] for each VendorId using top with ties with row_number():
select top 1 with ties *
from (
        select a.vendorid,
            a.DOCDATE as [Last Date Received],
            b.VENDNAME as [Vendor Name]
        from PM20000 a
        inner join PM00200 b on a.VENDORID = b.VENDORID
        where b.VNDCLSID in ('cb', '6')
    union all
    select a.VENDORID,
        a.DOCDATE as [Last Date Received],
        b.VENDNAME as [Vendor Name]
    from PM30200 a
    inner join PM00200 b on a.VENDORID = b.VENDORID
    where b.VNDCLSID in ('cb', '6')
    ) u
order by row_number() over (partition by VendorId order by [Last Date Received] desc)

Using a common table expression and ordering by [Last Date Received] desc:
;with cte as (
  select top 1 with ties *
  from (
      select a.vendorid,
          a.DOCDATE as [Last Date Received],
          b.VENDNAME as [Vendor Name]
      from PM20000 a
      inner join PM00200 b on a.VENDORID = b.VENDORID
      where b.VNDCLSID in ('cb', '6')
      union all
      select a.VENDORID,
          a.DOCDATE as [Last Date Received],
          b.VENDNAME as [Vendor Name]
        from PM30200 a
      inner join PM00200 b on a.VENDORID = b.VENDORID
      where b.VNDCLSID in ('cb', '6')
    ) u
  order by row_number() over (partition by VendorId order by [Last Date Received] desc)
)
select
    VendorId
  , VendorName
  , [Last Date Received]
  , Days_LastInvoiced = datediff(day,[Last Date Received],getdate())
from cte
order by [Last Date Received] desc

without the common table expression...

select
    VendorId
  , VendorName
  , [Last Date Received]
  , Days_LastInvoiced = datediff(day,[Last Date Received],getdate())
from (
  select top 1 with ties *
  from (
      select a.vendorid,
          a.DOCDATE as [Last Date Received],
          b.VENDNAME as [Vendor Name]
      from PM20000 a
      inner join PM00200 b on a.VENDORID = b.VENDORID
      where b.VNDCLSID in ('cb', '6')
      union all
      select a.VENDORID,
          a.DOCDATE as [Last Date Received],
          b.VENDNAME as [Vendor Name]
      from PM30200 a
      inner join PM00200 b on a.VENDORID = b.VENDORID
      where b.VNDCLSID in ('cb', '6')
    ) u
  order by row_number() over (partition by VendorId order by [Last Date Received] desc)
)
order by [Last Date Received] desc

A: For performance reasons, I would suggest that you do the TOP before doing the UNION . . . and to use UNION ALL:
select top 1 *
from ((select top 1 a.vendorid, max(a.DOCDATE) as [Last Date Received],
              max(b.VENDNAME) as [Vendor Name]
       from PM20000 a inner join
            PM00200 b
            on a.VENDORID = b.VENDORID
      where b.VNDCLSID in ('cb', '6')
      group by a.VENDORID
      order by [Last Date Received] desc
     )
     union all
     (select top 1 a.VENDORID, max(a.DOCDATE) as [Last Date Received],
             max(b.VENDNAME) as [Vendor Name]
      from PM30200 a inner join
           PM00200 b
           on a.VENDORID = b.VENDORID
      where b.VNDCLSID in ('cb', '6')
      group by a.VENDORID
      order by [Last Date Received] desc
    )
   ) tt
order by [Last Date Received] desc;

As SQLZim points out, use with ties if you duplicates.


text:
Q: Status: Not By Design In light of the recent change in vote ordering, a certain aspect of the design process for SO has been highlighted.  It seems that certain features, while present in the system, are considered by the developers to be accidental (see this comment thread).  In this instance, the secondary ordering of answers by last change was "completely accidental, and was never by design."
Therefore, it seems the developers feel justified in making changes more arbitrarily than they would with parts of the system that were explicitly purposeful and by design. Since it was never intentional and certainly wasn't intended to be permanent, why not change it once a good idea comes along?
While I have no problem personally with the developers using whatever system they see fit to prioritize and implement code changes, I can see how it is frustrating for users (particularly those who frequent meta) to have their opinions weighed against the (unknown) original intentions of the developers.
Should the developers be more up front about which features may change at any time with little discussion, and which are carefully considered elements that will require extended consideration?  Is that even possible?
Or is this something that just has to be accepted as part of the package when dealing with a system as complex as SO?  After all, not every piece of code and layout is going to have been carefully considered.  Therefore, shouldn't we expect that some features are subject to change at the sole discretion of the developers?
At the end of the day, all features are at the discretion of the developers.  This is not open source, they own the code base.  But I think many people here on meta would like clarification on their role in making these decisions.

A: Let me preface this by saying that this post is not about the sorting of answers specifically. I do not want to discuss in this thread whether or not  it is a good idea. That has been done in other questions.
I think this issue actually highlights the flaw in Meta as a bug-tracking tool.
In the eyes of the developers (this is not official, this is my interpretation), they were fixing a bug that existed in the system. On typical bug-fixing issues, you do not have to go to the community, i.e. if there is a typo in an error message, you should just fix it and move on.
However, in this case the 'bug' that they fixed turned out to be near and dear to the hearts of many users.
Many people have made a hubbub about the fact that the community was not consulted, which doesn't really make sense to me because they did not anticipate that there would be controversy. I think it's too early to characterize 'the way they handled the controversy' because, as all of us can attest to, it's not over yet.
Meta is filled with hugely diverse questions. A lot of them are "how do I?", "feature requests", "bug reports", "I want to complain about xyz" and then a variety of things which are just wildly off-topic. In all of this, it is hard to get a handle on which questions and which pieces are 'code-actionable'.
If there was a way to keep track of a list of 'prospective functional code changes', then the community would be able to characterize their response to these things beforehand.
We already have an 'In-Progress' tag, but that only refers to the code changes which happen to be related to meta questions.
Suggested (possible) implementation
Every time you guys come up with an idea, or one of the StackOverflow Valued Associates makes a check in, you could log it on MSO with a Moderator-Only "In Next Release" tag.
Create a link that goes straight to the "In Next Release" Tags page. That way the community will have a very easy way to know exactly what changes are possible to happen in the next release, and they can discuss them.
This would also serve as release checklist, because once a deployment has occurred, you can change the tags one at a time to 'status-completed' once you have verified them in the production environment.
Hopefully, this will keep us from having venomous discussions after a deployment, and switch them to heated discussions prior to deployments. Oh, and this would only apply to changes that have a functional effect on the front end. I wouldn't expect any "performance tuning" type stuff to appear there, because it does not affect the features/bugs of the site.

A: I personally like the idea of feature changes being presented here on Meta first, with the community here giving feedback ont it, because that way I could have a part not only in the running of the system, but in the system design. (Architecture astronauts, anybody?)
I see two possible problems with that approach:

*

*Meta is already perceived as being elitist by some new users. This would add to that perception. (Even though that perception is clearly wrong IMO)

*The biggest challenge for the developers is to find a solution to the find S[OFU] through Google use case. Since we knwo the S[OFU] engine for quite some time now, we are by definition the worst group of people to judge how a new user perceives the site.
Anyway, having a notice here on Meta when a feature change is released would be very nice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I created a new folder on the terminal and is not shown in the finder I came across this issue in my new mac book pro. I created a folder using iterm and I have some content on it (I cloned a git repo). When I go to finder I don't see it.
So maybe I'm not in the right folder... but I tried to create the folder in the finder and I get the "folder already exists" error but still I don't see it.
Im using mojave 10.14.1

A: One of the most probable cause for this to happen is that you inadvertently entered a name which the Finder isn't able to display correctly (or doesn't display to protect us from the complexity of the underlying Unix filesystem).
To check this hypothesis, please from iTerm go into the parent directory of the one you created let's say its name is foo bar and enter:
ls -aBdl 'foo bar'

The -B option will display any non printable character as a \xxx where xxx is the octal value of the non printable character.
This option is very helpful to deal with filenames which cause problems to shells and graphical interfaces like the Finder.

A: Unless you gave it a very common name you can use locate filename from the terminal. This will list all occurrences of the character string 'filename'. It lists the complete path of all the matches it finds. I would go to the directory above the one you thought you created file in and run the locate command from there.


text:
Q: Templates para Laravel Estou iniciando um sistema que vai ser a base de todos os sistemas da empresa.
O sistema irei desenvolver em Laravael 4 e a interface será um tema do wrapbootstrap.
Quais seriam as melhores práticas para usar o meu layout como library/package para os meus futuros projetos?

A: Já fiz o que você está fazendo algumas vezes e no meu caso achei melhor picotar todo o tema, cada pedaço correspondente há algum elemento do layout(header,footer,sidebar etc..) desta forma fica melhor para reaproveitar apenas usando o @include('') então na maioria das vezes minha estrutura fica assim:
views
--layouts
----master.blade.php(estrutura do html)
----partials
------sidebar.blade.php
------header.blade.php
------footer.blade.php
------styles.blade.php
------scripts.blade.php
------navigation.blade.php
------alerts.blade.php

A: O que resolvi:
seguindo a idéia de Richard segue minha estrutura:
views
--layouts
----master.blade.php(estrutura do html)
----sections (alteração minha)
------sidebar.blade.php
------header.blade.php
------footer.blade.php
------styles.blade.php
------scripts.blade.php
------navigation.blade.php
------content.blade.php (será usado para carregar a view que a rota definir)
------alerts.blade.php

Minha dúvida final era se poderia definir um template para um controller ao invés de usar o USE em cada view. Segue a resposta para a minha dúvida:
http://laravel.com/docs/4.2/templates
class UserController extends BaseController {

/**
 * The layout that should be used for responses.
 */
protected $layout = 'layouts.master';

/**
 * Show the user profile.
 */
public function showProfile()
{
    $this->layout->content = View::make('user.profile');
}

}
Valeu pessoal.


text:
Q: {{#if currentUser}} too slow I have created an Admin area on my website, which is protected by a login, that is powered by the account-package.
My Admin Template currently looks like this:
<template name = "Admin">
{{#if currentUser}}
    {{> SideNav}}
    {{> Template.dynamic template = getCurrent}}
{{else}}
    {{> Login}}
{{/if}}
</template>

It works, but when i change the website, it always shows the login page for a second, before it changes to the dynamic template. It is short, but you can notice it and it doenst look very nice. So how should i go about this? I am not sure how to fix this.

A: Bringing your logging-in logic on the view might be an easy way to do, but as you can see it, it is not worth.
The logging-in related tests must be done asap in your application. You should do it in the router, as it will allow you to efficiently manage the accesses and start subscriptions before the view start rendering (this last point depends on your package and yout way of managing the renders though).
In addition, several packages provides very relevant tools to improve your app perfs and rendering in this kind of situation.
Here are some of them :

*

*meteorhacks:fastRender

*meteorhacks:subscription-manager

*kadira:flow-router (rather than Iron:router, which is way more random in rerunning the route and renders.)
Here is some example of how you would handle it with Flow Router.
The following example architecture is built according to The Meteor Chef model.
In this example, I assume you use alaning:roles package and code according to last version of Ecmascript.
/both/routes/__triggers.js
// Let's declare some namespace for our routing triggers
Triggers = {};
Triggers.mustBe = {};
Triggers.mustNotBe = {};

// Here, we check for the state of the client
Triggers.mustBe.loggedIn = ( ) => {
  if (!(Meteor.loggingIn() || Meteor.userId()))
  // If he is not logged in or logging in, we handle the redirection
  {
    FlowRoute = FlowRouter.current();
    if (FlowRoute.route.name != "home")
      Session.set("redirectAfterLogin", FlowRoute.path);
    FlowRouter.go('/splash');
  }
};

Triggers.mustBe.admin = ( ) => {
  // Same here. If the user is not an admin, we should redirect him somewhere or prevent the routing to be executed
  if (!Roles.userIsInRole(Meteor.user(), ['admin']))
    FlowRouter.go(FlowRouter.current().path);
};

// Just an example of what if would looks like if we wanted to be sure the client is not connected (for accessing the login screen for example)
Triggers.mustNotBe.loggedIn = ( ) => {
  if (Meteor.loggingIn() || Meteor.userId())
    FlowRouter.go('/');
};

/both/routes/_configuration.js
// We set the rendering root to the 'body' tag. Check for the doc links I give below
if (Meteor.isClient) Meteor.startup(function() { BlazeLayout.setRoot('body'); });

exposed_Routes = FlowRouter.group({
  name: "exposed",
  triggersEnter: []
});

loggedIn_Routes = FlowRouter.group({
  name: "loggedIn",
  triggersEnter: [
    Triggers.mustBe.loggedIn
  ]
});

// You might see that we declare the admin routes group from the logged_in group. Doing so, we will execute all the logged_in triggers before executing the one we define here. It will allow us to check if the user is connected before checking he is an admin
admin_Routes = loggedIn_Routes.group({
  name: "admin",
  triggersEnter: [
    Triggers.mustBe.admin
  ]
});

/both/routes/admin.js
admin_Routes.route('/admin/reports', {
  name: "reports",
  action: function (params, queryParams) {
    // We use kadira:BlazeLayout package to manage the rendering
    BlazeLayout.render('adminLayout', { main: "someTemplate", menu: "SideNav" });
    // Any other logic you would execute each time you create this route.
  }
});

/client/templates/layouts/admin.html
<template name="adminLayout">
  {{> Template.dynamic template=menu }}
  {{> Template.dynamic template=main }}
</template>

BlazeLayout & FlowRouter docs (by Kadira)

A: Probably you need {{loggingIn}} helper which is reactive and is true while login method is currently in progress.
http://docs.meteor.com/#/full/template_loggingin
<template name = "Admin">
    {{#if loggingIn}}
        Loading...
    {{else}}
        {{#if currentUser}}
            {{> SideNav}}
            {{> Template.dynamic template = getCurrent}}
        {{else}}
            {{> Login}}
        {{/if}}
    {{/if}}
</template>


text:
Q: Probability that population mean is less than $3$ given sample $\text{{1, 3, 3, 5, 9}}$ So I was wondering if you were given a sample within a population of unknown size, how you would determine the chance that the population's mean is less than $3$. The sample is $\text{{1, 3, 3, 5, 9}}$. I know about the standard deviation ($3.03$) and mean of the sample ($4.2$), that the population is normally distributed, and the expected value of the population's mean ($4.2$).
My approach to the problem was to assume population size $5$, find its standard deviation, and find the probability that the population mean is less than $3$. Then repeat with population size $6, 7, 8, 9...$ and find the average of the probabilities since each population size is equally likely. This is how the math looks like: $$P(\mu \leq 3) = \lim_{t \to \infty} \frac {\sum ^{t}_{i = 5} P_i(\mu_i \leq 3)}{t-5}$$ where $P_i$ is the probability that the mean is less than $3$ for population size $i$. Unfortunately, I cannot find this function without knowing the standard deviation of the population. How do I find the standard deviation knowing this information (in $1$st paragraph)?

A: This is the kind of question that Bayesian statistics answers.
The traditional way of doing statistics that gets covered early on (AP statistics, for instance) is called frequentist statistics. It is not that frequentist statistics gets it wrong or is worthless, but frequentist statistics cannot and should not answer this question.
Frequentist statistics answers how likely it is to get a mean of at least 4.2, under the assumption that the population has a mean of 3, which is somewhat of the reverse of what you seek. (This is just about the definition of a p-value.)
Bayesian statistics, however, combines your observations with some prior beliefs; this is the prior distribution. If you believe, before collecting data, that you have a population that's $N(3,1)$, your five observations do not change your belief very much. The combination of prior beliefs and data form the posterior distribution of $\mu$, which would allow you to calculate the probability that $\mu<3$.
However, you must make some assumption for that prior belief. Without that, the question cannot be answered.

A: Are you familiar with the difference between the Frequentist/Bayesian approaches of statistical inference?
The reason I'm asking is because, asking:

(1) What is the chance the mean of a population is less than x?

Is a valid question within the Bayesian framework and not a valid question within the frequentist framework.
In the Frequentist framework we assume the parameter we wish to infer about (in your case, the population mean) has a fixed unknown value. In this school of thought, it doesn't make any sense to ask what's the probability that the population mean is less than 3 as the mean is either 3 or not - the mean isn't a random variable.
We can however test the hypothesis that the population mean is less than three. The difference is, that now we are asking:

(2) Is the population mean less than 3?

Notice that this question doesn't involve asking about the probability of the values the mean can take. In order to answer (2) we typically use hypothesis testing. PennState
and StatTrek have some guides on hypothesis testing. For your problem, you are should look for the one sided test of a mean.
In the Bayesian paradigm the unknown parameter is treated as a random variable, this allows us to ask questions such as (1). The randomness is incorporated into the unknown parameter by giving it a prior distribution. This prior distribution should reflect our beliefs on the possible values that the parameter can take, possibly due to past experience. You might for example know that $\mu\sim N(0,1)$. The Bayesian inference is based on the posterior distribution of the parameter, which is the distribution of the parameter given the observed data. I think it's best to understand frequentist inference before approaching the Bayesian solution. If your'e looking into a learning more, this is a very good book and concise book on statistical theory (Abramovich was my lecturer for statistical theory).


text:
Q: Dynamically change to portrait mode - SSSP I am successfully running my application in portrait mode. Thanks for the great documentation here:
http://www.samsungdforum.com/B2B/Guide/tut20009/index.html
But I have a big issue now. I need to change the orientation dynamically. Do SSSP have any such API for changing the orientation dynamically (just by code).
Any idea/help will be greatly appreciated.
PS- We have 3x LFD TV (DM32D, DM48D, DB32D)


text:
Q: Invoking a ASP.NET MVC controller from a request handler with more than one parameter as data I am working on building an MVC frontend for a CMS system. The CMS system will serve ASP.NET MVC with pages and content.
In Global.asax I registered a custom route handler like this:
public class MvcApplication : EPiServer.Global
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.Add(new Route("{*data}", new MvcRouteHandler()));
    }

    protected void Application_Start()
    {
        ControllerBuilder.Current.SetControllerFactory(new MvcControllerFactory());
        ModelBinders.Binders.Add(typeof(MvcPageData), new PageDataModelBinder());
        RegisterRoutes(RouteTable.Routes);
    }
}

This is how my route handler looks like:
public class MvcRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MvcRequestHandler(requestContext);
    }
}

And my MVC request handler:
protected void ProcessRequest(HttpContext httpContext)
{
    List<string> pageParams;

    // Get the requested page from the CMS
    EPiServer.UrlBuilder internalUrlBuilder = GetInternalUrl(httpContext.Request.RawUrl, out pageParams);
    MvcPageData mvcPage =
        CurrentPageResolver.Instance.GetCurrentPage(internalUrlBuilder.QueryCollection["id"] ??
            string.Empty);

    string controllerName = mvcPage.ControllerName;
    if (pageParams.Count == 0)
    {
        mvcHandler.RequestContext.RouteData.Values.Add("action", "Index");
    }
    else
    {
        mvcHandler.RequestContext.RouteData.Values.Add("action", pageParams[0]);
    }

    mvcHandler.RequestContext.RouteData.Values.Add("controller", controllerName);
    mvcHandler.RequestContext.RouteData.Values["data"] = mvcPage; // This works fine, but I also want to add the remidning pageParams

    IController controller = ControllerBuilder.Current.
        GetControllerFactory().CreateController(mvcHandler.RequestContext, controllerName);

    controller.Execute(mvcHandler.RequestContext);
}

This is what a controller looks like today:
public class StandardController : Controller
{
    public ActionResult Index(MvcPageData currentPage)
    {
        return View(currentPage);
    }
}

My problem is that I want to be able to pass more than one parameter to the controller, so I will need to change the mvcHandler.RequestContext.RouteData.Values["data"] to contain some kind of list of parameters. I have searched but not found an solution to the problem, maybe it is really simple. The resulting controler might look something like this:
public ActionResult Index(MvcPageData currentPage, int id, string name)
Anyone knows how to do this? Thanks.

A: You can try to create array of objects with items count pageParams.Count and add to it the mvcPage object and all objects from pageParams except the first one (which is your action name).

A: I had missunderstood how the model binding works in MVC. I thought all the data sent to the controller had to be defined in ProcessRequest before calling controller.Execute, which not is the case.

A: Have you tried registering the handler in the Web.config?
<configuration>
  <system.web>
    <httpHandlers>
      <add verb="*" path="yourApiUrlPrefix/*"
        type="MvcRouteHandler, YourAssemblyName" />
    </httpHandlers>
  </system.web>
</configuration>


text:
Q: outlook mailitem not closing properly I have managed to open a new outlook mail item from c# code successfully using the following:
using Outlook = Microsoft.Office.Interop.Outlook;

Outlook.Application oApp;
Outlook.Inspectors oInspects;
Outlook._MailItem  oMailItem;

oApp = new Outlook.Application();
oInspects = oApp.Inspectors;
oMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

oMailItem.Display(true);

my problem is as follows:
when I click on the X in the corner of the mailitem window in order to close it, I receive a message asking if I want to save changes, which is OK. but after selecting the option "no", the email window closes but another one seems to appear right behind it (greyed out) and I have to click again on the X in the corner to close it.
the same happens if I click on the send button to send the email. the original window closes and then another window exactly the same (with all the content) appears but the buttons are greyed out and I have to click on the X in order to close it
I have tried to close the window using the following code (any combination of the lines below) but nothing seems to work:
oMailItem.Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olDiscard);
oMailItem.Delete();
Marshal.FinalReleaseComObject(oMailItem);
Marshal.ReleaseComObject(oApp);

if anyone has an idea on how to solve this I would greatly appreciate it. I have been busting my head for hours looking for an answer
thanks in advance

A: Even though this is 4 years old, here's how i solved the problem:
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(mailItem) != 0) { }
mailItem = null;
GC.Collect();
GC.WaitForPendingFinalizers();

A: Try to use oMailItem.Display(false); instead 'true'

A: I've tried your code with Outlook 2007 + VS 2010 Express.
The problem you are facing does not occur in my environment.
I tried with and without Outlook running when starting the code.
The "using" statement is part of the using section at the top of the source code, not a "using" variable reference in the routine.
The 'true' in oMailTime.Display(true) has to stay true to get a modal window.


text:
Q: Why it this printing "none" after running program? class student:
    def name(self):
        print('Aman')
        print('kant')
class hostel_fee(student):
    def hfee(self):
        print('hostel fee',int(78000))
        return 78000
class academic_fee(student):
    def afee(self,):
        print('academic fee',int(69500))
        return 69500*2
class total_fee(hostel_fee,academic_fee):
    def Total(self):
        self.h=super().hfee()
        self.a=super().afee()
        self.t=self.a+self.h
        print('total fee',self.t)
        print(super().name())
obj=total_fee()
obj.Total()

A: You are calling print(super().name()) in class total_fee, that in turn calls on student via the tree of inheritance, but this method returns nothing (None)


text:
Q: Are header files different for x86 and ARM for webrtc? I need to use webrtc in my Android native application.
After downloading the source for webrtc, here are the primary steps for building webrtc:
$ export GYP_DEFINES="OS=Android..."
$ gclient runhooks
$ ninja -C out/Release AppRTCDemo

The target architecture, ARM or x86, must be defined through GYP_DEFINES.
I need to decide if I must create platform-specific directories for webrtc source files. Does gclient runhooks modify webrtc source code in any way? Regards.


text:
Q: android studio error Cannot launch AVD in emulator I have some problems withs Android Studio, I installed and there are some errors.
Cannot launch AVD in emulator.
Output:
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  6 (X_GLXIsDirect)
  Serial number of failed request:  49
  Current serial number in output stream:  48
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  6 (X_GLXIsDirect)
  Serial number of failed request:  49
  Current serial number in output stream:  48
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  BadValue (integer parameter out of range for operation)
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  24 (X_GLXCreateNewContext)
  Value in failed request:  0x0
  Serial number of failed request:  33
  Current serial number in output stream:  34
QObject::~QObject: Timers cannot be stopped from another thread.

I don't understand, how to solve this?.


text:
Q: Jenkins - Git clone command not working on shell I have a very simple JOB in Jenkins on a Windows 10 machine, which is aimed to clone a github repo into a dir when triggered.
It's simple a Windows shell including a command git clone xxx some_output_dir: I'm not using GIT plugin.
This command will run forever and goes in timeout.
If I run manually in CMD it works perfectly.
Any idea on which setting I may need to look at?
output directory rights are correctly set.
Is there any convenient way to do so?


text:
Q: How can I install me gemfile, its giving errors? This is my gem file:
source "https://rubygems.org"
gem 'fastlane'
gem 'cocoapods'
gem 'CFPropertyList' gem 'slather'

plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
eval_gemfile(plugins_path) if File.exist?(plugins_path)

And this is the error message im getting:
[!] There was an error parsing `Gemfile`: Undefined local variable or method `'CFPropertyList' for Gemfile. Bundler cannot continue.

 #  from /Users/jordyhuijgens/Desktop/project folder/BwLidar/Gemfile:5
 #  -------------------------------------------
 #  gem 'cocoapods'
 >  gem 'CFPropertyList' gem 'slather'
 #
 #  -------------------------------------------

I am trying to install Travis CI for my IOS app.

A: Enter line each dependency
source "https://rubygems.org"

gem 'fastlane'
gem 'cocoapods'
gem 'CFPropertyList'
gem 'slather'

plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
eval_gemfile(plugins_path) if File.exist?(plugins_path)


text:
Q: tkinter display file name selected as text label in grid I'm new to Python and I'm trying to display the name of a file selected in a tkinter window using a grid format.
the code I have managed to put together so far is as follows:
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
import time

ws = Tk()
ws.title('Select Input Files')
ws.geometry('400x300')

def open_file():
    file_path = askopenfile(mode='r', filetypes=[('CSV Files', '*.csv')])
    if file_path is not None:
        pass

up1 = Label(
    ws,
    text='sales_history_document '
    )
up1.grid(row=0, column=0, padx=10)

btn1 = Button(
    ws,
    text ='Choose File',
    command = lambda:open_file()
    )
btn1.grid(row=0, column=1)

up2 = Label(
    ws,
    text='style_group_document '
    )
up2.grid(row=1, column=0, padx=10)

btn2 = Button(
    ws,
    text ='Choose File ',
    command = lambda:open_file()
    )
btn2.grid(row=1, column=1)

upld = Button(
    ws,
    text='Upload Files',
    command=uploadFiles
    )
upld.grid(row=7, columnspan=3, pady=10)

ws.mainloop()

The output is a series of labels and buttons but I would like to have the file name populate to the left to each button.
view output here

A: Hey you are almost there. askopenfile gets the filename for you and you can use the name information like in the example below. I used the os package in addition:
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
import time
import os

ws = Tk()
ws.title('Select Input Files')
ws.geometry('400x300')

def open_file():
    file_path = askopenfile(mode='r', filetypes=[('CSV Files', '*.csv')])

    if file_path is not None:
        # this gets the full path of your selected file
        filename = file_path.name
        # this is only selecting the name with file extension
        filename = os.path.basename(filename)
        # to replace your Label you first have to destroy the other label
        up1.destroy()
        # then create a new label with the filename
        file_label = Label(ws, text=filename).grid(row=0, column=0, padx=10)
        # you can even change the title of your tkinter window if you want
        ws.title('Select Input Files -- ' + filename)

up1 = Label(
    ws,
    text='sales_history_document '
    )
up1.grid(row=0, column=0, padx=10)

btn1 = Button(
    ws,
    text ='Choose File',
    command = lambda:open_file()
    )

btn1.grid(row=0, column=1)

up2 = Label(
    ws,
    text='style_group_document '
    )
up2.grid(row=1, column=0, padx=10)

btn2 = Button(
    ws,
    text ='Choose File ',
    command = lambda:open_file()
    )
btn2.grid(row=1, column=1)

ws.mainloop()

A: If you just want to get the filename, use askopenfilename() instead of askopenfile().
You need to pass the label widget to open_file() if you want to show the filename in the label at the left of the button:
...
from tkinter.filedialog import askopenfilename
...
def open_file(lbl):
    file_path = askopenfilename(filetypes=[('CSV Files', '*.csv')])
    if file_path is not None:
        lbl.config(text=file_path)

up1 = Label(
    ws,
    text='sales_history_document '
    )
up1.grid(row=0, column=0, padx=10)

btn1 = Button(
    ws,
    text ='Choose File',
    command = lambda:open_file(up1)
    )
btn1.grid(row=0, column=1)

up2 = Label(
    ws,
    text='style_group_document '
    )
up2.grid(row=1, column=0, padx=10)

btn2 = Button(
    ws,
    text ='Choose File ',
    command = lambda:open_file(up2)
    )
btn2.grid(row=1, column=1)
...


text:
Q: Replication using Datagaurd to FAR DR We have already setup Oracle replication using Dataguard from a primary active site to a near DR site. The near DR is a passive site.
Is it possible to replicate from the Near DR (Passive) site to Far DR site using dataguard?

A: Yes it is possible.
Cascaded Redo Transport Destinations

A cascaded redo transport destination (also known as a terminal
  destination) receives primary database redo indirectly from a standby
  database rather than directly from a primary database.
A physical standby database that cascades primary database redo to one
  or more terminal destinations at the same time it is applying changes
  to its local database files is known as a cascading standby database.

More details at the above URL.


text:
Q: Apps will not open, post OS X Mavericks update I recently upgraded my 2012 Retina MacBook Pro to OS X 10.9 Mavericks and shortly afterwards I updated the iWork apps to their latest version.
After they were all downloaded and installed, I noticed that in my /Applications folder there were, in addition to the newly updated iWork apps, the old iWork '09 apps in a separate folder. I had just assumed that this was just in case you still wanted access to the old iWork apps and so I deleted them.
For the first few hours, the new iWork apps were still working as expected. But, after deleting the old iWork '09 apps, I noticed that I could no longer open the Mac App Store. The icon in my dock just bounces once and then settles, unlike other apps which will bounce a couple of times and start.

*

*I did some digging online but none of the results were recent enough for OS X Mavericks.

*Many forum posts say to delete com.apple.appstore.plist as well as many other files but I can't seem to find any of these files anywhere on my hard drive.

*I have contacted Apple but they want £35/$57 just to handle my support request.

*The next morning, I noticed that the error that had caused the MAS to not open had extended to the iWork apps, as well as many other Apple apps including Calendar, Terminal and Photo Booth.

What I would like to know is how easily could this be fixed? To me, it feels like it would need to a complete fresh re-install of OS X.

A: I'm having the same issue on two of my machines. None of the core apps will launch (Mac App Store, Maps, Message, Photobooth, etc.).
One solution that worked for me for a short period of time:

*

*If you hold Command+R on restart, it activates the recovery partition from which you can reinstall OS X Mavericks.

*Unfortunately the "fix" doesn't last for long and you're either forced to rinse and repeat, or give up entirely.

There doesn't seem to be a genuine fix anywhere online that works for me.

A: This seems to be a strange issue. So I do not have any solutions to fix them as it exists on the system. Before you proceed, ensure that you create a backup (using Time Machine or a disk cloning tool like Clonezilla, Carbon Copy Cloner or SuperDuper!). In case things get worse, you can at least revert to the last known (better) state.
You can do one or both of the following:

*

*You can reinstall OS X yourself. Hold Cmd+R on startup to get into Recovery Mode and select the reinstall OS X Mavericks option.

*If you have a backup with Time Machine from before the upgrade, you can also choose Restore From a Time Machine Backup from the recovery options, select the date/time of that backup and go back to OS X Mountain Lion.

Also see OS X: About OS X Recovery to use Recovery Mode (this is applicable from OS X Lion onwards).

A: Some suggestions (I am using iTunes as an example)…
Try the command file /Applications/iTunes.app/Contents/MacOS/iTunes
/Applications/iTunes.app/Contents/MacOS/iTunes: Mach-O universal binary with 2 architectures
/Applications/iTunes.app/Contents/MacOS/iTunes (for architecture i386): Mach-O executable i386
/Applications/iTunes.app/Contents/MacOS/iTunes (for architecture x86_64):   Mach-O 64-bit executable x86_64
Try the command ls -l /Applications/iTunes.app/Contents/MacOS/iTunes
/Applications/iTunes.app/Contents/MacOS/iTunes
-rwxr-xr-x  1 root  wheel  52680144 Nov  2 03:11 /Applications/iTunes.app/Contents/MacOS/iTunes
Check for any Unix links (using command ls -ld)
Disk Utility allows Repair Disk Permissions as an option.

A: This is a new security propriety on OS X 10.9, to remove it:

*

*Go to System Preferences → Security and Privacy.

*Unlock the preference pane by clicking on the lock icon and entering your password.

*Make sure that Anywhere is selected.

Do note, that this is a bit like leaving your front door unlocked. White listing apps you wish to open rather than turning off all code checks might be a better plan for most people, but you can disable this feature entirely if you wish.


text:
Q: why to update real DOM in Reactjs ,if we get the updates from virtual DOM? why is there need to update real DOM .I mean we get the updation from virtual DOM .so why is it necessary to update real DOM? Please Help.

A: As said in @Lakshya Thakur's comment, the real DOM is the representation of parsed HTML. Updating the real DOM changes the user's screen. React has a virtual DOM to compare the current version with the previous version and update the real DOM.


text:
Q: Centralizer and Normalizer Let be $V\leq \mathrm{Aut}\left( G\right)$, $N\vartriangleleft G$ and $V$-invariant.
Consider the semidirect product $G\rtimes V$.
Let  $X$ be the preimage of $C_{G/N}\left( V\right) =\left\{
gN~;~g^{v}N=gN,\forall v\in V\right\} $ in $G$. Is it true that $X$ normalizes $NV$?

A: Let $g\in X$. If $v\in V$, then we know that $vgv^{-1}N = gN$, so in particular there exists $n\in N$ such that $vgv^{-1}=gn$. Therefore, $vgv^{-1}g^{-1}=gng^{-1} = n'$ for some $n'\in N$ (since $N\triangleleft G$), so $gv^{-1}g^{-1} = v^{-1}n' = (v^{-1}n'v)v^{-1}=n''v^{-1}$ for some $n''\in N$.
Therefore, for every $n\in N$ and $v\in V$ we have
$$g(nv^{-1})g^{-1} = \Bigl(gng^{-1}\Bigr)\Bigl( gv^{-1}g^{-1}\Bigr) = n'''n''v^{-1}\in NV.$$


text:
Q: What is a right pattern for transmitting different changes to a Model to a Child Component? Hi I have a parent component that allows one to select different fields. I'm using nz-zorro's date selector and select components. For example, Date from a date selector, a couple of strings from drop down select fields etc. I've figured that you can use a a Subject event to emit changes to the child components input as and when any of the individual field selectors' callbacks are called.
It seems to me that making an event/input/output for each variable is a repetitive pattern that could be avoided by mapping all these fields I care about to one model.
My question then becomes how do I synchronize changes to any field of a model in one function or in a non code paste way....
var1DateEvent: Subject <Date> = new Subject <Date>();
var2StringEvent: Subject <string> = new Subject <string>();

Instead of having
onvar1Change(){ this.var1DateEvent.next(this.ngModelDate)}
onvar2Change(){ thos.var2StringEvent.next(this.ngModelString)}

Where the model variables are the models mapped to my UI components and onvar1Change() is the callback mapped to that UI element, the child component subscribes to these Input Observable inside its init file.
What I would like to do is have a custom model that has all these changeable fields and whenever any field of the model is changed, the UI emits an event of the entire model to the Child component. This feels like a better pattern to me but I'm not sure how to go about it as I'm new to Angular.

A: If you have a parent child relation in your component there is no need to use the subject observable , i suggest you to use the @Input and @Output, for synchronising the changes in your child component

*

*firstly in your parent component make a variable:

var1DateEvent:any;

*In your html file where you're calling the child component paste this code on:
<your-app-selector-name [var1DateEvent]="var1DateEvent" ></your-app-selector-name

*In your child component place:

@Input() var1DateEvent;

and call the ngOnChanges() :
ngOnChanges(){
console.log('changes from parent component',var1DateEvent);
}

also you need to import Input from :
import { Component, OnInit ,Input } from '@angular/core';
I hope this would help you, Thanks


text:
Q: Where do all methods, attributes get wired into grails controller? I'm looking at grails (2.2), and it's all beautiful and even magical, how it all works. I'm looking at a Controller class which is created with grails create-controller and out of the box it has many methods and properties available, like render(), redirect(), params, request and I presume it goes on and on.
where does all this get wired in? Where in the code/project/framework do I see that render() is made available as a method? And how is it implemented?
As a java developer I'm used to inheritance and code injection and reflection. And in javascript prototypes can do some black magic. But the XXController.groovy is just a standalone object. Is it the name (XXController) or the location (grails-app/controllers?) or is there some injection happening which the IDE can pick up?

A: Welcome to the wonderfull world of Grails,
Here you have a couple of links that may help you:

*

*The Section of Controllers in the Web Layer docs.

*And the docs of the render method. Check it out the "Quick reference" column at the right for more methods avaliable at the Controllers.

If you are wondering how that magic is done, Grails is an open source project, so as usual, go and serve yourself at Github (warning, it is quite large project).
Grails works on the top of Groovy, which is a Dynamic Language with a powerful support of meta programming. Tha is basically the trick of all the magic of Grails
Finally, Grails is a framework based on CoC (Convection over configuration), So the Controllers will be any class under the directory "grails-app/controllers" and with the suffix "Controller". (In the folder of controllers may be "commandObjects as well).
The integration with well-know ides is quite powerful as well, you should check it out
EDIT
You may also found how the render methods behaves here at github.
And more inyected stuff at the Controllers metaClass package

A: As of Grails 2.0+ it's implemented using an AST transformation - previously it was done by adding the methods to the Groovy MetaClass. The benefits of the new approach are that things will be a bit faster and use less memory.
GORM domain class methods now use this approach too (except for dynamic methods like findByFooAndBar which have to be added dynamically to the metaclass) and those have the benefit of being callable from Java since the AST adds the methods to the bytecode. This doesn't help controllers though since they're only called from Grails itself as the result of a web request.
For the gory details, ControllersApi is where the methods are, and they're mixed into each controller class by a combination of ControllerTransformer and the code in the doWithDynamicMethods closure in ControllersGrailsPlugin


text:
Q: How to recover key and iv for files encrypted by OpenSSL using 3DES encryption? I know there are some answers for similar question, but those seems for AES encryption only, and I got different result when I use python for key derivation.
Now I have passphrase and the salt (from encrypted file by OpenSSL previously using 3DES). I can simply calculate the key and iv by OpenSSL, but I want to implement the key derivation into my python.
This is from OpenSSL output and I believe I should get the same result after key derivation using python:
# openssl enc -des3 -pass pass:cfe4ec9fcec928d51d243855a094b05ebb7bc870 -S 3AA6A64F87764632 -P
salt=3AA6A64F87764632
key=6A8E552A81763B15EC9E1430FAB774C7B5113AFD89E6F03C
iv =DE2CFC91DC61E734

I used this code into my python:
...
print("password is", password.hexdigest())
...
D1=hashlib.md5(password.digest() + openssl_salt).digest()
D2=hashlib.md5(D1 + password.digest() + openssl_salt).digest()
D3=hashlib.md5(D2 + password.digest() + openssl_salt).digest()
key=D1+D2
iv=D3
print ('salt:', openssl_salt.hex())
print ('key:', key.hex())
print ('iv:', iv.hex())

and here's my result, it's obviously different and the key/iv length is also wrong:
password is cfe4ec9fcec928d51d243855a094b05ebb7bc870
...
salt: 3aa6a64f87764632
key: 49096a6dca92f70c88e92a9d67062b8ae70223e432e23a4ee9abd3531d35e1aa
iv: 964f7299c4b960a1264863a23fbbf20b

I think maybe those codes are for AES key derivation, not for 3DES. Could anyone advise?

A: Looking at this post and the documentation for the KDF used by openssl enc, it seems you are quite close to the solution.

*

*The password cfe... is just encoded to bytes as ASCII text, not as a hex string.

*The key is 24 bytes, the IV is 8, and the MD5 digest is 16, so we only need two rounds.

Putting it together:
>>> password = 'cfe4ec9fcec928d51d243855a094b05ebb7bc870'.encode()
>>> salt = bytes.fromhex('3AA6A64F87764632')
>>> d1 = hashlib.md5(password+salt)
>>> d2 = hashlib.md5(d1.digest()+password+salt)
>>> keymatter = d1.digest() + d2.digest()
>>> key = keymatter[:24].hex().upper()
>>> iv = keymatter[24:32].hex().upper()
>>> print(f'key: {key}\nIV:  {iv}')
key: 6A8E552A81763B15EC9E1430FAB774C7B5113AFD89E6F03C
IV:  DE2CFC91DC61E734

A: If you like a pure Python solution without external library use the method provided by Tom Tang on his GitHub Gist https://gist.github.com/tly1980/b6c2cc10bb35cb4446fb6ccf5ee5efbc.
An output would be:
SO derive key and iv from passphrase like OpenSSL for 3DES
password: cfe4ec9fcec928d51d243855a094b05ebb7bc870
salt (hex) length: 8  data: 3aa6a64f87764632
key (hex) length:  24 data: 6a8e552a81763b15ec9e1430fab774c7b5113afd89e6f03c
iv (hex) length:   8  data: de2cfc91dc61e734

Full source code:
# source get_key_and_iv by Tom Tang
# https://gist.github.com/tly1980/b6c2cc10bb35cb4446fb6ccf5ee5efbc

# ================================================================
# get_key_and_iv
# ================================================================
def get_key_and_iv(password, salt, klen=32, ilen=16, msgdgst='md5'):
    '''
    Derive the key and the IV from the given password and salt.

    This is a niftier implementation than my direct transliteration of
    the C++ code although I modified to support different digests.

    CITATION: http://stackoverflow.com/questions/13907841/implement-openssl-aes-encryption-in-python

    @param password  The password to use as the seed.
    @param salt      The salt.
    @param klen      The key length.
    @param ilen      The initialization vector length.
    @param msgdgst   The message digest algorithm to use.
    '''
    # equivalent to:
    #   from hashlib import <mdi> as mdf
    #   from hashlib import md5 as mdf
    #   from hashlib import sha512 as mdf
    mdf = getattr(__import__('hashlib', fromlist=[msgdgst]), msgdgst)
    password = password.encode('ascii', 'ignore')  # convert to ASCII

    try:
        maxlen = klen + ilen
        keyiv = mdf(password + salt).digest()
        tmp = [keyiv]
        while len(tmp) < maxlen:
            tmp.append( mdf(tmp[-1] + password + salt).digest() )
            keyiv += tmp[-1]  # append the last byte
        key = keyiv[:klen]
        iv = keyiv[klen:klen+ilen]
        return key, iv
    except UnicodeDecodeError:
        return None, None

def bytesToHex(input):
  return input.hex()

print("SO derive key and iv from passphrase like OpenSSL for 3DES")
password = 'cfe4ec9fcec928d51d243855a094b05ebb7bc870'
salt = bytes.fromhex('3AA6A64F87764632')
key, iv = get_key_and_iv(password, salt, 24, 8)
print("password: " + password)
print("salt (hex) length: " + str(len(salt)) + "  data: " + bytesToHex(salt))
print("key (hex) length:  " + str(len(key)) + " data: " + bytesToHex(key))
print("iv (hex) length:   " + str(len(iv)) + "  data: " + bytesToHex(iv))


text:
Q: How to iterate over Future object? The return value of my call() method List<Person>. MyCallable class looks like this:
public class MyCallable implements Callable<List<Person>> {

    public List<Person> call() throws Exception {

           ...

           return list;
    }

    public MyCallable(List<Account> accountList) {
        super();
    }
}

Below is the code I'm writing in my CallableFuture class:
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
List<Future<List<Person>>> list = new ArrayList<Future<List<Person>>>();
for (int i = 0; i < 20; i++) {
    Callable<List<Person>> worker = new MyCallable(accountList);
    Future<List<Person>> submit = executor.submit(worker);
    for(Future<List<Person>> :list){
        //list.add(submit);
    }
}

I don't know how to iterate over list and add submit to it. Am i doing this right?

A: Couple of problems. First of all, rather than attempting to grab the results of the Future immediately after submitting each one (if you do this you're essentially just serializing everything and defeating the purpose), submit all of them, and then retrieve the results:
List<Future<List<Person>>> list = new ArrayList<Future<List<Person>>>();
for (int i = 0; i < 20; i++) {
    Callable<List<Person>> worker = new MyCallable(accountList);
    Future<List<Person>> submit = executor.submit(worker);
    list.add(submit); // just keep track of them
}

// NOW the next step is to get the results...

Next, you're having some basic syntax problems. In general to iterate over the items in a container the syntax is:
List<A> list = ...;

for (A a : list) {
   // do things with 'a'
}

And finally, you need to check the docs for Future, which show you how to wait for it to be computed and obtain the results by using Future#get().
Putting this all together you end up with the next step (after submitting everything as above) being:
// ... all tasks submitted and 'list' now contains the Futures, next step:

for (Future<List<Person>> future : list) {
    List<Person> result = future.get(); // wait for task to complete
    // 'result' is now the List<Person> returned from the corresponding callable.
}

The idea behind submitting everything then getting all the results is you now allow your tasks to execute concurrently instead of waiting for each one to complete before adding the next. Then, at the end, even if you end up waiting on a few, it's OK, because the total wait time for all tasks has been reduced as intended.


text:
Q: Vuetify password validation to include special characters, capital letter, number and min length 6 character I am trying to add password rules in my vue app. I am using vuetify version 2.3.10.
This is what I have so far, and I am not able to figure out how can I add the validation for password to include special characters, capital letter and number.
passwordRules: [
 value => !!value || 'Please enter a password',
 (value) => !!value || 'Please type password.',
 (value) => (value && value.length >= 6) || 'minimum 6 characters',
]

Help me resolve this issue.

A: Useful topic:
https://stackoverflow.com/a/21456918/7158959
passwordRules: [
 value => !!value || 'Please enter a password',
 (value) => !!value || 'Please type password.',
 (value) => (value && /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/.test(value)) || 'Minimum 6 characters, One capital latter, Special charater, Number',
]

console.log(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/.test("hEse%9"))

As requested to brake it down:
passwordRules: [
 value => !!value || 'Please enter a password',
 (value) => !!value || 'Please type password.',
 (value) => (value && /\d/.test(value)) || 'At least one digit',
 (value) => (value && /[A-Z]{1}/.test(value)) || 'At least one capital latter',
 (value) => (value && /[^A-Za-z0-9]/.test(value)) || 'At least one special character',
 (value) => (value && value.length < 6 ) || 'minimum 6 characters',
]

console.log(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/.test("hEse%9"))

console.log(/\d/.test("hE4se%")) // digit
console.log(/[A-Z]{1}/.test("hE4se%")) // Capital latter
console.log(/[^A-Za-z0-9]/.test("hE#4se")) // Special character

Also your length needs to be checked with < 6 I believe.


text:
Q: Why does my data binding see the real value instead of the coerced value? I'm writing a real NumericUpDown/Spinner control as an exercise to learn custom control authoring.  I've got most of the behavior that I'm looking for, including appropriate coercion.  One of my tests has revealed a flaw, however.
My control has 3 dependency properties: Value, MaximumValue, and MinimumValue.  I use coercion to ensure that Value remains between the min and max, inclusive.  E.g.:
// In NumericUpDown.cs

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register("Value", typeof(int), typeof(NumericUpDown),
    new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal, HandleValueChanged, HandleCoerceValue));

[Localizability(LocalizationCategory.Text)]
public int Value
{
    get { return (int)this.GetValue(ValueProperty); }
    set { this.SetCurrentValue(ValueProperty, value); }
}

private static object HandleCoerceValue(DependencyObject d, object baseValue)
{
    NumericUpDown o = (NumericUpDown)d;
    var v = (int)baseValue;

    if (v < o.MinimumValue) v = o.MinimumValue;
    if (v > o.MaximumValue) v = o.MaximumValue;

    return v;
}

My test is just to ensure that data binding works how I expect.  I created a default wpf windows application and threw in the following xaml:
<Window x:Class="WpfApplication.MainWindow" x:Name="This"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:nud="clr-namespace:WpfCustomControlLibrary;assembly=WpfCustomControlLibrary"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <nud:NumericUpDown Value="{Binding ElementName=This, Path=NumberValue}"/>
        <TextBox Grid.Row="1" Text="{Binding ElementName=This, Path=NumberValue, Mode=OneWay}" />
    </Grid>
</Window>

with very simple codebehind:
public partial class MainWindow : Window
{
    public int NumberValue
    {
        get { return (int)GetValue(NumberValueProperty); }
        set { SetCurrentValue(NumberValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for NumberValue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty NumberValueProperty =
        DependencyProperty.Register("NumberValue", typeof(int), typeof(MainWindow), new UIPropertyMetadata(0));

    public MainWindow()
    {
        InitializeComponent();
    }
}

(I'm omitting the xaml for the control's presentation)
Now if I run this I see the value from the NumericUpDown reflected appropriately in the textbox, but if I type in a value that's out of range the out of range value gets displayed in the test textbox while the NumericUpDown shows the correct value.
Is this how coerced values are supposed to act?  It's good that it's coerced in the ui, but I expected the coerced value to run through the databinding as well.

A: A new answer for an old question: :-)
In the registration of the ValueProperty an FrameworkPropertyMetadata instance is used. Set the UpdateSourceTrigger property of this instance to Explicit. This can be done in a constructor overload.
public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register("Value", typeof(int), typeof(NumericUpDown),
    new FrameworkPropertyMetadata(
      0,
      FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal,
      HandleValueChanged,
      HandleCoerceValue,
      false
      UpdateSourceTrigger.Explicit));

Now the binding source of the ValueProperty will not be updated automatically on PropertyChanged.
Do the update manually in your HandleValueChanged method (see code above).
This method is called only on 'real' changes of the property AFTER the coerce method has been called.
You can do it this way:
static void HandleValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
    NumericUpDown nud = obj as NumericUpDown;
    if (nud == null)
        return;

    BindingExpression be = nud.GetBindingExpression(NumericUpDown.ValueProperty);
    if(be != null)
        be.UpdateSource();
}

In this way you can avoid to update your bindings with non-coerced values of your DependencyProperty.

A: Wow, that is surprising.  When you set a value on a dependency property, binding expressions are updated before value coercion runs!
If you look at DependencyObject.SetValueCommon in Reflector, you can see the call to Expression.SetValue halfway through the method.  The call to UpdateEffectiveValue that will invoke your CoerceValueCallback is at the very end, after the binding has already been updated.
You can see this on framework classes as well.  From a new WPF application, add the following XAML:
<StackPanel>
    <Slider Name="Slider" Minimum="10" Maximum="20" Value="{Binding Value,
        RelativeSource={RelativeSource AncestorType=Window}}"/>
    <Button Click="SetInvalid_Click">Set Invalid</Button>
</StackPanel>

and the following code:
private void SetInvalid_Click(object sender, RoutedEventArgs e)
{
    var before = this.Value;
    var sliderBefore = Slider.Value;
    Slider.Value = -1;
    var after = this.Value;
    var sliderAfter = Slider.Value;
    MessageBox.Show(string.Format("Value changed from {0} to {1}; " +
        "Slider changed from {2} to {3}",
        before, after, sliderBefore, sliderAfter));
}

public int Value { get; set; }

If you drag the Slider and then click the button, you'll get a message like "Value changed from 11 to -1; Slider changed from 11 to 10".

A: You are coercing v which is an int and as such a value type. It is therefore stored on the stack. It is in no way connected to baseValue. So changing v will not change baseValue.
The same logic applies to baseValue. It is passed by value (not by reference) so changing it will not change the actual parameter.
v is returned and is clearly used to update the UI.
You may want to investigate changing the properties data type to a reference type. Then it will be passed by reference and any changes made will reflect back to source. Assuming the databinding process does not create a copy.


text:
Q: Finding Sum of values of a particular group in Table I have two tables in MySQL. The first one is Catalog with one of its columns as Category, and another table Stock with SP and CP as columns. I want to find the total profit of each category.
I am not able to come up with an appropriate query. Every query I try gives an error. Can anyone help?
select A.Category,sum(B.SP group by A.Category) as TotalSP,sum(B.CP group by A.Category) as TotalCP,
case
when TotalSP>TotalCP then ((TotalSP-TotalCP)/TotalSP)*100
when TotalSP<TotalCP then ((TotalSP-TotalCP)/TotalCP)*100
end
as TotalProfit
from Catalog A,Stock B;

Note: negative profit automatically considered as loss.

A: select A.Category,sum(B.SP) as TotalSP,sum(B.CP) as TotalCP,
case
when TotalSP>TotalCP then ((TotalSP-TotalCP)/TotalSP)*100
when TotalSP<TotalCP then ((TotalSP-TotalCP)/TotalCP)*100
end
as TotalProfit
from Catalog A
INNER JOIN Stock B ON B.catalog_id = A.id/*Write how your tables linked here*/
group by A.Category;

This query selects all catalog records, joins stock data to it, then groups results by category, counts sums in each group.


text:
Q: bootstrap table-responsive not working on firefox mobile I add table-responsive class to wrapper div of table and it work fine in all browsers except Firefox for mobile(android at least) and scroller not shown any idea?
p.s. I visit other questions in site but my table is normal table without fieldset or other thing that mentioned in other questions.
Here is my code:

                foo
                foo
                foo
                foo
                foo
                foo

                    foo
                    till

                    foo

                200
                50%
                100
                100

                      foo

A: @Mohsenkw can you please jsfiddle your code and send the link here ?
I will possibly fix it.
Thanks :)


text:
Q: how can i use require(""); in javascript i want to use a plugin in Firefox that it is in this. in this plugin tutorial use require function, and it is: require("sdk/preferences/service");
but i get error that require is not defined. so i search and download requireJS. but when attach this i get error module name sdk/preference/service has not been loaded yet from context. use require([]).
so i use require(["sdk/preferences/service"],function(pref){}); but in function i can't use pref and get error script error sdk/preferences/service
so how can i use require function?
or a HTML example that use require function and it works correctly?

A: The code you found was for use in a Firefox extension. You're not writing a Firefox extension, you're using a web page, so you can't use that code. There's no drop-in replacement; you'll have to find something else.


text:
Q: How many intersections of two functions with the same monotonicity? For example, consider two functions monotonically increasing (when they have at least one intersection) in a particular interval,how many intersections do they have? Which factor may influence the number of intersection?
What if I add the condition that one's value includes the other's?
Meanwhile, I also wonder if there's a rule to determine whether two monotonically increasing functions with one's value including the other have only 1 intersection points?
Does this related to derivatives or concavity, or there just don't have a rule?


text:
Q: How to assign all table properties of table1 to table2 using Novacode DocX? After creating table2 and inserting it after table1, how would u give table2 properties of another table that exists in the document? Properties I am speaking of include Keep with next, Keep lines together, Allow rows to break across pages, etc..
Novacode.Table table1 = template.Tables[index];
Novacode.Table table2 = table1.InsertTableAfterSelf(1, 2);
//table2.properties = table1.properties

A: I'm still a novice myself at Novacode-DocX, but I believe you can do an assignment like this
 table2.Design = table1.Design;

This code is able to compile, but I have not tested it's results thoroughly.
You can do a lot of assignments like that, it's not the best, but it depends on what your needs are. A great place for DocX questions is the discussion board. You can find a number of posts with custom code modifications to the .dll file that might suit future needs.
A useful tool to have when using the DocX code library, is the help documentation text. Unfortunately, it hasn't been updated in some time, but you can still download an older version which has many of the functions defined from here
Hopefully this gets you going
Have an awesome day, and be well!


text:
Q: Avoiding repetitive "content_for" in views I have a submenu placed in my layout wich differs from controller to controller, but not between each controllers method views. What I am currently doing is the following:
<% content_for( :submenu ) do %>
    <%= render :partial => 'submenus/correct_submenu' %>
<% end %>

In every view for a method
My applications layout then has this in it
<%= yield :submenu %>

However, this feels kind of repetitive, doing it for each view. Is there some way to do this per controller?

A: My suggest is to have a convention for this, so if you have a ProductsController then the submenu would be submenus/products_menu.  This way you can write a helper that looks like:
def render_submenu
  content_for(:submenu) { render :partial => "submenus/#{controller.controller_name}_menu" }
end

You can then call this by doing:
<%= render_submenu %>

You could then make this the default content_for the submenus and only specify the content if it needs to be different.
I hope this helps!

A: Use nested layouts to nest a specific controller's layout under the application layout, by creating a file like so:
# app/view/layouts/<controller_name>.html.erb
<% content_for( :submenu ) do %>
  <%= render :partial => 'submenus/correct_submenu' %>
<% end %>
<%= render template: "layouts/application" %>

With this method, you don't have to modify a bunch of view files.


text:
Q: PHP include pathing problems I know this question has been asked plenty of times, or at least related questions, but I just can't seem to figure it out. I haven't done too much PHP programming, I'm just trying to keep a simple template across all of the website I'm working on.
Basically there is a sidebar,banner,footer.php. I just do
<?php include('includes/banner.php'); ?>

That is when you're in the root folder - in index.php.
Inside banner.php is:

That works fine and dandy for all the .php's in the root directory.
Now when I go to say directory A then to B I have another example.php ( So A/B/example.php ). Now if I try to use
<?php include('../../includes/banner.php'); ?>

It of course has the wrong path to the images. Since the code above is just pasted into the example.php with the image path of images/../banner.jpg. When it should be ../../images/../banner.jpg
How do I go about changing it so no matter how many directories deep I go, the banner image path is correct?
Just as FYI, I'm actually updating an old site for a friend. The layout of all the files and such ( and code, ugh ) are rather messy. So that's why I've been trying to clean it all up and make it a bit more organized and easier to update.
Thanks for help

A: This is the simple idea use in Joomla / Wordpress / Cakephp & other open source.
Use:
require( dirname( __ FILE __ ).'/images/imagename.jpg');
Let me know if this works.
Thanks,
Munjal