text:
Q: List to Dictionary: Even items as keys, odd items as values I am trying to use Python to convert a list into a dictionary and I need to help coming up with a simple solution.  The list that I would like to convert looks like this:
inv = ['apples', 2, 'oranges', 3, 'limes', 10, 'bananas', 7, 'grapes', 4]

I want to create a dictionary from this list, where the items in the even positions (apples, oranges, limes, bananas, grapes) are the keys, and the items in the odd positions (2, 3, 10, 7, 4) are the values.
inv_dict = {'apples':2, 'oranges':3, 'limes':10, 'bananas':7, 'grapes':4}

I've tried using something like enumerate to count the position of the item, and then if it's even, set it as a key.  But then I'm not sure how to match the following number up with it's correct item.

A: Shortest way:
dict(zip(inv[::2], inv[1::2]))

A: Another option using zip:
dict([(x, y) for x, y in zip(inv[::2], inv[1::2])])
# {'apples': 2, 'bananas': 7, 'grapes': 4, 'limes': 10, 'oranges': 3}

Or as @DSM suggested:
dict(zip(inv[::2], inv[1::2]))
# {'apples': 2, 'bananas': 7, 'grapes': 4, 'limes': 10, 'oranges': 3}

A: The key is to use the pairwise iteration and call dict() constructor on the resulting list of pairs, which would create a dictionary using first items as keys and second as values:

Each item in the iterable must itself be an iterable with exactly two
objects. The first object of each item becomes a key in the new
dictionary, and the second object the corresponding value.

Sample:
>>> inv = ['apples', 2, 'oranges', 3, 'limes', 10, 'bananas', 7, 'grapes', 4]
>>> dict(pairwise(inv))
{'grapes': 4, 'bananas': 7, 'apples': 2, 'oranges': 3, 'limes': 10}

where pairwise() function is taken from this answer:
from itertools import izip

def pairwise(iterable):
    a = iter(iterable)
    return izip(a, a)

Python3 version:
def pairwise(iterable):
    a = iter(iterable)
    return zip(a, a)


text:
Q: Is it wrong to refer to results as "nearly" or "somewhat" significant? The general consensus on a similar question, Is it wrong to refer to results as being "highly significant"? is that "highly significant" is a valid, though non-specific, way to describe the strength of an association that has a p-value far below your pre-set significance threshold. However, what about describing p-values that are slightly above your threshold? I have seen some papers use terms like "somewhat significant", "nearly significant", "approaching significance", and so on. I find these terms to be a little wishy-washy, in some cases a borderline disingenuous way to pull a meaningful result out of a study with negative results. Are these terms acceptable to describe results that "just miss" your p-value cutoff?

A: From my perspective, the issue boils down to what it actually means to carry out a significance test. Significance testing was devised as a means of making the decision of either to reject the null hypothesis or to fail to reject it. Fisher himself introduced the infamous 0.05 rule for making that (arbitrary) decision.
Basically, the logic of significance testing is that the user has to specify an alpha level for rejecting the null hypothesis (conventionally 0.05) before collecting the data. After completing the significance test, the user rejects the null if the p value is smaller than the alpha level (or fails to reject it otherwise).
The reason why you cannot declare an effect to be highly significant (say, at the 0.001 level) is because you cannot find stronger evidence than you set out to find. So, if you set your alpha level at 0.05 before the test, you can only find evidence at the 0.05 level, regardless of how small your p values is. In the same way, speaking of effects that are "somewhat significant" or "approaching significance" also doesn't make much sense because you chose this arbitrary criterion of 0.05. If you interpret the logic of significance testing very literally, anything bigger than 0.05 is not significant.
I agree that terms like "approaching significance" are often used to enhance the prospects of publication. However, I do not think that authors can be blamed for that because the current publication culture in some sciences still heavily relies on the "holy grail" of 0.05.
Some of these issues are discussed in:
Gigerenzer, G. (2004). Mindless statistics. The Journal of Socio-Economics, 33(5), 587-606.
Royall, R. (1997). Statistical evidence: a likelihood paradigm (Vol. 71). CRC press.

A: The difference between two p-values itself typically is not significant. So, it doesn't matter whether your p-value is 0.05, 0.049, 0.051...
With regards to p-values as  a measure of strength of association: A p-value is not directly a measure of strength of association. A p-value is the probability of finding as extreme or more extreme data as the data you have observed, given the parameter is hypothesized to be 0 (if one's interested in the null hypothesis -- see Nick Cox' comment). However, this is often not the quantity the researcher is interested in. Many researchers are rather interested in answering questions like "what's the probability of the parameter to be greater than some chosen cut-off value?" If this is what you're interested in, you need to incorporate additional prior information in your model.

A: This slippery slope calls back to the Fisher vs Neyman/Pearson framework for null-hypothesis significance testing (NHST). On the one hand, one wants to make a quantitative assessment of just how unlikely a result is under the null hypothesis (e.g., effect sizes).  On the other hand, at the end of the day you want a discrete decision as to whether your results are, or are not, likely to have been due to chance alone. What we've ended up with is a kind of hybrid approach that isn't very satisfying.
In most disciplines, the conventional p for significance is set at 0.05, but there is really no grounding for why this must be so.  When I review a paper, I have absolutely no problem with an author calling 0.06 significant, or even 0.07, provided that the methodology is sound, and the entire picture, including all analyses, figures, etc. tell a consistent and believable story.  Where you run into problems is when authors attempt to make a story out of trivial data with small effect sizes. Conversely, I might not fully 'believe' a test is practically meaningful even when it reaches conventional p < 0.05 significance. A colleague of mine once said: "Your statistics should simply back up what is already apparent in your figures."
That all said, I think Vasilev is correct.  Given the broken publication system, you pretty much have to include p values, and therefore you pretty much have to use the word 'significant' to be taken seriously, even if it requires adjectives like "marginally" (which I prefer). You can always fight it out in peer review, but you have to get there first.

A: Whether "nearly significant" makes sense or not depends on one's philosophy of statistical inference.  It's perfectly valid to consider the alpha level as a line in the sand, in which case one should only pay attention to whether $p<\alpha$ or $p>\alpha$.  For such an "absolutist", "nearly significant" makes no sense.  But it's also perfectly valid to think of p values as providing continuous measures of strength of support (not strength of effect, of course).  For such a "continualist", "nearly significant" is a sensible way to describe a result with a moderate p-value.  The problem arises when people mix these two philosophies - or worse, are not aware that both exist.  (By the way - people often assume these map cleanly onto Neyman/Pearson and Fisher, but they don't; hence my admittedly clumsy terms for them).  More detail about this in a blog post on this subject here: https://scientistseessquirrel.wordpress.com/2015/11/16/is-nearly-significant-ridiculous/

A: If you want to allow "significance" to admit of degrees then fair enough ("somewhat significant", "fairly significant"), but avoid phrases that suggest you're still wedded to the idea of a threshold, such as "nearly significant", "approaching significance", or "at the cusp of significance" (my favourite from "Still Not Significant" on the blog Probable Error), if you don't want to appear desperate.

A: I tend to think saying something is almost statistically significant is not correct from a technical standpoint. Once you set your tolerance level the statistical test of significance is set. You have to go back to the idea of sampling distributions. If your tolerance level is say 0.05 and you happen to get a p-value of 0.053 then it is just by chance that the sample used yielded that statistic. You could very well get another sample that may not yield the same results- I believe the probability of that occurring is based on the tolerance level set and not on the sample statistic. Remember that you are testing samples against a population parameter and samples have their own sampling distribution. So in my opinion, either something is statistically significant or it is not.

A: The p-value is uniformly distributed on $[0,1]$ under $\mathcal{H}_0$ so getting a result with a p-value of 0.051 is as likely as getting a result with a p-value of 1. Since you have to set the significance level before getting data you reject the null for every p-value $p > \alpha$. Since you don't reject your null, you have to assume a uniformly distributed p-value, a higher or lower value is essentially meaningless.
This is a wholly different story when you reject the null, since the p-value is not uniformly distributed under $\mathcal{H}_1$ but the distribution depends on the parameter.
See for example Wikipedia.

redpajama_set_name: RedPajamaStackExchange


text:
Q: work with PHP_SELF It give me this error :  Undefined index: action in  LINE  :  $act=$_POST['action'];
<?php
 function_2()
    {

    ?>
 <FORM name="poll" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
      <input type="hidden" name="action" value="insert">
      .
      .
      .

</FORM>

<?php
        }
    $act=$_POST['action'];
    switch($act)
    {
        case "insert":

            function_1();
            break;
        default:
            fuction_2();
            break;
    }
?>

please help me about it.

A: That error is saying that $_POST['action'] doesn't exist. So, you will need a conditional statement to set that value of $act.
// Set Default
$act = '';
if ( isset($_POST['action'])) ) {
    $act = $_POST['action'];
}

switch($act)
{
    case "insert":

        function_1();
        break;
    default:
        fuction_2();
        break;
}


text:
Q: Is it possible to access a Mac via SSH without administrator access? I want to be able to SSH into my Mac, but it's disabled in System Preferences (Sharing --> Remote Connections, I believe). The administrator disabled this, and I'm looking for a way to re-enable it without an admin password. Is there a way I can re-install SSH to enable it, or something along those lines?

A: Not easily and you may be running afoul of policy if you are circumventing the access policies of a computer to which you are not supposed to be modifying the security stance.
If you were to run sshd in your user space, you will need to use a port higher than 1024 and also hope that the firewall and network will allow you to accept inbound traffic on the port you chose.
Here is a decent article on how you would do this with admin permissions. It's not a perfect fit for Mac OS - but should give you a feel for what the issues are in your quest to set up sshd.
Also, netcat.

A: It's possible:
User:
dseditgroup -o edit -n /Local/Default -u localadmin -p -a username -t user com.apple.access_ssh

Group:
dseditgroup -o edit -n /Local/Default -u localadmin -p -a groupname -t group com.apple.access_ssh

Make sure to insert your local admin's short name (localadmin) and the user (username) or group (groupname) you're trying to add.


text:
Q: Do cauldrons catch rainwater? I can't remember when or where I saw it, but at one point I remember being able to fill a cauldron with rainwater.
Is this possible in Vanilla Minecraft?

A: To quote the Minecraft wiki:

A cauldron slowly fills with water when rained upon, if starting empty or with some water. This happens randomly, at 5% of the rate in which snow accumulates on the ground during snowfall.

Yes, it has a chance to fill it. In fact someone even built a machine that fills them when it rains and I suspect you could use them as a type of rain detector with a comparator.

A: Cauldrons do collect rainwater, however, it is only by chance.

A cauldron also has a chance to fill up with water when rained upon.

According to the Minecraft Wiki.


text:
Q: .htaccess rewrite rule for several parameters I have found some usefull links but I can't figure out why isn't working.
Current url:
http://localhost/noyk/clients/clients.php?name=StackOverflow&category=technology

The final url I would like it to be:
http://localhost/noyk/clients/StackOverflow/technology

I have found this topic, and I've tried to adapt.
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([^/]+)/([^/]+)/?$ index.php?name=$1&category=$2 [L,QSA]
RewriteRule ^([^/]+)/?$ index.php?name=$1 [L,QSA]

If you guys tell me that this should work it does not.
When I type in the url http://localhost/noyk/clients/StackOverflow I receive the default XAMPP page error:
The requested URL /noyk/clients/StackOverFlow was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

A: I'm guessing your .htaccess file is in your site root? If so, either move to /noyk/clients/ or edit as follows:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^noyk/clients/([^/]+)/([^/]+)/?$ index.php?name=$1&category=$2 [L,QSA]
RewriteRule ^noyk/clients/([^/]+)/?$ index.php?name=$1 [L,QSA]


text:
Q: pointer already defined in file I have this piece of code that works as expected when all of it is in a single file
The problem is i need the platform to have a static pointer to the engine and vice versa
#include <iostream>

#pragma region include/iplatform.h
namespace engine {
    class IEngine;
}

namespace platform {
    class IPlatform {
    public:
        virtual ~IPlatform() = default;
        static engine::IEngine* ptrEngine;
    };

    static std::unique_ptr<IPlatform> platform;
    engine::IEngine* platform::IPlatform::ptrEngine = nullptr;
}
#pragma endregion

#pragma region include/iengine.h
namespace engine {
    class IEngine {

    };
}
#pragma endregion

#pragma region include/engine.h
namespace engine {
    class Engine : public IEngine {
    public:
        Engine();
        void setup();
    };
}
#pragma endregion

#pragma region src/enginge.cpp
namespace engine {
    Engine::Engine() { setup(); }

}
#pragma endregion

#pragma region include/platform.h
namespace platform {
    class Platform : public platform::IPlatform{
    public:
        virtual ~Platform() override;
    };
}
#pragma endregion

#pragma region src/platform.cpp
namespace platform {
    Platform::~Platform() {

    }
}
#pragma endregion

#pragma region src/engine.cpp
namespace engine {
    void Engine::setup() {
        platform::platform = std::make_unique<platform::Platform>();
        platform::platform->ptrEngine = this;
    }
}
#pragma endregion

int main() {
    engine::Engine* e = new engine::Engine();

    std::cout << "" << e << std::endl;
    std::cout << "" << platform::platform->ptrEngine;

    return 0;
}

but once i separate it out into files as outlined by the region blocks i start getting errors, the project structure requires us to have headers and source separately
Severity    Code    Description Project File    Line    Suppression State
Warning C6031   Return value ignored: 'std::unique_ptr<platform::IPlatform,std::default_delete<platform::IPlatform> >::->'. CPP_BOILERPLATE C:\Users\Tiit\Documents\cpp\cpp-project-masters\app\main.cpp    74
Warning C6031   Return value ignored: 'std::unique_ptr<platform::IPlatform,std::default_delete<platform::IPlatform> >::->'. CPP_BOILERPLATE C:\Users\Tiit\Documents\cpp\cpp-project-masters\app\main.cpp    83
Warning D9025   overriding '/W3' with '/W4' C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cpp-project-masters C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cl  1
Warning D9025   overriding '/W3' with '/W4' C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cpp-project-masters C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cl  1
Error   LNK2005 "public: static class engine::IEngine * platform::IPlatform::ptrEngine" (?ptrEngine@IPlatform@platform@@2PEAVIEngine@engine@@EA) already defined in engine.cpp.obj  C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cpp-project-masters C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\platform.cpp.obj    1
Error   LNK1169 one or more multiply defined symbols found  C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cpp-project-masters C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\main.exe    1

is there a way to do this

A: The solution as @wohlstad commented was moving the line
engine::IEngine* platform::IPlatform::ptrEngine = nullptr;

to one of the source files


text:
Q: RangeAttribute with Enum I have the following Enum:
public enum ApplicationLogTypes
    {
        Undefined = 0,
        Information = 100,
        Statistic = 200,
        Debug = 300,
        Security = 400,
        Error = 500
    }

I have a property with RangeAttribute Validation to enforce the user has not selected the default option "Undefined":
[Range(1, int.MaxValue, ErrorMessage = "Cannot select default option.")]
public ApplicationLogTypes ApplicationLogType { get; set; }

But when I use the Validator, it passes:
public bool IsValid(ICollection<ValidationResult> results)
{
  bool isValid;
  ValidationContext validationContext = new ValidationContext(this);

  isValid = Validator.TryValidateObject(this, validationContext, results);

  return isValid;
}

Other validation using this method properly fails validation using other attributes such as Required.
Any suggestions?

A: Try this:
 isValid = Validator.TryValidateObject(this, validationContext, results, true);

There is no problem with enums, you just miss the last parameter - validateAllProperties
    Type: System.Boolean
    true to validate all properties; if false, only required attributes are validated.

A: Workaround advice: Remove the Undefined enumeration value. Use nullable enum type and null value for an unknown value instead. Then you can use the required validator.
Possible cause: Your value type is an enum, but you specify integer ranges. Try specifying enum values as min/max or using RangeAttribute.OperandType.


text:
Q: Class scope variabile visibility If I have:
class A
{
   void foo()
   {
      int a = count;
   }

   void bar()
   {
      int a = c; // here ERROR
      int c = 10;
   }

   private int count = 10;

}

here in foo count is used without problem also if it's declared after the use.
The same is not true in method bar where the variable c must be declared before its
use.
Which are the class scope rules? How they differs from method scope rules?
P.S.
My doubt is because the common scope resolutions rules:
When the compiler find count it should try to find it "back" to its
use but back there is Class A... so maybe private int count is "hoisting" at
beginning of Class A?

A: Imagine that you were a compiler, and you get to the line:
int a = c;

Won't you get angry and ask yourself "What is c"? The order is important1.
1count doesn't make a problem because it's a class member, it's known in the whole class. You can place class members in the beginning of the class, or at the end.

A: count is declared in the class while c is declared in the method
While compiling, the class would find count in the class.
class A
{
   void foo()
   {
      int a = count;
   }
   private int count = 10;
}

is equal to put count anywhere in the class, as it is a class member and can be found in the class everywhere.
while in your case of
class A
{
   void bar()
   {
      int a = c; // here ERROR
      int c = 10;
   }
}

c is not defined before use, as c is a local variable in a method.


text:
Q: how to install/start docker engine service inside a docker container I am running jenkins off of the official docker container for jenkins. And i have the following dockerfile following the instructions at https://docs.docker.com/engine/installation/linux/debian/
FROM jenkins:2.32.1

# install docker inside this container
USER root
    # Install Docker inside Jenkins
    RUN apt-get update
    RUN apt-get purge "docker.io*"
    RUN apt-get update
    RUN apt-get install -y apt-transport-https ca-certificates gnupg2
    RUN apt-key adv \
       --keyserver hkp://ha.pool.sks-keyservers.net:80 \
       --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
    RUN echo "deb https://apt.dockerproject.org/repo debian-jessie main" > /etc/apt/sources.list.d/docker.list
    RUN apt-get update
    RUN apt-cache policy docker-engine
    RUN apt-get update
    RUN apt-get install -y docker-engine
    RUN gpasswd -a jenkins docker
    USER jenkins

Then i perform the following:

*

*build an image from this dockerfile

*run a container from the image

*execute bash in the container as root user

*run sudo docker service start in bash inside the container

Here is what i get:
root@1e0f4b325d58:/# sudo service docker start
mount: permission denied
rmdir: failed to remove 'cpu': Read-only file system
mount: permission denied
rmdir: failed to remove 'cpuacct': Read-only file system
mount: permission denied
rmdir: failed to remove 'net_cls': Read-only file system
mount: permission denied
rmdir: failed to remove 'net_prio': Read-only file system
/etc/init.d/docker: 96: ulimit: error setting limit (Operation not permitted)

A: You need to run the container as a privileged container if you want to run docker inside docker.
So something like this (1) is required:
docker run --privileged your_image:tag

You also need to be careful with iptables and App Armour, but this works after a bit of tinkering.

The alternative is to give access to the docker daemon inside the container, like so (2):
docker run -v /var/run/docker.sock:/var/run/docker.sock your_image:tag

Ref:
1 https://blog.docker.com/2013/09/docker-can-now-run-within-docker/
2 https://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/


text:
Q: I dont understand how to call Validation logic with Template 10 Validation I've been trying to reproduce the simplest validation logic ever possible with template 10 validation, but I Just dont get it.
I have created my Model like the wiki at the example at github:
public class User : ValidatableModelBase
{
    //public User()
    //{
    //    FirstName = string.Empty;
    //    LastName = string.Empty;
    //    Validator = i =>
    //    {
    //        var u = i as User;
    //        if (string.IsNullOrEmpty(u.FirstName))
    //            u.Properties[nameof(u.FirstName)].Errors.Add("The first name is required");
    //        else if (u.FirstName.Length <= 3)
    //            u.Properties[nameof(u.FirstName)].Errors.Add("First Name must be greater than 3 chars.");

    //        if (string.IsNullOrEmpty(u.LastName))
    //            u.Properties[nameof(u.LastName)].Errors.Add("The last name is required");
    //        else if (u.LastName.Length <= 3)
    //            u.Properties[nameof(u.LastName)].Errors.Add("Last Name must be greater than 3 chars.");
    //    };
    //}

    public int Id { get; set; }
    public string FirstName
    {
        get
        {
            return Read<string>();
        }
        set
        {
            Write(value);
        }
    }
    public string LastName
    {
        get
        {
            return Read<string>();
        }
        set
        {
            Write(value);
        }
    }
    public override string ToString() => $"{FirstName} {LastName}";
}

as you can see I've even created a constructor to initialize my Object, I commented out because I wanted to initialize the values at my ViewModel Constructor.
Then my view model is this:
public class MainPageViewModel : ViewModelBase
{
    public MainPageViewModel()
    {
        User = new User
        {
            FirstName = string.Empty,
            LastName = string.Empty,
            Validator = i =>
            {
                var u = i as User;
                if (string.IsNullOrEmpty(u.FirstName))
                    u.Properties[nameof(u.FirstName)].Errors.Add("The first name is required");
                else if (u.FirstName.Length <= 3)
                    u.Properties[nameof(u.FirstName)].Errors.Add("First Name must be greater than 3 chars.");

                if (string.IsNullOrEmpty(u.LastName))
                    u.Properties[nameof(u.LastName)].Errors.Add("The last name is required");
                else if (u.LastName.Length <= 3)
                    u.Properties[nameof(u.LastName)].Errors.Add("Last Name must be greater than 3 chars.");
            },
        };
    }

    private User _User;

    public User User
    {
        get { return _User; }
        set { _User = value; }
    }

    public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
    {
        User.Validate();
        await Task.CompletedTask;
    }

    public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
    {
        args.Cancel = false;
        await Task.CompletedTask;
    }

    public void GotoSettings() =>
        NavigationService.Navigate(typeof(Views.SettingsPage), 0);

    public void GotoPrivacy() =>
        NavigationService.Navigate(typeof(Views.SettingsPage), 1);

    public void GotoAbout() =>
        NavigationService.Navigate(typeof(Views.SettingsPage), 2);

}

Now at my view all I have is this:
<Page x:Class="ValidationSample.Views.MainPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:Behaviors="using:Template10.Behaviors"
  xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
  xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
  xmlns:controls="using:Template10.Controls"
  xmlns:validate="using:Template10.Controls.Validation"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="using:ValidationSample.Views"
  xmlns:m="using:ValidationSample.Models"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:vm="using:ValidationSample.ViewModels" mc:Ignorable="d">

<Page.DataContext>
    <vm:MainPageViewModel x:Name="ViewModel" />
</Page.DataContext>

<RelativePanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="AdaptiveVisualStateGroup">
            <VisualState x:Name="VisualStateNarrow">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="{StaticResource NarrowMinWidth}" />
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <!--  TODO: change properties for narrow view  -->
                    <!--<Setter Target="stateTextBox.Text" Value="Narrow Visual State" />-->
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="VisualStateNormal">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="{StaticResource NormalMinWidth}" />
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <!--  TODO: change properties for normal view  -->
                    <!--<Setter Target="stateTextBox.Text" Value="Normal Visual State" />-->
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="VisualStateWide">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="{StaticResource WideMinWidth}" />
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <!--  TODO: change properties for wide view  -->
                    <!--<Setter Target="stateTextBox.Text" Value="Wide Visual State" />-->
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <controls:PageHeader x:Name="pageHeader" RelativePanel.AlignLeftWithPanel="True"
                         RelativePanel.AlignRightWithPanel="True"
                         RelativePanel.AlignTopWithPanel="True" Text="Main Page">

        <!--  secondary commands  -->
        <controls:PageHeader.SecondaryCommands>
            <AppBarButton Click="{x:Bind ViewModel.GotoSettings}" Label="Settings" />
            <AppBarButton Click="{x:Bind ViewModel.GotoPrivacy}" Label="Privacy" />
            <AppBarButton Click="{x:Bind ViewModel.GotoAbout}" Label="About" />
        </controls:PageHeader.SecondaryCommands>

    </controls:PageHeader>

    <validate:ControlWrapper PropertyName="FirstName"
                             RelativePanel.AlignLeftWithPanel="True"
                             RelativePanel.Below="pageHeader">
        <TextBox Width="300"
                 Margin="12,0,0,0"
                 Header="First Name"
                 Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    </validate:ControlWrapper>

</RelativePanel>

As fas as I know I have the model with the ValidatableModelBase logic Applied, I do have the Validate:wrapper applied to the view, I've set the validator at the VM ctor or I could set it at model ctor.
My problem is where do i make the Calling logic???
Because I havent been able to trigger the UpdateSourceTrigger of my FirstName field.
What am i doing wrong??
To be more honest I dont know where to place the Validate method, because at the sample at github the validate method is call everytime you open the modal dialog window, but that is when you are navigating to that window and its field everytime they changed they are being validated, but in my case nothing happens, why?? Hopefully someone can help me out, since I'm new at template 10 and also at UWP.

A: Damn, I was so damn tired but my mistake was so god damn simple I forgot to set the DataContext at the Parent Panel, In this case I should had add DataContext ={Binding Model}
this at XAML within the relative panel or any other Panel.
I felt so noob to have made this question.


text:
Q: Azure Java Function (App Service Plan) can not use VPN I've deployed a Java Function with the App Service Plan on Azure and also associated a VPN (connecting back to my data center) to that App Service Container.  My application is trying to send an HTTP request to another server in my data center over the VPN but the requests fails with a "Time out" exception. If I connect directly to my data center VPN (not through Azure) it works no problem.
Also, strangely, if I recreate the function in C# it works from Azure.
1) I've tried connecting to different ports with a raw TCP socket, no luck.
2) I've dumped the list of adapters to a log and the VPN adapter doesn't show up.  Should it?
What's my next step in troubleshooting?


text:
Q: Passing $(this) to jQuery .hover() functions I wrote a simple tooltip functionality, to be seen here.
The thing is, in both handler functions set in .hover() I need access to $(this) and other 2 variables based on it. In order do achieve that, I declare the same 3 variables in both handlers:
$('a').hover(
    function () {
        var $this = $(this);
        var link_offset = $this.offset();
        var link_tooltip = $this.data('tooltip');
        // Rest of the code
    },
    function () {
        var $this = $(this);
        var link_offset = $this.offset();
        var link_tooltip = $this.data('tooltip');
        // Rest of the code
    }
);

DRY principle should be respected, so my question is: Is there other and smarter/less dirty way of passing the same variables set to both functions within .hover()?
Obvioulsy, the variables can't be global (and globals are evil anyway).
Any ideas how to achieve this with jQuery or pure JS?

A: Call one named function inside the anonymous callbacks:
$('a').hover(function() {
        hoverFunc($(this), true)
    }, function() {
        hoverFunc($(this), false)
    });

function hoverFunc($this, is_hovered) {
    var link_offset = $this.offset();
    var link_tooltip = $this.data('tooltip');
    if (is_hovered) {
        console.log('ok')
        // do something
    } else {
        console.log('out')
        // do something else
    };
}

http://jsfiddle.net/mblase75/8njk2m32/


text:
Q: How to add an array to an array I have an array items with some arrays. Now I want to add an array item_optional to the top of array items.
This is what I've tried, but I think this is not correct:
$item_optional = array(
    'harry' => array('name'=>'test1', 'code'=>1697, 'hmp'=>'x1')
);

$items = array(
    'denise'  => array('name'=>'test2', 'code'=>2697, 'hmp'=>'x2'),
    'mike'    => array('name'=>'test3', 'code'=>3697, 'hmp'=>'x3'),
    'richard' => array('name'=>'test4', 'code'=>4697, 'hmp'=>'x4')
);

array_unshift($items, $item_optional);

The output should be:
$items = array(
    'harry'   => array('name'=>'test1', 'code'=>1697, 'hmp'=>'x1'),
    'denise'  => array('name'=>'test2', 'code'=>2697, 'hmp'=>'x2'),
    'mike'    => array('name'=>'test3', 'code'=>3697, 'hmp'=>'x3'),
    'richard' => array('name'=>'test4', 'code'=>4697, 'hmp'=>'x4')
);

A: You can try:
$item_optional = array(
    'harry' => array('name'=>'test1', 'code'=>1697, 'hmp'=>'x1')
);

$items = array(
    'denise'  => array('name'=>'test2', 'code'=>2697, 'hmp'=>'x2'),
    'mike'    => array('name'=>'test3', 'code'=>3697, 'hmp'=>'x3'),
    'richard' => array('name'=>'test4', 'code'=>4697, 'hmp'=>'x4')
);

The code:
$items = $item_optional + $items;

Result:
array (size=4)
  'harry' =>
    array (size=3)
      'name' => string 'test1' (length=5)
      'code' => int 1697
      'hmp' => string 'x1' (length=2)
  'denise' =>
    array (size=3)
      'name' => string 'test2' (length=5)
      'code' => int 2697
      'hmp' => string 'x2' (length=2)
  'mike' =>
    array (size=3)
      'name' => string 'test3' (length=5)
      'code' => int 3697
      'hmp' => string 'x3' (length=2)
  'richard' =>
    array (size=3)
      'name' => string 'test4' (length=5)
      'code' => int 4697
      'hmp' => string 'x4' (length=2)

A: Try array_merge:
$items = array_merge( $item_optional, $items );

or you can use the + operator
$items = $item_optional + $items;

A: You can use array_merge().
This will put the array at the end of the other array.  Then your first argument will be your array on top and the second argument will be the array on end.
$items = array_merge( $item_optional, $items );

More information: array_merge()


text:
Q: Where is the k8s yaml file generally placed? Is it professional in this position of the server?
enter image description here

A: Hi there and welcome to StackOverflow. This question is probably going to be closed soon for being unclear. Kubernetes is driven by an API so where you put the files is up to you, as long as you upload them into the API, usually via kubectl apply. It's hard to be more specific than that given how vague your question is.


text:
Q: Handle limit data with 2 buttons (Next and previous button ) in vuejs In my work, the concept look like have lot of data in array , but the first one i want to show only 4 object (id 1 to id 4) in array. So , next i press next button that i want to loop the next object in array (id 5 to id 8) , then i press the back button they return to previous object that i pass them . i don't know the logic for this.
<template>
  <v-container fluid>
    <v-row no-gutters>
      <v-col cols="12" md="12" sm="12">
        <v-card>
          <v-row no-gutters>
            <v-col cols="12" md="12" sm="12" class="">
              <v-row no-gutters class="d-flex">
                <v-col
                  cols="6"
                  md="6"
                  v-for="(item, index) in content"
                  :key="`item-${index}`"
                >
                  <v-col cols="6">
                    <v-card-text>

{{ item.id }}

my name is : {{ item.title }}

                    </v-card-text></v-col
                  >
                </v-col>
              </v-row>
            </v-col>
          </v-row>

          <v-col cols="12" md="12" sm="12" class="d-flex">
            <v-col cols="6" md="6" sm="6">
              <v-btn medium elevation="" color="primary" @click="backpage()"
                >Back</v-btn
              >
            </v-col>
            <v-col cols="6" md="6" sm="6">
              <v-btn medium elevation="" color="primary" @click="nextPage()"
                >Next</v-btn
              >
            </v-col>
          </v-col>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

A: Try like following snippet:
Add data property currentPage: 1, then in next/back page increment/decrement current page and slice(this.showCounted * this.currentPage, this.showCounted * this.currentPage + this.showCounted) / slice(this.showCounted * this.currentPage - this.showCounted, this.showCounted * this.currentPage). Also you can disable/enable buttons if you are on last/first page. This way you can chose whatever number of items you want to show just set showCounted to desired value.

Vue.config.productionTip = false
Vue.config.devtools = false
new Vue({
  el: '#demo',
  vuetify: new Vuetify(),
  data(){
    return {
      showCounted: 4,
      currentPage: 1,
      content: '',
      nextValue: Number,
      user: [
        {id: 1, title: 'Saysana'}, {id: 2,title: 'Binh'}, {id: 3, title: 'Say'},
        {id: 4, title: 'Q'}, {id: 5, title: 'a'}, {id: 6, title: 'b'},
        {id: 7, title: 'c'}, {id: 8, title: 'e'}, {id: 9, title: 'e'},
        {id: 10, title: 'e'}, {id: 11, title: 'e'},{id: 12, title: 'e'},
      ],
      isDisabledN: false,
      isDisabledB: false
    }
  },
  methods: {
    defaultData() {
      this.content = this.user.slice(0, this.showCounted)
    },
    nextPage() {
      this.content = this.user.slice(this.showCounted * this.currentPage, this.showCounted * this.currentPage + this.showCounted)
      this.currentPage++
      this.checkPage()
    },
    backpage() {
      this.currentPage--
      this.content = this.user.slice(this.showCounted * this.currentPage - this.showCounted, this.showCounted * this.currentPage)
      this.checkPage()
    },
    checkPage() {
      if (this.showCounted  * this.currentPage >= this.user.length) {
        this.isDisabledN = true
        this.isDisabledB = false
      } else if(this.currentPage <= 1) {
        this.isDisabledN = false
        this.isDisabledB = true
      } else {
        this.isDisabledN = false
        this.isDisabledB = false
      }
    }
  },
  mounted() {
    this.defaultData()
    this.checkPage()
  },
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">

  <v-app>
    <v-main>
      <v-container fluid>
        <v-row no-gutters>
          <v-col cols="12" md="12" sm="12">
            <v-card>
              <v-row no-gutters>
                <v-col cols="12" md="12" sm="12" class="">
                  <v-row no-gutters class="d-flex">
                    <v-col
                      cols="6"
                      md="6"
                      v-for="(item, index) in content"
                      :key="`item-${index}`"
                    >
                      <v-col cols="6">
                        <v-card-text>

{{ item.id }}

my name is : {{ item.title }}

                        </v-card-text></v-col
                      >
                    </v-col>
                  </v-row>
                </v-col>
              </v-row>

              <v-col cols="12" md="12" sm="12" class="d-flex">
                <v-col cols="6" md="6" sm="6">
                  <v-btn :disabled="isDisabledB" ref="back" medium elevation="" color="primary" @click="backpage()"
                    >Back</v-btn
                  >
                </v-col>
                <v-col cols="6" md="6" sm="6">
                  <v-btn :disabled="isDisabledN" ref="next" medium elevation="" color="secondary" @click="nextPage()"
                    >Next</v-btn
                  >
                </v-col>
              </v-col>
            </v-card>
          </v-col>
        </v-row>
      </v-container>
   </v-main>
 </v-app>


text:
Q: Bluetooth Low Energy - java.lang.NullPointerException So I've been struggling with this for the past few hours and searching SO before I don't think I can find a way to sovle my problem. Basically I'm trying to use Context inside of the Fragment extension and it's giving me errors I've pasted the full code here in this gist
enter link description here
From what I found on SO it sounds like this happens when there is null for Context, but I don't understand how to fix it.
LogCat:

> 06-18 10:20:08.972    5718-5718/com.aparosecurity.kblock W/dalvikvm﹕
> threadid=1: thread exiting with uncaught exception (group=0x41625898)
> 06-18 10:20:08.992    5718-5718/com.aparosecurity.kblock
> E/AndroidRuntime﹕ FATAL EXCEPTION: main
>     java.lang.NullPointerException
>             at com.aparosecurity.kblock.ImageFragment.onCreate(ImageFragment.java:77)
>             at android.support.v4.app.Fragment.performCreate(Fragment.java:1477)
>             at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:904)
>             at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:834)
>             at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:841)
>             at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
>             at android.support.v4.view.ViewPager.populate(ViewPager.java:1066)
>             at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
>             at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
>             at android.view.View.measure(View.java:15848)
>             at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
>             at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
>             at android.view.View.measure(View.java:15848)
>             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
>             at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
>             at android.view.View.measure(View.java:15848)
>             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
>             at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
>             at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
>             at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
>             at android.view.View.measure(View.java:15848)
>             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
>             at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
>             at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
>             at android.view.View.measure(View.java:15848)
>             at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
>             at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
>             at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
>             at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
>             at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
>             at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
>             at android.view.Choreographer.doCallbacks(Choreographer.java:562)
>             at android.view.Choreographer.doFrame(Choreographer.java:532)
>             at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
>             at android.os.Handler.handleCallback(Handler.java:730)
>             at android.os.Handler.dispatchMessage(Handler.java:92)
>             at android.os.Looper.loop(Looper.java:137)
>             at android.app.ActivityThread.main(ActivityThread.java:5136)
>             at java.lang.reflect.Method.invokeNative(Native Method)
>             at java.lang.reflect.Method.invoke(Method.java:525)
>             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
>             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
>             at dalvik.system.NativeStart.main(Native Method)

Any help is appreciated.
The specific lines which are failing, the error occurs when mContext is used.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
    mHandler = new Handler();

    // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
    // BluetoothAdapter through BluetoothManager.
    final BluetoothManager bluetoothManager =
            (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

}

A: You have not initialized mContext and it is null. Invoking a method on null reference causes the NPE.
In a fragment, use getActivity() to get a reference to the hosting activity that can be used as a Context. (Caveat: Only when attached to an activity. Works in onCreate() which comes after onAttach().)
So, replace
mContext.getSystemService()

with
getActivity().getSystemService()


text:
Q: Stop html formatting in TinyMCE Thought I should do a new question rather than extend the other, sorry if that was the wrong thing to do.
I am having another issue with TinyMCE. When I want enter something like a  single dash, when I submit my changes the editor will just remove it and I would have to 2 dashes in order to show 1. Of course I would know what to do but I don't want to make my website live expecting the people using it to know that they have to do that. Is there a way to disable the html formatting TinyMCE does?
This is my current setup:
      tinymce.init({

          selector: "textarea",
          allow_html_in_named_anchor: true,
          valid_elements: "*[*]",
          verify_html: false,
          plugins: [

              "advlist autolink lists link image charmap print preview anchor",

              "searchreplace visualblocks code fullscreen",

              "insertdatetime media table contextmenu paste",

          ],
          toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",

      });

Is anyone able to help?
Thanks

A: TinyMCE will not do anything (on its own) to a single backslash that you type into the editor.
Open this TinyMCE Fiddle:
http://fiddle.tinymce.com/HLgaab/7
...and type in a single backslash.  You will see in the adjacent
 that the single backslash is maintained.
You will also note that if you are using JavaScript to process the HTML as a string that the backslash has a special meaning and must be escaped.
For example, if you are trying to load content into the editor using JavaScript you would have to properly escape the backslash so that JavaScript does not interpret it incorrectly:
editor.setContent('
pizza\\burger
');

...is correct but...
editor.setContent('
pizza\burger
');

...is incorrect and the \b is treated as an escape sequence as opposed to simple characters.
If you are pre or post processing the content using JavaScript you need to properly escape the content.


text:
Q: Dropdown spinner android 2.3.3 I'm developing app in Android 2.3.3 having spinner always opening in Dialog mode .I want to open it as in Drop Down mode . Is there any customization available in android 2.3.3 to open it as Drop Down mode ?

A: There is no dropdown spinners for android below android 4.0 But you can use this PopupWindow as dropdown list more info here or lib HoloEverywhere Hope it helps :)


text:
Q: Creating A Standalone Python exe New to programming. I created a python program and wanted to make it standalone using cx_Freeze. I've installed a whp. file from their website and I had problems installing cx_Freeze, as when I try to do a pip, install: it says "pip is not recognized.
When running my setup.py it says error importing cx_Freeze as such module doesn't exist.

A: pyinstaller yourfile.py -F --onefile

This creates a standalone EXE file on Windows.
Important note 1: The EXE file will be generated in a folder named 'dist'.
Important note 2: Do not forget --onefile flag
You can install PyInstaller using pip install PyInstaller
NOTE: In rare cases there are hidden dependencies...so if you run the EXE file and get missing library error (win32timezone in the example below) then use something like this:
pyinstaller --hiddenimport win32timezone -F "Backup Program.py"


text:
Q: Black Hole horizons and the Equivalence Principle? In the reference frame of a freefalling observer, does crossing the event horizon not cause a contradiction between two classical principles that supposedly apply at the event horizon: the equivalence principle and the principle that no signal can cross from inside the horizon to outside?
Consider the following:
Let us first suppose that the equivalence principle holds.  In this case, consider an astronaut falling into a very large black hole such that the tidal forces at the horizon are negligible.  The equivalence principle states that the astronaut will not even be aware that she is crossing the horizon (the spacetime there is smooth and 'uninteresting' from her perspective, and she will feel the same as she would if she were floating in empty space).  If this is true, then she could have a camera on her foot connected to a transmitter on her head, and as she crosses the horizon she will be able to transmit the images captured by her camera outside the black hole via the transmitter on her head.  If she detects nothing physically different as she crosses the horizon, then when her feet are inside the horizon while her head is outside the horizon, there should be nothing preventing her from transmitting the pictures out to the Unvierse from her transmitter.  But this violates the principle that no signals can leave a black hole.  Now, if we rather take as true the principle that no signals can pass from inside to outside the horizon, then as her feet cross the horizon, the forces holding her feet to her ankles will be changed because while her ankles can send force signals to her feet, her feet cannot send force signals back to her ankles, and she will therefore 'feel' herself cross the horizon, but this in tern violates the equivalence principle.
How are these contradictions resolved in the current understanding of black hole physics

A: An object inside a black hole horizon cannot send signals outside of the horizon, but something falling into the black hole can fall through the signal.
Take the example of the camera attached to the astronaut's foot. When the astronaut is halfway through the horizon, the camera is about a meter inside the horizon and the transmitter is about a meter outside the horizon. You say this would allow information to be sent out of the horizon, but that assumes instantaneous signal transmission from camera to antenna.
In actuality, the signal moves at the same speed as light - more generally, the speed of information, field disturbance propagation, massless particles, etc. - which, one meter inside the horizon, is still toward the center even when directed outward. So the camera sends a burst of data through a wire up the astronaut's leg, but the data is slowly falling down despite being sent "up" at the speed of light.
However, the astronaut is falling quickly toward the center of the black hole, so from her perspective the signal is still moving up the wire relative to her, and because the speed of electromagnetic perturbations (like light and changes in electric current) is locally invariant, she will measure it moving at the same 3x10^6 m/s as always. She can't tell she's already fallen through the horizon because there's nothing amiss about her measurements locally. By the time the signal from the camera reaches the transmitter, the transmitter is already inside the horizon.
Since all the other forces at play also move at the same speed, for example the electromagnetic forces holding her feet to her ankles and such, the same principle applies. The astronaut won't sense that her feet have passed the horizon, because in order for her brain to register any difference, the signal would have to travel from her ankles to her head faster than light.

A: The equivalence principle only holds for extremely small regions of spacetime. Which means they hold for short time intervals as well as small spatial regions.
Consider an event near the event horizon. If the event is outside the horizon there might be a frame moving away from it that cover a very small region that is also completely outside the horizon and it could all fall down, but with an upwards velocity so that for the short time interval it exists the whole thing stays outside the horizon.
If the event is inside the horizon then there is a small region and a small time interval where the whole frame starts out inside the horizon and all stays inside the horizon.
If the event is right on the horizon, then no matter what timelike tangent you select it is heading in. So you can pick a short time interval and a small region of space where the whole frame falls within the horizon, just like the worldline tangent to that event does.  You could also do this for the example with the event outside if it is close enough and heading in enough.
Everything has to be small since general relativity doesn't necessarily have global frames (that is what the word general indicates).
So the only part that seems relevant are the frames that cross the horizon. But each of those frames is inertial and nothing interesting is happening.  In those frames the horizon is like an expanding surface of light that rushes past them at the speed of light. It just is not an issue. The frame moves in a locally timelike manner and the horizon is a locally lightlike surface so it just rushes past.
It's like how if you lie down with your feet facing your favorite sports team how your feet might get the information about their victory before the rest of you. It's not going to look or feel weird. Imagine that by the time that information gets to your friend you can't make predictions about who's going to win.
An event horizon is a global feature it is a last call, last time to send a letter home and have it get there, last chance to order before they stop taking orders, last chance to change your mind. Its the "are you sure" button except its actually all invisible and it is relative to someone far far away.
You don't feel that the last mailman heading to a particular destination has passed you. And that is 100% all that happens in classical physics when there is an event horizon. You can imagine that someone else is already sending a signal out the signal that never get out. You can send something before it and it will get out, or you can send something with it and also fail.
It literally does not feel like something. And you head and your foot can be in different frames. That always happens in general relativity, frames are local. That just means it's like your body communicates by letter you send something and then wait to hear back.


text:
Q: Asymptotic expansion of $\int_{0}^{\infty}(1+\frac{u}{k})^{-k}e^{-u}du$ as $k\to \infty$ (Ablowitz) The following is from Complex Variables by Ablowitz & Fokas (P438).

Show that $\displaystyle \int_{0}^{\infty}\left(1+\frac{u}{k}\right)^{-k}e^{-u}du \sim \frac{1}{2}+\frac{1}{8k}$ as $k\to \infty$.

The original source had the third term, but it was omitted by the instructor of my course.
My attempt
Since the section is about Laplace's method, I tried to use it.
The integral can be written as
$\displaystyle \int_{0}^{\infty}e^{-k\log{(1+\frac{u}{k})}}e^{-u}du \tag*{}$
To use Laplace's method, we let $u/k=s$. Then we have $u=sk$ and $du=kds$. so the integral can be written as
$\displaystyle \int_{0}^{\infty}e^{-k\log{(1+s)}}e^{-sk}kds \tag*{}$
or
$\displaystyle k\int_{0}^{\infty}e^{-k(\log{(1+s)+s)}}ds \tag*{}$
Now we use Laplace's method. Since $h(s)=\log{(1+s)}+s$ attains minimum in $[0,\infty)$ at $s=0$, we have
$\displaystyle k\int_{0}^{\infty}e^{-k(\log{(1+s)+s)}}ds \sim \frac{1}{2}ke^{-kh(0)}\sqrt{\frac{2\pi}{k|h''(0)|}} = \sqrt{\frac{\pi k}{2}} \tag*{}$
...But this is obviously not what we wanted. I am stuck here.

A: I am not sure if it is correct, so feel free to correct it. Denote the integral by $I(k)$.
We have $h'(s)=1+\frac{1}{1+s} = \frac{2+s}{1+s}$. Since $h'(s)>0$ on $[0,\infty)$, $h$ is a strictly increasing function. Thus, most contribution to the integral comes from the neighborhood of $s=0$, where $h(s)$ attains minimum (on $[0,\infty)$). Moreover, since it is a strictly increasing function, it has an inverse $h^{-1}$.
Now, we substitute $t=h(s)$. Then we have $s=h^{-1}(t)$. We have $t=0$ when $s=0$, and $t\to\infty$ when $s\to \infty$. Moreover, we have
$\displaystyle ds = \frac{dt}{h'(h^{-1}(t))} = \frac{1+h^{-1}(t)}{2+h^{-1}(t)}dt \tag*{}$
Therefore,
$\displaystyle I(k) = k \int_{0}^{\infty} \frac{1+h^{-1}(t)}{2+h^{-1}(t)}e^{-kt}dt \tag*{}$
We note that the contribution to the integral comes from the neighborhood of $t=0$. So, we find the asymptotic behavior of $\frac{1+h^{-1}(t)}{2+h^{-1}(t)}$ as $t\to 0$.
Since $t=h(s)=s +\log{(1+s)}$, we have
$\displaystyle t=s+s+O(s^2) =2s+O(s^2)\tag*{}$
Thus, $s=h^{-1}(t)=\frac{t}{2}+O(t^2)$.
Therefore, as $t\to 0$,
$\displaystyle \frac{1+h^{-1}(t)}{2+h^{-1}(t)} \sim \frac{1+\frac{t}{2}}{2+\frac{t}{2}}
 \\ \displaystyle =\frac{1}{2} \frac{1+\frac{t}{2}}{1-(-\frac{t}{4})} \\ \displaystyle  = \frac{1}{2}(1+\frac{t}{2})(1-\frac{t}{4}+O(t^2)) \\ \displaystyle = \frac{1}{2}+\frac{t}{8} +O(t^2)$
Here, we used
$\frac{1}{1-x} = 1+x+O(x^2) \textrm{ as } x\to 0\tag*{}$
from the second line to the third line for $x=-\frac{t}{4}$.
Thus,
$\displaystyle I(k)\sim k\left(\frac{1}{2}\int_{0}^{\infty}e^{-kt}dt+\frac{1}{8}\int_{0}^{\infty}te^{-kt}dt\right) \\ \displaystyle = k\left(\frac{1}{2k}+\frac{1}{8k^2} \right) \\ = \displaystyle \frac{1}{2}+\frac{1}{8k}$


text:
Q: sql lite, android - copy record into the same table I am trying to copy a record from a sql lite database within a android application and then insert that same record into the same table but with two different ids in the first two columns. any ideas?
    SQLiteDatabase db = dbs.getReadableDatabase();
        String SQL = "SELECT * FROM table_1 a " +
                "join table_2 b on a.ID = b.ID " +
                "where table1_Id = '"+Id+"' And" +
                "table_2_ID = 'one'";
        Cursor cursor2 = db.rawQuery(SQL, null);
        startManagingCursor(cursor2);
        int m = cursor2.getColumnCount();
        try{
           while (cursor2.moveToNext()) {
             for(int i=0; i<m; i++){
                String id1 = cursor2.getString(i);
             }
           }
         }
         catch(Exception e){}

A: try {
  while (cursor2.moveToNext()) {
    dbs.ad(Id, Id, cursor2.getString(3), "",
           cursor2.getString(5), cursor2.getString(6), cursor2.getString(7),
           "", "");
    }
}


text:
Q: How to apply a normal linear regression in Mahout? I found there's OnlineLogisticRegression in Mahout, but nothing about LinearRegression, is there any related classes allow me to apply linear regression ?

A: No.
Apache Mahout doesn't have a routine for LinearRegression since it is considered to be a simple problem for even large datasets.
If you still keen on using LinearRegression on Hadoop (having large dataset), I highly recommend you to use the MLib - Apache Spark library which has support for L1- and L2- regularized Linear Regression that runs on Hadoop extremely efficient and highly scalable.


text:
Q: Can I use a PNP Transistor with an Electret Microphone to get an non-inverting output for my Arduino? I'm looking to simply read the generic sound level from an Electret Microphone. I've seen a number of schematics with NPN transistors, that will provide an inverted output (~5V when quiet, ~0V when loud, linear operation in between).
Here's an example:

However, I would like non-inverted output (linear operation, super quiet input gives ~0V, super loud input gives ~5V). I realize I could easily correct for this in software, but it just seems backward to me in a way and I cannot find any examples of a non-inverting output with a PNP transistor.
Is there a reason for this beyond being uncommon? If it's possible, could anyone provide a schematic of an electret microphone and PNP transistor that will give ~0V when quiet and ~5V when loud?
Further, is there some reason why this is so uncommon, or undesirable? NPNs seem to be used much more often than PNPs, why is this?
Edit
It seems I was rather confused in what I would get as output from the NPN preamp, which would be 0V for silence, and +/- Vin / 2. Here's what I want instead:
0V when silent, ~2.5V in medium sound levels, ~5V in maximum sound levels. This could be read by the ADC easily into 'sound level' without much work at all. However, I cannot feed voltages < 0V or > 5V to the analog comparator. It looks like I want the above with an envelope detector, however that would only get me from 0V to 2.5V. How do I make it vary the full 0V to 5V, 0V being 'quiet' and 5V being 'loud', with everything in between linear?

A: As far as I understood, you are trying to make some kind of a sound level detector, which will let you detect if there is a sound with a certain volume or not. You can do this with minor changes to the schematic you have. But before that, you should understand the circuit.
Let's break that circuit down. First of all the part with the microphone.

R1 is for supplying power that is needed by the microphone and this is called biasing the microphone. A microphone generates an AC voltage, which is sometimes negative and sometimes positive and it changes most of the time. Think of a sine wave. But remember, we had some biasing to it which is a DC voltage. We have to take that out and give only the AC voltage to the amplifier. And doing this is easy with a simple, single capacitor. A capacitor does not let the DC to pass, but lets AC pass easily. We have blocked the DC portion of the voltage on the electret microphone.
Now, let's look at the amplifier itself. Imagine that there is nothing else but the below schematic:

In this configuration, the transistor is biased to be in the linear region. It is in the edge of being turned ON or turned OFF, but it is neither of it. If it was fully ON, it would be saturated. If it was fully OFF, it would be not conducting at all. But it is in the middle, which is called the linear region.
When it is configured like that, if you touch (not literally) to the base of it, creating a small change, the output will be changing largely. This is what amplification called. You can beg Google for more detailed information.
What if we combine the two circuits mentioned above. A biased electret microphone with a capacitor will output small changes with respect to sound. The transistor will amplify these small changes so they can be viewed easily:

Notice that I have changed C1 to 1uF. You can use values up to 100uF. You will probably need electrolytic capacitors. Also, notice that there is no more an output capacitor. This means that you will have an output voltage somewhere between 0 and 5 V, depending on the sound level. If you have an oscilloscope, view the waveform on the output. If you do not, try lighting an LED if the analog read is higher than, for example, 750. Experiment with different values than 750, then report me the results.

A: The common emitter class A amplifier is always inverting even if you use a PNP, the only difference is you invert the power supply polarity. If you use an audio transformer instead of  a capacitor you could change the signal phase as you please. But it will probably cost more than use two BJT. In order to solve your final question anyway, you have to rectify ( even with a single diode ) the output and apply the result to a load ( a resistor would be fine ) and feed this to the arduino analog input. There is no reason to invert the signal at all.

A: This amplifier inverts the signal, but you shouldn't care for an audio signal.
What you'll have at the output is AC, a capacitor blocks DC. So, you cannot say ~0V for quiet noise and ~5V for loud.
If what you want is a sound level sensor, one easy way is to add, after the output cap a circuit called "demodulator" or "peak detector", easily implemented around a diode and a few passive components.

A: Simply invert the output a second time, using a 2 stage amplifier. (See this page for more info on two stage, and non-inverting transistor amplification. Very insightful)

The same value resistors and capacitors, the same 2n3094 transistor, added to the output of your existing schematic, would provide a second inversion.
But someone correct me if I am wrong, but your schematic shows a simple biased amplifier, so you would really have 2.5v as the quiet range, and the waveform gets larger with more sound? You will have a ±2.5v peak to peak. You would have 1v/3v as a middle loudness.


text:
Q: Does calculation of resistances in parallel apply to magnetic circuits too? Like the title says.
Is 1/Rges = 1/R1 + 1/R2.... for magnetic resistances true aswell?
E.g. can we say that Rpar = R1*R2/(R1+R2) with magnetic resistances in parallel?

A: Yes, reluctances add the same way as resistors in parallel. That's why the centre post of an E-I transformer lamination is usually twice the area of the sides.


text:
Q: Summing up double lists in a Linq GroupBy I need to group a large number of records which were recorded every minute into daily and bind them to a chart. These records have two fields the datetime value and the double list. I've tried something like this:
var result = Alldatas
  .AsEnumerable()
  .GroupBy(r => r.TimeStamp.Day)
  .Select(x => new {
                 Day = x.Key,
                 Value = x.Sum(r => r.Value.Sum())
          })
  .OrderBy(x => x.Day)
  .ToList();

The problem is that the list items in the double list is being summed up each other into a single double value. The correct result is that double lists should be adding up each other into a single double list for each day. Is there a way to achieve this? Thanks.

A: If I understood you correctly, here is the code:
var result = Alldatas
    .AsEnumerable()
    .GroupBy(r => r.TimeStamp.Day)
    .Select(x => new {
        Day = x.Key,
        // Using Aggregate method
        Value = x
            .Select(y => y.Value)
            .Aggregate(new List<double>(), (acc, list) =>
            {
                for (int i = 0; i < list.Count; ++i)
                {
                    if (acc.Count == i) acc.Add(0);
                    acc[i] += list[i];
                }

                return acc;
        }),
        // Pure LINQ, using GroupBy
        Value2 = x
            // Create tuple (index, value) for each double
            .SelectMany(y => y.Value.Select((z, i) => Tuple.Create(i, z)))
            // Group by index
            .GroupBy(y => y.Item1)
            // Sum values within groups
            .Select(y => y.Select(z => z.Item2).Sum())
            // Make list
            .ToList()
    })
    .OrderBy(x => x.Day)
    .ToList();

For input:
var Alldatas = new []
{
    new { TimeStamp = DateTime.Now, Value = new List<double> { 1, 2, 3 } },
    new { TimeStamp = DateTime.Now, Value = new List<double> { 1, 2, 3 } },
    new { TimeStamp = DateTime.Now, Value = new List<double> { 1, 2, 3 } }
};

This will produce following result:
new[] {
    new { Day = 20, Value = new[] {3,6,9}, Value2 = new[] {3,6,9} }
}


text:
Q: Как задать условие в C# для StreamReader Делаю парсинг текстового файла. Нужно задать условие: "если строка начинается с числа" и тд. Как это реализовать

A: Есть такая штука, как String.StartWith(s1, s2);
Где s1 строка, которую ты проверяешь, а s2 - подстрока, наличие которой проверяеться в начале
Имеем следующий код:
StreamReader sr = new StreamReader(@puth);
string buffer; // буфер для считывания строк

while(!sr.EndOfStream)
{
    buffer = sr.ReadLine();
    if (String.StartWith(buffer, i.ToString()) // где і - нужное число, преобразованое в строку
    {
        // выполняешь нужные действия
    }
}
sr.Close();

Так же можно создать метод, который будет выполнять нужные действие в зависимости от содержащего числа в начале считаной строки, например:
public static string DoSomeOperationWithString(string s, string subS)
{
    string result;
    if(subS == "1.1")
    {
        // выполняешь действия, записывая результат в переменную result, потом возвращаешь ее
    }
    else if(subS == "1.2")
    {
        // выполняешь действия, записывая результат в переменную result, потом возвращаешь ее
    }
    return result;
}

Метод вызываешь  в теле цикла считывания, вместо if, и проверка осуществляеться непосредственно в методе. Так же можно создать подметоды, котоыре будут вызываться из этого метода.
Надеюсь, я овтетил на твой вопрос.
А вообще, ответ на твой вопрос есть вот тут:
https://msdn.microsoft.com/ru-ru/library/baketfxw(v=vs.110).aspx
PS: мой первый ответ на StackOverFlow:)

A: Ответ найден! Реализовал при помощи Regex(регулярные выражения):
string line = sr.ReadLine();
RegexOptions ignoreCase = RegexOptions.IgnorePatternWhitespace;
Regex reg = new Regex(@"^\s+[0-9]", ignoreCase);
Match m = reg.Match(line);


text:
Q: ¿Porque no me muestra datos de un Select cuando le agrego estilos y js? tengo un pequeño ejercicio que estaba haciendo para hacer selects anidados (Departamento-Provincia-Distrito) conectado a una bd en oracle. todo bien hasta ahí pero cuando le ingresaba estilos y js a mi index al momento de compilar sólo me mostraba los datos de mi primer Select (departamento) pero ya no de los demás. Adjunto mi código:
Código Ajax:
 function getXMLHTTPRequest() {
    try {
        req = new XMLHttpRequest();
    } catch(err1) {
    try {
        req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (err2) {
    try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (err3) {
        req = false;
        }
    }
    }
    return req;
}

var http = getXMLHTTPRequest(); // creo una instancia del objeto XMLHTTPRequest.

function elegirdepartamento(n_dep){
    var ele1=n_dep;
    var url = 'cargarselects.jsp?ele1='+ele1; // creacion de la URL.
    http.open("GET", url, true); // fijando los parametros para el envio de datos.
    http.onreadystatechange = handler1; // Quee funcion utilizar en caso de que el estado de la peticion cambie.
    http.send(null); // enviar peticion.
}

function handler1() {
    if (http.readyState == 4) {
        if(http.status == 200) {
            provincia.innerHTML="";
            provincia.innerHTML=provincia.innerHTML+http.responseText;
        }
    }
}

function elegirprovincia(n_prov){
    var ele2=n_prov;
    var url = 'cargarselects2.jsp?ele2='+ele2; // creacion de la URL.
    http.open("GET", url, true); // fijando los parametros para el envio de datos.
    http.onreadystatechange = handler2; // Quee funcion utilizar en caso de que el estado de la peticion cambie.
    http.send(null); // enviar peticion.
}

function handler2() {
    if (http.readyState == 4) {
        if(http.status == 200) {
            distrito.innerHTML="";
            distrito.innerHTML=distrito.innerHTML+http.responseText;
        }
    }
}

Código "cargarselects" donde hago referencia en mi ajax:
<%
    Conexion con=new Conexion();
    ResultSet res = null;
    Statement sen= con.getConexion();
    String n_dep = request.getParameter("ele1");
    System.out.print("Departamento seleccionado : "+n_dep+"\n");
    String provinciacon ="SELECT UNIQUE(n_prov) from ocex_uea WHERE n_dep like '"+n_dep+"%' ORDER BY n_prov asc";
    ResultSet rtprpovincia=sen.executeQuery(provinciacon);
%>

<select name="provincia" required>
<option selected value="0" >[PROVINCIA]</option>
<% while(rtprpovincia.next()){
System.out.println("Provinvia: "+rtprpovincia.getString(1));
%>
<option value="<%=rtprpovincia.getString(1)%>"><%=rtprpovincia.getString(1)%></option>
<%} %>
</select>

Este es mi index sin cargar los estilos y js:
Departamento de Residencia

<select name="departamento" id="departamento" onChange="elegirdepartamento(this.value)" required>

<option selected value="0">[DEPARTAMENTO]</option>
<%
Conexion con=new Conexion();
Statement sen= con.getConexion();
String sql="SELECT unique(n_dep) FROM ocex_uea ORDER BY n_dep asc";
ResultSet resdpto=sen.executeQuery(sql);
while(resdpto.next()){
resdpto.getNString(1);
%>
<option value="<%=resdpto.getNString(1)%>"><%=resdpto.getNString(1)%></option>
<%} %>
</select>

Provincia de Residencia
<select name="provincia" id="provincia" onChange="elegirprovincia(this.value)" required>
<option selected value="0">[PROVINCIA] </option>
</select>

Distrito de Residencia
<select name="distrito" id="distrito"  onchange="elegirdistrito(this.value)" required>
<option selected value="0">[DISTRITO] </option>
</select>

Para agregar mis estilos y js pongo esto:
<link href="css/materialize.min.css" type="text/css" rel="stylesheet" media="screen,projection">
<link href="css/style.min.css" type="text/css" rel="stylesheet" media="screen,projection">
<link href="css/custom/custom.min.css" type="text/css" rel="stylesheet" media="screen,projection">
<link href="js/plugins/prism/prism.css" type="text/css" rel="stylesheet" media="screen,projection">
<link href="js/plugins/perfect-scrollbar/perfect-scrollbar.css" type="text/css" rel="stylesheet" media="screen,projection">
<link href="js/plugins/chartist-js/chartist.min.css" type="text/css" rel="stylesheet" media="screen,projection">

Y despues que agrego esto y lo corro, no muestra los datos en los select (provincia, distrito). Alguna ayuda de qué está pasando, gracias.


text:
Q: Visualisation of a recursive function Is there a way to nicely visualize recursive functions? (diagrams/plots)
More specifically I'm looking for a way to make contrast (visually) between e.g. the cosine function which if continuously applied on itself converges to the Dottie number, whereas e.g. a usual linear function $2x$ if taken recursively keeps diverging.
If it helps, this is asked for pedagogical reasons, in the context of attractors.

A: Let you have a function and an initial point
f[x_] := Cos[x]
x0 = 0.2;

Then you can calculate a sequence
seq = NestList[f, x0, 10]
(* {0.2, 0.980067, 0.556967, 0.848862, 0.660838, 0.789478, \
0.704216, 0.76212, 0.723374, 0.749577, 0.731977} *)

and vizualize it with a so-called Cobweb plot
p = Join @@ ({{#, #}, {##}} & @@@ Partition[seq, 2, 1]);

Plot[{f[x], x}, {x, 0, π/2}, AspectRatio -> Automatic,
 Epilog -> {Thick, Opacity[0.6], Line[p]}]

The same for f[x_] := 2x

The logistic map:
logistic[α_, x0_] := Module[{f},
   f[x_] := α x (1 - x);
   seq = NestList[f, x0, 100];
   p = Join @@ ({{#, #}, {##}} & @@@ Partition[seq, 2, 1]);
   Plot[{f[x], x}, {x, 0, 1}, PlotRange -> {0, 1},
    Epilog -> {Thick, Opacity[0.6], Line[p]}, ImageSize -> 500]];

t = Table[logistic[α, 0.2], {α, 1, 4, 0.01}];
SetDirectory@NotebookDirectory[];
Export["logistic.gif", t];

A: Two slight improvements to the code:
[1] Using Function is faster:
f[α_] = Function[x, α x (1 - x)];

[2] One should localise seq, and Riffle is clearer than Join @@ ({{#, #}, {##}} & @@@
logistic[α_, x0_] := Module[{seq},
    seq = NestList[f[α], x0, 100];
    p = Riffle[Transpose[{seq, seq}], Partition[seq, 2, 1]];
    Plot[{f[α][x], x}, {x, 0, 1},
        AspectRatio -> Automatic,
        PlotRange -> {0, 1},
        Epilog -> {Thick, Opacity[0.6], Line[p]},
        ImageSize -> 500]]

Then I'd use Manipulate to visualize...

A: dottie = FindRoot[Cos[x] == x, {x, 1}] // Values // First

0.739085

Plot[{Cos[x], x}, {x, -5, 5},
 Epilog -> {Red, PointSize[0.02], Point[{dottie, dottie}]}]

Convergence can be seen with EvaluationMonitor
{res, {evx}} =
 Reap[FindRoot[Cos[x] == x, {x, 0}, EvaluationMonitor :> Sow[x]]]

{{x -> 0.739085}, {{0., 1., 0.750364, 0.739113, 0.739085, 0.739085}}}

points = Point @ Transpose[{evx, evx}]

Plot[{Cos[x], x}, {x, -5, 5},
 Epilog -> {Red, PointSize[0.02], points}]

Finding Dottie with Newton
fun = Cos[x] - x;

newton[fun_, n_] :=
 With[{f = fun / D[fun, x]}, NestList[# - f /. x -> # &, 0., n]]

points = newton[fun, 5]

{0., 1., 0.750364, 0.739113, 0.739085, 0.739085}

dottie = Last @ points;

ListLinePlot[points,
 Axes -> False,
 Frame -> True,
 FrameTicks -> {{{0, dottie, 1}, None}, {Automatic, None}},
 GridLines -> {Automatic, {0, dottie, 1}},
 Mesh -> All,
 MeshStyle -> Directive[PointSize[Medium], Red],
 ImageSize -> 500,
 PlotRange -> {{0.9, 6.1}, {-0.1, 1.1}}]

FixedPointList
f = # / D[#, x] & [fun]

fpl1 = FixedPointList[# - f /. x -> # &,  0.0];
fpl2 = FixedPointList[# - f /. x -> # &, -0.5];

ListLinePlot[
 {fpl1, fpl2},
 Axes -> False,
 Frame -> True,
 FrameTicks -> {{{-0.5, 0, dottie, 2}, None}, {Automatic, None}},
 GridLines -> {Automatic, {-0.5, 0, dottie, 2}},
 Filling -> {1 -> {2}},
 Mesh -> All,
 MeshStyle -> Directive[PointSize[Medium], Red],
 ImageSize -> 500,
 PlotLegends -> {"Start at   0.0", "Start at -0.5"},
 PlotRange -> {{0.9, 8.1}, {-0.6, 2.2}}]

Interpolation
fun = Cos[x] - x;
f = #/D[#, x] & [fun];
fpl = FixedPointList[# - f /. x -> # &, #] & /@ {0., -0.5, 3.0};
dottie = fpl[[1, -1]];

ListLinePlot[
 fpl,
 InterpolationOrder -> 2,
 Axes -> False,
 Frame -> True,
 FrameTicks -> {{{-0.5, 0, dottie, 2, 3}, None}, {Automatic, None}},
 GridLines -> {Automatic, {-0.5, 0, dottie, 2, 3}},
 Filling -> {{1 -> {2}}, {2 -> {3}}},
 FillingStyle -> Directive[Opacity[0.5], Gray],
 Mesh -> False,
 ImageSize -> 500,
 PlotLegends -> {"Start at   0.0", "Start at -0.5", "Start at   3.0"},
 PlotStyle -> Thickness[0.01],
 PlotRange -> {{0.9, 7.1}, {-0.6, 3.1}}]

A: Another realization of ybeltukov's code.
start=1/2;
f[x_] = x + Sin[x];
Manipulate[
Show[Plot[{x, f[x]}, {x, 0, Pi}],
NestList[{Last@#, f[First@# ]} &, {start, f[start]}, n] // ListLinePlot
], {n, 1, 10, 1}
]

A: Newton secant method (provided by anonymous users):
NewtonRaphson[func_, x_, start_ : 1.0, iter_ : 10] :=

 Module[

  {pts, xold = start, xnew, f, df, rangea, rangeb, labelPts,
   labelLines},

  pts = {};
  f = func; Print["f[", x, "]  = ", f];
  df = \!\(
\*SubscriptBox[\(∂\), \(x\)]f\);
  Print["f'[", x, "] = ", df];
  Do[

   AppendTo[pts, {xold, 0}];
   AppendTo[pts, {xold, f /. x -> xold}];
   xnew = xold - (f /. x -> xold)/(df /. x -> xold);
   xold = xnew,

   {k, 1, iter}

   ];
  Print["Root  = ", xnew];
  rangea = Floor[Min[pts] - 1];
  rangeb = Ceiling[Max[pts] + 1];
  labelPts = {{PointSize[.03], Point[{start, 0.}]}, {PointSize[.03],
     Point[{xnew, 0.}]}};
  labelLines =
   Join[
    labelPts,
    Table[
     {Thickness[.0007 i], Dashing[{.02, .01}],
      Line[Take[pts, {i, i + 1}]]},
     {i, 1, Length[pts] - 1}
     ]
    ];
  Plot[
   f,
   {x, rangea, rangeb},
   PlotRange -> All,
   PlotStyle -> Thickness[.007], Epilog -> labelLines
   ]

  ]

NewtonRaphson[Sin[x], x, 1.15, 5]


text:
Q: JavaScript String.split with group When I use a grouped expression in the regex in String.split, it results in keeping the separators in the result, without it the separators are lost. Is this an undocumented feature, or something I can rely on?

console.log('The quick brown fox jumped over the lazy dog.'.split(/h/g))
console.log('The quick brown fox jumped over the lazy dog.'.split(/(h)/g))


text:
Q: 'Nullable object must have a value' when adding entity to set in EF Core I'm having some trouble with adding an entity to a DbSet in EF Core.
The entity looks like this:
public class Employee : TenantEntity
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string EmailAddress { get; set; }

    public string PhoneNumber { get; set; }
}

With this base class:
public class TenantEntity
{
    public Guid Id { get; set; }

    public Guid TenantId { get; set; }

    public DateTime CreatedUtc { get; set; }

    public DateTime? UpdatedUtc { get; set; }

    public DateTime? DeletedUtc { get; set; }
}

The exception occurs in this method:

public class MultitenantRepository<TEntity> where TEntity : TenantEntity
{

    ...
    public TEntity Add(TEntity entity)
    {
        entity.TenantId = TenantProvider.GetTenantId();
        entity.CreatedUtc = DateTime.UtcNow;

        return Context.Set<TEntity>().Add(entity).Entity;
    }
    ...
}

Specifically on the Add method on Set<>(). Just some more details, I set the DateTime type as datetime2 within the DbContext.


text:
Q: Hiding another html component with Select2 + Jquery I am trying to hide a div (id #pagos) when a select input (id #buy_sell) option has been chosen (using select2).
Doing it with JQuery and a standard select box is pretty easy, but I'm a bit new to using select2 and everything has gotten complicated.
So far, I have not been able to find a script that works, that's why I come to you.
This is the code I have so far. I would be very grateful for any corrections to make it work.

A:

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>

  <select id="buy_sell">
    <option value="1">First option</option>
    <option value="2">Last option</option>
  </select>

Will be hidden if "2" is selected


text:
Q: Django - Change a ForeignKey relation to OneToOne I am using South with my Django app.  I have two models that I am changing from having a ForeignKey relation to having a OneToOneField relation. When I ran this migration on my dev database, it ran fine. When the migrations get ran as part of creating a test database, the latest migration fails with a MySQL 1005 error: "Can't create table mydb.#sql-3249_1d (errno: 121)". Doing some Googling revealed that this is usually a problem with trying to add a constraint with the same name as an existing constraint. The specific line in the migration that it fails on is:
The relation was changed from:
class MyModel(models.Model):
    othermodel = models.ForeignKey(OtherModel)

to
class MyModel(models.Model):
    othermodel = models.OneToOneField(OtherModel)

which generated the following statements in the migration:
db.alter_column('myapp_mymodel', 'othermodel_id', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['myapp.OtherModel'], unique=True))

db.create_unique('myapp_mymodel', ['othermodel_id'])

But instead of failing on the create_unique call, it is failing on the alter_column call. I ran the following command to see what SQL was being generated:
python manage.py migrate myapp 0010 --db-dry-run --verbosity=2

and it printed out
myapp:0010_auto__chg_field_mymodel_othermodel__add_unique_mymodel
   = ALTER TABLE `myapp_mymodel` ADD CONSTRAINT `myapp_mymodel_othermodel_id_uniq` UNIQUE (`othermodel_id`) []
   = SET FOREIGN_KEY_CHECKS=1; []
   = ALTER TABLE `myapp_mymodel` ADD CONSTRAINT `myapp_mymodel_othermodel_id_uniq` UNIQUE (`othermodel_id`) []

It seems strange that it is trying to run the ADD CONSTRAINT twice, but if I remove the db.create_unique call, no SQL is generated when I run it with --db-dry-run, but I still get the error if I run it for real.
I am at a loss here, any help is appreciated.

A: You actually don't need a migration at all. OneToOne and ForeignKey relations have a compatible database schema under the hook: a simple column witht the other object ID in one of the table.
Just fake the migration with migrate --fake if you don't want to enter in the trouble of telling south to ignore this change.

A: First thing I would try would be to add a db.delete_unique(...) in various places to see if I could hack it.
Failing that, I'd split it up into 3 migrations:

*

*a schema migration to add a new column for the OneToOne

*a data migration to copy all FK values from old column over to new

*a schema migration to remove the old column, which then I'd edit manually to include a command to rename the new column to the same as the old one.

A: I agree with @e-satis that the goal here is to fake a migration, but I suggest a different approach if you're working with a team.
If you create a migration then --fake it, all your team members will need to remember to --fake it as well. If any of them don't do this when they upgrade, you're in trouble.
A better approach is to create an empty migration, then migrate it:
manage.py schemamigration yourapp --empty fake_migration_of_foreign_key_to_onetoone
manage.py migrate  # Like you always do!


text:
Q: Android camera previews black image after taking photo I have a small application which opens up the camera preview, you click a button to take a photo, and it displays on the screen after. I'm using an emulator to preview this, with a Nexus 5 API 25.
When I start the app, I can see the camera preview as it should be. However when I click to take a photograph, it gives a black screen where the image should be, and the imageView.setBitmap(photo) also displays this black image.
I've been following this tutorial: https://www.youtube.com/watch?v=k1Wc0vmD284 and no one else seems to have this issue.
What could be the issue? Is it something to do with the sizing of the image after it's been taken? I've added file read and write permissions to my manifest file, and the photo preview does work without taking a picture so I'm assuming I have permission to use the camera.
Below is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

Button myButton = (Button) findViewById(R.id.myButton);
    imageView = (ImageView) findViewById(R.id.imageView);

    //disable button if user has no camera
    if(!hasCamera() ) {
        myButton.setEnabled(false);
    }
}

//Check if the user has a camrea
private boolean hasCamera() {
    return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}

//Launching the camera
public void launchCamera(View view ){
  Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

       Bundle extras = data.getExtras();
       Bitmap photo = (Bitmap) extras.get("data");
       imageView.setImageBitmap(photo)
}

A: private Uri fileUri;
public static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
 private void launchCamera() {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImage");
    imagesFolder.mkdirs();
    File image = new File(imagesFolder, "IMG_" + timeStamp + ".jpg");
    Uri uriSavedImage = Uri.fromFile(image);

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    startActivityForResult(cameraIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

    fileUri=uriSavedImage;

}

private boolean hasCamera() {
    if (getApplicationContext().getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // this device has a camera
        return true;
    } else {
        // no camera on this device
        return false;
    }
}

 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on scren orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

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

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case CAMERA_CAPTURE_IMAGE_REQUEST_CODE:
            if (resultCode == RESULT_OK) {
                // successfully captured the image
                // display it in image viewproduct_image
                Bitmap photo = (Bitmap) data.getExtras().get("data");

                storeImage(photo);

            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
            break;
}
}
    private void storeImage(Bitmap image) {

    if (fileUri == null) {
        Log.d("TAG",
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    }
    try {
        FileOutputStream fos = new FileOutputStream(fileUri.getPath());
        image.compress(Bitmap.CompressFormat.JPEG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d("TAG", "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d("TAG", "Error accessing file: " + e.getMessage());
    }

    Bitmap bitmap1= BitmapFactory.decodeFile(fileUri.getPath());
    imageView.setImageBitmap(bitmap1);
}
  public static boolean checkIfAlreadyhavePermission(Activity activity, String permission) {
    int result = ContextCompat.checkSelfPermission(activity, permission);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}
public static void requestForSpecificPermission(Activity activity, String granted_permission) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        activity.requestPermissions(new String[]{granted_permission}, 101);
    }
}
  protected void onResume() {
    super.onResume();
if( checkIfAlreadyhavePermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) ){

    }else {
        requestForSpecificPermission(
                activity, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    if( checkIfAlreadyhavePermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) ){

    }else {
        requestForSpecificPermission(
                activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (checkIfAlreadyhavePermission(activity, Manifest.permission.CAMERA)){

    }else {
        requestForSpecificPermission(
                activity, Manifest.permission.CAMERA);
    }
}

try the above code it works fine till android 8


text:
Q: How to use Remote Desktop for administration when a policy is set to start a program automatically? On a Windows 2008 R2 server with the Remote Desktop Services role installed, I have used a local group policy to start a program automatically. How do I log into the console session to manage the server using Remote Desktop in this scenario? In other words, how do I log in to manage the server without having the program start? The /admin switch doesn't work. It did when connecting to Windows 2003 Terminal Service servers.

A: Starting the program with Local Group Policy isn't, probably, the best way to do what you're looking for.
In Terminal Services environments generally one uses Loopback Group Policy processing (in either Merge or Replace mode) to apply a set of user policy settings to users logging-on to the Terminal Server computer. For "Administrators", typically one would "Deny" the "Apply Group Policy" right to the GPO containing the settings that aren't appropriate for "Administrator" users (like starting a program automatically on logon).
The Multiple Local Group Policy object (MLGPO) functionality can accomodate what you want, as well, but I discourage people from using it in Domain environments. Generally it's better to put your GPOs in the Directory because, in the future, you may have a different (or multiple) server computers in the Terminal Server role. Using GPOs in the Directory means that you need only put new Terminal Server computers into the correct OU to have them "do the right thing", as opposed to having to manually replicate MLGPO settings "by hand" between machines. (In general, you should only want to do a given thing once...)

A:
I think you are on to something! I set
  the policy in the "Computer" section
  of the local group policy. Having some
  of these settings available in the
  "user" section is new in Server 2008
  (I believe). I'll try changing the
  setting to start the program
  automatically into the user section
  and then I'll try connecting to with
  the /admin switch again

Sorry it took so long to understand, but when you see it, you just soak in all the details, but to me, it was just not coming across.
Yes, now that I had enough information to even understand the problem, I was getting to that. I would make it a user policy, and just move the users, administrator for example, to a different OU, so it is not affected by the policy that starts the program. If you already create a separate OU for your users (I highly recommend this anyway), at least administrator in the default users OU won't have to be touched. Any other users you want to exempt, you should move out too.
I will keep the rest of the answer for reference.
2008 Server no longer supports connecting to the console:
http://support.microsoft.com/kb/947723
http://www.techrepublic.com/blog/datacenter/windows-server-2008-drops-rdp-console-option/434

A: Which version of RDP uses the client you are connecting from? Try to use the /console switch.


text:
Q: convert time to decimal in SQL server 2012 i have a table in sql server 2012, with one of its column having the following data in time datatype,
How would you convert 00:45:00 to 0.45
or 01:45:00 to 1.45 ?
please help.

A: You know that decimal value of 1:45:00 is 1.75h
try this if you want to convert time to decimal
select  datediff(second,0,'01:45:00') / (60.0 * 60.0)

But if you getting value as par your requirement then try this way
select cast(datepart(hour, '01:45:00')+datepart(minute, '01:45:00') / 100.00 as decimal(7,4));

A: You could do arithmetic such as:
 select cast(datepart(hour, col) + datepart(minute, col) / 100.00 as decimal(5, 2));

But as noted in the comments, "1.45" seems quite confusing.  Most people think this should be "1.75".  If you want the latter -- with precision to the minute -- you can do:
 select cast(datepart(hour, col) + datepart(minute, col) / 60.00 as decimal(5, 2));

A: From the question, it seems you only want to remove the ':' with '.'. If so, it can be achieved in many ways in SQL Server 2012. One example is below.
If your column is 'Datetime', use this:
SELECT REPLACE(LEFT(CAST(DatetimeCol AS TIME),5),':',',') FROM Tbl

Else if it just 'Time' then remove the cast.

A: Don't know if this approach can help, but I use a simple one liner for performance monitoring:
CONVERT(DECIMAL(19,3), DATEDIFF(MS, DATEADD(S,0,0), [Duration_tm])/1000.0) AS [Duration_sec]

... turns a TIME to DECIMAL seconds.
Keep in mind though if you substitute a TIME type for DATETIME, the DATEDIFF(MS ... will overflow if that exceeds 24days 20h:31m:23s; i.e. the DATEDIFF return type INT upper limit (roughly)


text:
Q: How to calculate Distance from succesive images Suppose I take an image at one location and after shifting the camera by a fixed distance I take another picture.Is there any way to determine the distance shifted using these two images.?

A: Not without knowing something about the scene you are looking at.  Picture some object.  Now move the object twice as far away from you and double its size. It will look identical to you.  If you now move to the left the object will move to the right but how far it appears to move will depend on how far you moved it away from you.  This effect is called parallax and is what lets you determine the relative depth of objects if you know exactly how far you moved.  Unfortunately it also means that without knowing the depth of what you are looking at you can't know how far you moved.
If you can define the location of some points in world space then it becomes possible.