text:
Q: dynamically set upload_tmp_dir in apache2 I am working on this for hours and its driving me nuts!
so i think its a really tough one hence the detailed question.
The problem is:

*

*I have a server that accepts file post uploads by php script.

*The data will be distributed to several discs.

*I want to save the file to the right disc during upload (tmp file).
Because:

*

*The file needs to be moved later, and i don't want it to take long (copy from the systems tmp directory to target disk)

*The system drive is an ssd that won't be very happy when so much data is written and deleted on it.
This server config changes the init value. during an upload an can see the temp file and see how its filesize increases:
Alias /thundercloud /home/thundercloud
<Directory /home/thundercloud>
    php_admin_value upload_tmp_dir /home/thundercloud/locations/42/tmp
</Directory>

My sripts are in /home/thundercloud and there are several symlinks in /home/thundercloud/locations (named numerically 1-n) that all point to the according mountpoints.
Now what i need is to get the number 42 (which is disk no. 42  - no there are only 14 disks in the server, dis his just for test) to be dynamic.
I have a lot of control over the request so I basically don't care whether its determined by hostname, get variable, subdirectory etc.
So my first attempt was this:
RewriteLock /var/lock/apache2/rewrite.lock
Alias /thundercloud /home/thundercloud
RewriteMap getuplaodlocation prg:/home/thundercloud/uploadloc.php
RewriteEngine On
<Directory /home/thundercloud>
    AllowOverride All
    php_admin_value upload_tmp_dir ${getuplaodlocation:%{THE_REQUEST}}
</Directory>

the corresponding rewrite map was:
#!/usr/bin/php
<?
set_time_limit(0); # forever program!
$keyboard = fopen("php://stdin","r");
while (1) {
    $line = trim(fgets($keyboard)); // dont care for now
    echo '/home/thundercloud/locations/42/tmp'.PHP_EOL;
}

I jut hardcoded 42. if it worked i would have parsed the correct falue from THE_REQUEST . It did not work. the script was chmod 777 and everything.
My next attempt was:
Alias /thundercloud /home/thundercloud
<Directory /home/thundercloud>
    SetEnvIfNoCase Host lionel\.2x\.to upload=/home/thundercloud/locations/42/tmp
    php_admin_value upload_tmp_dir upload
</Directory>

no luck.
so my final attempt was:
Alias /thundercloud /home/thundercloud
<Directory /home/thundercloud>
    php_admin_value upload_tmp_dir /home/thundercloud/locations/%{REMOTE_HOST}/tmp
</Directory>

no luck either. i printed ini_get_all() and got the following output:
["upload_tmp_dir"]=>
  array(3) {
    ["global_value"]=>
    string(47) "/home/thundercloud/locations/%{REMOTE_HOST}/tmp"

so obviously this "constant" isn't available like this in this scope
now i ran out of ideas
i must admin my apporaches are really trial and error.
anyony can point me in the right direction or tell me its not possible and justify that?
ps: it obviously doesnt work at php runtime ;)
edit:
Ok after some more hours and a useful comment from Marc B I came up with this "solution":
<VirtualHost *:80>
    ServerName 42.thundercloud.lionel.2x.to
    DocumentRoot /home/thundercloud
    php_admin_value upload_tmp_dir /home/thundercloud/locations/42/tmp
</VirtualHost>
<VirtualHost *:80>
    ServerName 43.thundercloud.lionel.2x.to
    DocumentRoot /home/thundercloud
    php_admin_value upload_tmp_dir /home/thundercloud/locations/43/tmp
</VirtualHost>

Just brute force an own VirtualHost container for every disk... its ugly and I hoped to avoid that step and have a generic webserver config, but it seems like the only way to go - atleast it works.
I still wonder whether theres a nicer way and i think its very interesting to go so deep into webserver configurations. Apache is incredibly flexible and its getting really interesting when you push it to the limits (thats at least what i think).
Thats why I will leave this question open and put a bounty on it.
edit:
After some more research I think there might be a solution applying the techniques here:
http://httpd.apache.org/docs/2.0/vhosts/mass.html
something like:
<VirtualHost *>
Use CanonicalName off
VirtualDocumentRoot /home/thundercloud/locations/%0/tmp/
php_admin_value open_basedir VIRTUAL_DOCUMENT_ROOT
<VirtualHost>

This is just an idea, not tested yet. still trying to figure it out. The paths are not correct in this case but there might be a workaround with symlinks. Would be nice if some1 could point me in the right direction.

A: There's no way to use variable substitution in php_admin_value settings. This is just because apache modules can only parse their own config directives. mod_rewrite supports using environment variables because doing so is built into mod_rewrite itself.
Because you can't use variables, you'll have to set up all of the possible values using something like <Location>'s. For example:
RewriteEngine on
RewriteRule /upload(\d+)$       /upload.php

php_admin_value upload_tmp_dir /tmp

<Location /upload1>
    php_admin_value upload_tmp_dir /tmp/1
</Location>
<Location /upload2>
    php_admin_value upload_tmp_dir /tmp/2
</Location>
....
<Location /upload100>
    php_admin_value upload_tmp_dir /tmp/100
</Location>

Then you just post to /upload{$id}. This is obviously not as nicely dynamic as it would be if substitution were possible. There are 2 obvious alternatives to make it neater:
1) Have a separate build script which generates a file to put in /etc/httpd/conf.d with the relevant lines for each server
2) Create a universal config file which simply has e.g. the 100 location rules. On each server, you'd then just need to set up the symlinks you wanted and have the PHP which generates the form decide which volume to point the upload at - you'd end up with a bunch of /uploadX urls that wouldn't work on each server, but nothing would post there anyway.
The alternative is to use mod_macro, which basically lets you do the same as above but with a smaller config file, generating the expanded config automatically, but still essentially just generating a big config file with lots of vhost/location blocks. To do it as nicely as you original asked, you've need to modify mod_php.

A: If i understood the question correctly, you can always use ini_set
ini_set ("upload_tmp_dir", "/home/thundercloud/locations/42/tmp");


text:
Q: Select textbox on form load in C# I need to give the focus to a specific textbox when the application is launched.
I'm using this piece of code:
private void myForm_Load(object sender, EventArgs e)
{
    myTextbox.select()
}

It actually works. But is this the correct way to achieve my goal?

A: Use it like this:
mytextbox.Focus();

Or you can set the tab index on that text box to 0.

A: TextBox1.Focus() is the best way to select a Textbox in a Windows Forms application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with translation in ASP.NET Core via ASP.NET Core localization in _Layout.cshtml I am trying to learn programming in ASP.NET Core by making simple programs, but I got stuck with translating some parts of texts by using a localization feature.
For example, I created Resources and folders with all needed resource files with translated words and phrases. For _Layout.cshtml i created Resources -> Views -> Shared -> _Layout.en.resx and _Layout.fr.resx
I tried to use this type of code but it doesn't work, the page is loading but when I change the culture from en to fr the words in _Layout don't change, only what I get is the words write in @localizer quotes in both languages.
The code in _Layout is the same as yours.
The differences in Startup.cs:
In ConfigureServices:
services.AddLocalization(opt => { opt.ResourcesPath = "Resources"; });
services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).AddDataAnnotationsLocalization();
        services.Configure<RequestLocalizationOptions>(
            opt =>
            {
                var supportCulteres = new List<CultureInfo>
                {
                    new CultureInfo("en"),
                    new CultureInfo("fr")
                };
                opt.DefaultRequestCulture = new RequestCulture("en");
                opt.SupportedCultures = supportCulteres;
                opt.SupportedUICultures = supportCulteres;
            });

In Configure i add only that code:
app.UseRequestLocalization(app.ApplicationServices.GetRequiredService<IOptions>().Value);
I made this to work this file _Culture.cshtml (problem with adding code)
https://i.stack.imgur.com/WV9pn.jpg
And I got side like this:
https://i.stack.imgur.com/1vRWE.jpg
And after changing the language (in this example i have polish language but normally it is french)
https://i.stack.imgur.com/Fbn8j.jpg

A: Here is a whole working demo:
1.Add resource file in Resources/Views/Shared folder in root project:

2.Edit your resource file(_Layout.fr.resx) like below:
Note:Be sure you have added the correct value for key(Home,Privacy,Book List.Book List contains space).

3.Create _Culture.cshtml:
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var culture = Context.Features.Get<IRequestCultureFeature>();
    var cultureList = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}

    <form asp-controller="Home" asp-action="CultureManagement"
          asp-route-returnUrl="@returnUrl" method="post">
        <select name="culture" asp-for="@culture.RequestCulture.UICulture.Name" asp-items="cultureList"
                onchange="this.form.submit();" >
        </select>
    </form>

4.Change your _Layout.cshtml like below:
@inject Microsoft.AspNetCore.Mvc.Localization.IViewLocalizer localizer

<!DOCTYPE html>

    //...

                MvcCore3_1
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">

                </button>

                            @localizer["Home"]

                            @localizer["Privacy"]

                    //add the partial here
                    @await Html.PartialAsync("_Culture")

            @RenderBody()

            © 2020 - MvcCore3_1 - Privacy

    @RenderSection("Scripts", required: false)

5.Be sure add AddViewLocalization in your Startup.cs like below:
Note: It should be:app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>() not app.ApplicationServices.GetRequiredService<IOptions>().
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddControllersWithViews()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

        services.Configure<RequestLocalizationOptions>(
         opt =>
         {
             var supportCulteres = new List<CultureInfo>
             {
                new CultureInfo("en"),
                new CultureInfo("fr")
             };
             opt.DefaultRequestCulture = new RequestCulture("en");
             opt.SupportedCultures = supportCulteres;
             opt.SupportedUICultures = supportCulteres;
         });

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        var options = app.ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(options.Value);

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

    }

6.Controller:
[HttpPost]
public IActionResult CultureManagement(string culture, string returnUrl)
{
    Response.Cookies.Append(
        CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
    );

    return LocalRedirect(returnUrl);
}

Result:


text:
Q: Run python script in Django and produce live output buffer on the web I am a beginner to Django web framework. I have a bunch of python scripts which runs and produce output on cli at present but I want the same scripts to run from django web and display live buffer output
Can anyone shed some light on how to achieve it

A: "Live" output will not be possible without using a more advanced technique or some JS. To get you started, execute the Python code in the view and then pass the results to a template to render them for the user (or as plain HttpResponse).
Have a look at the official docs to get you started if you are a total beginner: https://docs.djangoproject.com/en/4.1/intro/tutorial03/#write-views-that-actually-do-something


text:
Q: Periodic solutions to Riccati equations Suppose $\alpha, L>0.$ Under what conditions (between $\alpha, L$) the Riccati equation
$d\Phi/dz=2i[\Phi(z)^2+\alpha Cos(2\pi z/L)\Phi(z)+1]$
can have a periodic solution with period  $L$ (under the initial assumption of $\Phi(0)=0$)?


text:
Q: Meaning of symbol ^ in Objective C
Possible Duplicate:
Caret in objective C
What does this ^ syntax mean in Objective-C?

I am tired by searching the meaning of symbol ^ in Objective C. I have seen it in lot of projects especially in back ground running tasks. I will put a link
http://developer.apple.com/library/ios/#samplecode/StitchedStreamPlayer/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010092
and in MyStreamingMovieViewController.m you can find the following inside - (IBAction)endScrubbing:(id)sender method.
timeObserver = [[player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(tolerance, NSEC_PER_SEC) queue:dispatch_get_main_queue() usingBlock:
                         ^(CMTime time)
                         {
                             [self syncScrubber];
                         }] retain];
    }

Also http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication*    app = [UIApplication sharedApplication];

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    // Clean up any unfinished task business by marking where you.
    // stopped or ending the task outright.
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // Do the work associated with the task, preferably in chunks.

    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
});
}

Please let me know the answer.

A: From the second page of Apple's Blocks Programming Topics:

You use the ^ operator to declare a block variable and to indicate the beginning of a block literal. The body of the block itself is contained within {}, as shown in this example (as usual with C, ; indicates the end of the statement):

A: That symbol is used to declare block.Blocks are addressable sections of code implemented inline (inside other functions). The inline-edness can be convenient but the real reason why blocks are different to regular functions and function pointers is that they can reference local variables from the scope of the function surrounding their implementation without the invoker of the block needing to know of the surrounding scope variables' existence.
How blocks are implemented (and the consequences)

A: That symbol is used to declare block.
For more information read here Blocks Programming Topics
Some more info:

Block objects are a C-level syntactic and runtime feature. They are
  similar to standard C functions, but in addition to executable code
  they may also contain variable bindings to automatic (stack) or
  managed (heap) memory. A block can therefore maintain a set of state
  (data) that it can use to impact behavior when executed.
You can use blocks to compose function expressions that can be passed
  to API, optionally stored, and used by multiple threads. Blocks are
  particular useful as a callback because the block carries both the
  code to be executed on callback and the data needed during that
  execution.


text:
Q: Omnet++ Question: Using Standard Container Classes for Fields of abstract L3Address SlectedNodes[]; // will use std::vector? I want to use Standard Container Classes for Fields of abstract L3Address SlectedNodes[]; // will use std::vector? I have made the following message declaration:
enter code here
packet PacketData {
@customize(true);
abstract L3Address SlectedNodes[]; // will use std::vector<L3Address >
}

In the generated C++ code i write the following C++ file :
#include <iostream>
#include <sstream>
#include "PacketData_m.h"
class PacketDataPacket : public PacketData_Base
{
protected:
std::vector<L3Address> SlectedNodes;// SlectedNodes= SlectedNodes
// helper method
void unsupported() {throw cRuntimeError("unsupported method called");}
public:
// SlectedNodes methods
virtual L3Address getSlectedNodes(unsigned int k) {return SlectedNodes[k];}
virtual void setSlectedNodes(unsigned int k, const L3Address& SlectedNodes)
{SlectedNodes[k]=L3Address& SlectedNodes;}
virtual void addSlectedNodes(const L3Address& SlectedNodes)
{SlectedNodes.push_back(L3Address& SlectedNodes);}
virtual void setSlectedNodesArraySize(unsigned int size)
{SlectedNodes.resize(size);}
virtualL3Address getSlectedNodesArraySize() const {return
SlectedNodes.size();}
};
Register_Class(PacketData);

Some additional boilerplate code
 PacketData_Base::PacketData(const char *name=nullptr, int kind=0)
:PacketData_Base(name,kind) {
}
PacketData_Base:: PacketData(constPacketData& other)
:PacketData_Base(other.getName()) {
operator=(other);
}
PacketData& operator=(const PacketData& other) {
if (&other==this) return *this;
PacketData_Base::operator=(other);
 SlectedNodes = other.SlectedNodes;
}
virtualPacketData *dup() {
 return newPacketData(*this);
}

Is this use of standard container classes (STL) as fields, but of
std::vector< L3Address> IntVector; is true? is there any wrong?


text:
Q: Suppose $a_n \ge 0$ for all n and that $\sum_{n=1}^{\infty} (a_n)^2$ converges, does the $\sum_{n=1}^{\infty} a_n$ also converge? I don't think so, but I'm not sure as to how to prove this so. A counterexample I can think of is for $a_n = \frac{1}{n}$, here $a_n \ge 0$ for all n and its infinite series when squared does converge. But $a_n$ does not converge, it diverges.

A: No. Consider the counter-example that $a_n = \frac{1}{n}$.


text:
Q: Some detail in the proof of the mean value formulae for harmonic functions Let

*

*$B_r(x_0)$ and $\overline{B}_r(x_0)$ be the open and closed ball in $\mathbb{R}^n$, respectively

*$u\in C^2(B_r(x_0))$ and $\rho\in (0,r)$

*$\lambda_n$ be the Lebesgue-measure on the Borel-$\sigma$-algebra on $\mathbb{R}^n$

*$S_M$ denote the "surface measure" on a submanifold $M$

I've read in a book that we've got $$\int_{B_\rho(x_0)}\Delta u\;d\lambda_n=\int_{\partial B_\rho(x_0)}\frac{\partial u}{\partial\nu}dS_{\partial B_\rho(x_0)}\color{red}{\stackrel{(1)}{=}\int_{\partial B_1(0)}\frac{\partial u}{\partial\rho}(x_0+\rho\omega)\rho^{n-1}\;d\omega}$$
where $\nu$ is the "outer normal field" of $B_\rho$. How can we prove the right equation?

I've tried the following: Let $$\phi:\partial B_\rho(x_0)\to\partial B_1(0)\;,\;\;\;x\mapsto\frac{x-x_0}\rho .$$ Moreover, let $$F:\partial B_\rho(x_0)\to\mathbb{R}\;,\;\;\;x\mapsto\frac{\partial u}{\partial \nu}(x)$$ and $$f:\partial B_1(0)\to\mathbb{R}\;,\;\;\;\omega\mapsto F(x_0+\rho\omega) .$$ Obviously, we've got $F=f\circ\phi$ and thereby $$\int_{\partial B_\rho(x_0)}F\;dS_{\partial B_\rho(x_0)}=\int_{\partial B_1(0)}f\;d\left(S_{\partial B_\rho(x_0)}\circ\phi^{-1}\right)\tag{2}$$ where $S_{\partial B_\rho(x_0)}\circ\phi^{-1}$ is the pushforward measure. Now, that doesn't look too bad. We may need to notice that $$\nu(x)=\frac{1}{\rho}(x-x_0)\;\;\;\text{for all }x\in\partial B_\rho(x_0) .$$ So, $$\nu\left(\phi^{-1}(\omega)\right)=\omega\;\;\;\text{for all }\omega\in\partial B_1(0) .$$ Hence, $$\frac{\partial u}{\partial\nu}\left(\phi^{-1}(\omega)\right)=\langle\nabla u\left(\phi^{-1}(\omega)\right),\nu\left(\phi^{-1}(\omega)\right)\rangle=\langle\nabla u(x_0+\rho\omega),\omega\rangle\;\;\;\text{for all }\omega\in\partial B_1(0)$$

I've got stuck at this point. How can we use the last equation in $(2)$ to achieve $(1)$? Please note, that I'm not familiar with the notation "$d\omega$". I assume that it is exactly the pushforward measure $S_{\partial B_\rho(x_0)}\circ\phi^{-1}$, but I may be wrong.

A: The notation $d\omega$ is being used for the standard (hyper)area measure on the unit sphere $\partial B_1$. The pushforward measure is in fact $d\left(S_{\partial B_\rho (x_0)} \circ \phi^{-1}\right) = \rho^{n-1} d\omega$, since the scaling $x \to \rho x$ scales hyperareas by $\rho^{n-1}$ and the translation leaves them invariant.
Thus the only missing piece is $$f(\omega) = \frac{\partial u}{\partial \nu} (x_0 + \rho \omega) = \frac{\partial}{\partial \rho} u(x_0 + \rho \omega),$$
which follows from the fact that the outwards derivative $$\frac{\partial u}{\partial \nu} (x_0 + \rho \omega) = \langle \nabla u(x_0 + \rho \omega), \omega\rangle$$ is simply $\partial/\partial \rho$ in spherical coordinates.


text:
Q: Get all the numbers on the start of the line in output from grep hello I am writing a news downloader from command line for calibre (calibre-ebooks.com) the script gets the id of an ebook from calibre DB using this command
 calibredb list --with-library '/mediacenter/media/Książki' | grep --line buffered "Benchmark.pl" | cut -c 1

but it works only for id 1-9
tried searching on the web and experimenting myself but I can't find anything
if you wonder how the output from calibredb looks like:
uniqueid name         date                 author
10       Benchmark.pl [pią, 24 mar 2017]   calibre

(i need that first unique id)

A: I suspect you would be better off with awk if you want to find lines that start with digits and contain "Benchmark":
calibredb ... | awk '/^[0-9]+/ && /Benchmark/ {print $1}'

Or, if you like grep:
calibredb ... | grep "Benchmark" | grep -Eo "^[0-9]+"


text:
Q: How to control the access of AWS secret manager Suppose I am an AWS Superuser who has all AWS permissions.
I have configured AWS glue including the connection to a database using username and password.
I have stored the username and password in AWS secret manager, the glue's ETL job script will connect database using this information and then run the ETL job.
ETL Data engineers do not have super user permission. But they know how to write the details of the ETL job script. And the script needs to retrieve the secret info first, which means engineers can write code to print out the password… and we have a lot of Data engineers…
My question is: what is the right strategy to control the password access of the secret manager?
1) Shall we allow ETL data engineers to update script to glue and run it? then they can see the password, or
2) Shall we only allow them to write ETL script, but let superuser to update the script to glue after reviewing the code? or
3) Do we have a way to separate the ETL job script code and get_password code?
Note, I know How to use IAM, tags to control secret manager. But my question is different.


text:
Q: how to refer to the next item in a list and compare it to the item before it? I have a homework question where it asks to make an algorithm which would go through every element in the list and see if the number beside it is greater than the current number or not. If it is not greater than the current number, then the counter will go up by 1, if it is greater the counter will stay where it is.
I got it to work but it only works if there are more than 3 items in the list.
Here's what I have so far:
def count(items):

if len(items) == 0:
    return 0

else:
    count = 0
    for i in items:
        count += 1
        items1 = items[i:]
        items2 = items[i+1:]

        if items1 > items2:
            return count - 1

print (count([42, 7, 12, 9, 2, 5])) #returns 4. works but does not work if len < 3
print (count([])) #returns 0. works
print (count(list(range(10**7))))  # supposed to print out 1 since it's only 1 number, but it just gets stuck and doesn't finish the rest of the program
print (count([99])) # prints out none
print (count(list(range(10**7,0,-1))))# supposed to print out 10000000 but prints 1 instead

Any kind of help or suggestions would be greatly appreciated.

A: If you have 0 or 1 elements - return 0.
You have to iterate over the length of the array, not over the elements themselves. There is a difference between:
for i in array and for i in range(0,len(array))
Be careful with the range - open a console and type python. Check what range(10**2) prints. It is not one element.
https://www.w3schools.com/python/ref_func_range.asp
def count(items):

    if len(items) == 0 or len(items) == 1:
        return 0
    else:
        count = 0
        for i in range(0,len(items)-1):
            items1 = items[i]
            items2 = items[i+1]

            if items1 > items2:
                count = count + 1
        return count

A: In general

def count_next_test(numbers, test_fn):
  count = 0
  last = len(numbers) - 1
  for i, n in enumerate(numbers):
    if i < last:
      if test_fn(n, numbers[i+1]):
        count += 1
  return count

In your case:  count_next_test(numbers, lambda a, b: a < b)
You could also do something like
pairs = zip(numbers, numbers[1:])
len([(a,b) for a,b in pairs if a < b])


text:
Q: Is there away to allocate memory to a long string in python? I am working with strings that are recursively concatenated to lengths of around 80 million characters.  Python slows down dramatically as the string length increases.
Consider the following loop:
s = ''
for n in range(0,r):
  s += 't'

I measure the time it takes to run to be 86ms for r = 800,000, 3.11 seconds for r = 8,000,000 and 222 seconds for r = 80,000,000
I am guessing this has something to do with how python allocates additional memory for the string.  Is there a way to speed this up, such as allocating the full 80MB to the string s when it is declared?

A: When you have a string value and change it in your program, then the previous value will remain in a part of memory and the changed string will be placed in a new part of RAM.
As a result, the old values in RAM remain unused.
For this purpose, Garbage Collector is used and cleans your RAM from old, unused values But it will take time.
You can do this yourself. You can use the gc module to see different generations of your objects See this:
import gc
print(gc.get_threshold())

result:
(596, 2, 1)

In this example, we have 596 objects in our youngest generation, two objects in the next generation, and one object in the oldest generation.
For this reason, the allocation speed may be slow and your program may slow down
use this link to efficient String Concatenation in Python
Good luck.

A: It can't be done in a straightforward way with text (string) objects, but it it is trivial if you are dealing with bytes - in that case, you can create a bytearray object larger than your final outcome and insert your values into it.
If you need the final object as text, you can then decode it to text, the single step will be fast enough.
As you don't state what is the nature of your data, it may become harder - if no single-byte encoding can cover all the characters you need, you have to resort to a variable-lenght encoding, such as utf-8, or a multibyte encoding, such as utf-16 or 32. In both cases, it is no problem if you keep proper track of your insetion index - which will be also your final datasize for re-encoding. (If all you are using are genetic "GATACA" strings, just use ASCII encoding, and you are done)
data = bytearray(100_000_000) # 100 million positions -
index = 0
for character in input_data:
    v = character.encode("utf-8")
    s = len(v)
    if s == 1:
        data[index] = v
    else:
        data[index: index + len(v)] = v
    index += len(v)
data_as_text = data[:index].decode("utf-8")


text:
Q: Context aware Items of Comboxbox in DataGrid Got a DataTemplateColumn in a DataGrid of a WPF application.
DataTemplate defines a ComboBox.
The list of items presented by the ComboBox needs to change based on the value of another field of bound ItemsSource for the same row that the ComboBox is in. I'm not using a ComboBoxColumn and cant for other reasons.
Currently have tried Binding the ItemsSource of the ComboBox to an ObjectDataProvider in the xaml, and then setting the MethodParameter of the ObjectDataProvider in the SelectionChanged event handler of the DataGrid.
The Combobox items in respective rows update correctly when selected, however all other ComboBoxes rendered update also. Which causes the selected item of a previously set ComboBox in the previous row to clear. I suspect the other ComboBoxes update because they receive an PropertyChanged event from the ObjectDataProvider to which they are all bound.
I tried setting the Binding Mode on the ItemsSource of the ComboBox to OneTime, but that did not help.
Any ideas on how to get the ComboBox to bind its Items when the DataGrid Row is selected, but not to rebind when another row (and subsequent ComboBox) is selected ?

A: Added an additional IEnumerable property to the DataGrid bound Entity collection (plus logic to generate the items) and then Databound the ItemsSource of the ComboBox to that.
In My case I did not need to add a property to bind the Selecteditem to as I was already binding the SelectedValue and Text properties of the ComboBox.


text:
Q: Awesomium not loading HTTPS web application This is what I have in my WPF application, I am using the Awesomium web browser control along with MVVM and Caliburn.Micro.
In my ShellViewModel I have the following code in the OnViewReady method
        if (!WebCore.IsInitialized)
        {
            WebCore.Initialize(
                new WebConfig()
                {
                    HomeURL = "http://www.ic24.org.uk".ToUri(),
                    LogPath = Path.Combine(@"C:\Users\nstevens\AppData\Local\IC24\Cleo", "logs"),
                    LogLevel = LogLevel.Verbose
                });
        }

        webControl = new WebControl
                             {
                                 Source = "https://newcleodev.sehnp.nhs.uk/".ToUri(), // this is a locally hosted web application
                                 WebSession =
                                     WebCore.CreateWebSession(
                                         @"C:\SessionDataPath",
                                         new WebPreferences
                                             {
                                                 WebSecurity = false,
                                                 AllowInsecureContent = true
                                             })
                             };
        webControl.WebSession.ClearCache();
        webControl.BorderThickness = new Thickness(0, 0, 0, 0);
        webControl.Margin = new Thickness(0, -4, 0, 0);
        webControl.ShowContextMenu += webControl_ShowContextMenu;
        webControl.ConsoleMessage += (sender, args) => Debug.WriteLine(args.Message);
        webControl.Crashed += (sender, args) => Debug.WriteLine(args.Status);
        webControl.LoadingFrame += this.webControl_LoadingFrame;
        webControl.LoadingFrameComplete += this.webControl_LoadingFrameComplete;
        webControl.CertificateError += (sender, args) =>
            {
                args.Handled = EventHandling.Default;
                args.Ignore = true;
            };

        WebCore.ResourceInterceptor = new CustomResourceInterceptor
                                          {
                                              RequestEnabled = true,
                                              Headers =
                                                  new Dictionary<string, string>
                                                     {
                                                          {
                                                              "theme",
                                                              shellView
                                                              .SelectedItem
                                                              .StyleSheet
                                                          }
                                                      }
                                          };

        this.documentPanel = new DockPane { Header = "NHS Confidential: Personal data about a patient", Content = webControl };

        this.dockingManager.AddDocument(this.documentPanel);

        webControl.DocumentReady += WebViewOnDocumentReady;

When I run the application I am not getting the web application loading in the browser control, I have tried accessing the Uri above in Internet Explorer and Chrome and the application loads in both, I have also tried different Uri's in the browser control and they all work.
I am really struggling with this specific Uri, the only issue that I have seen is that when i loaded this Uri in Chrome I get prompt to accept the client certificate (a dialog comes up with the root certificate listed)
I would like a sanity check that the code below is correct and I have not done anything wrong, also would like to know what the issue is, the contents of the log file are
[0807/143423:INFO:(0)] WebCore is now online.
[0807/143423:INFO:(0)] Running Awesomium 1.7.5.0
[0807/143423:INFO:Awesomium.NET(0)] Registering Javascript Callbacks

Nothing else gets output to either the log or the Output window in VS.
EDIT: I have checked the values of the LoadingFrameEventArgs and see no issues there, there are no SSL errors, the LoadingFrame event is fired but nothing else, I am really stuck with this!!


text:
Q: Class AppDelegate: UIResponder, UIApplicationDelegate Thread 1: signal SIGABRT I started working on app development tutorials from today and already started facing hard to deal bug. I know it may be easy for pro developers, but not for me.
The simple app I made is - To Do List
Under new project -> Tabbed Application - > Swift -> iPhone
This is the code for second view controller,
    import UIKit

class SecondViewController: UIViewController {
var toDoItems:[String] = []

    @IBOutlet weak var toDoItem: UITextField!

    @IBAction func addItem(sender: AnyObject) {

        toDoItems.append(toDoItem.text)

        println(toDoItems)

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

I am sick of this SIGABRT problem. Other people are using the exact same code that I am and there program is working perfectly fine. Not sure why I am having this issue.
I tried the following:

*

*Clear the cache

*Restarted the Xcode multiples times

*Redid the complete code again saving as a completely different file
I am using the following:

*

*xcode 6.0.1 (6A317)

*OS Yosemite

*I have a developer account

A: I had the same exact error and I know it is frustrating, but it is absolutely dumb.
The problem is with an outlet. Maybe you deleted the line of code and/or replaced it, but the link still exists.
In your main.storyboard check all the outlets, control+(click on outlet) and check if it is linked to something.
Once you correct that it should run with no problems.


text:
Q: SSL causing CORS issue when fetching data from Strapi back-end on nginx VPS I have created a mock e-commerce store using React. The back-end is built using Strapi.
I have deployed the Strapi backend to an nginx VPS running on ubuntu.
When I attempt to fetch the data from my mock e-commerce store domain, let's call it mymockstore.com I am only able to fetch the data successfully when there is no SSL certificate.
If I fetch from http://mymockstore.com everything works as expected.
If I install an SSL certificate on my domain and attempt to fetch from https://mymockstore.com I receive a CORS issue in the console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
https://194...**/api/products?populate=*&[filters][type][$eq]=featured.
(Reason: CORS request did not succeed). Status code: (null).

The Strapi cors middleware config file defaults to Access-Control-Allow-Origin: ['*']
My /etc/nginx/sites-available/api file currently looks like this:
server {
  listen 80;

  location / {
        proxy_pass http://localhost:1337;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
  }
}

It is a project on my first developer portfolio website and I'll use the work-around of removing the SSL but it would be great to figure this problem out.
Please let me know if you have any ideas on what could solve this?
Thanks in advance!


text:
Q: TextBox OnClick event without Javascript I have a textbox which I want it to be fired on Click. I read some forum in which I wrapped in LinkButton. Here is my mockup UI part:
 <asp:LinkButton runat = "server" OnClick = "txtAgentName_TextChanged"><asp:TextBox ID="txtAgentName" runat="server"></asp:TextBox></asp:LinkButton>

And this is my code behind:
  protected virtual void txtAgentName_TextChanged(object sender, EventArgs e)
    {

    }

And it seems like it is not firing up! I dont want to use Javascript :-P

A: the asp textbox control does not have a server side click event. "OnClick" renders an html "OnClick" attribute for the textbox. Your code will result in a javascript error.
your best bet is to do an ajax call to a WebMethod when the textbox blur event is fired and do something to the textbox based on the result. this article will help you with the webmethod call. using jquery you can handle the blur event pretty easily.


text:
Q: Convert C# sha256 hashing to PHP equivalent I need to convert some C# code into a PHP equivalent to work with a SOAP web API. All of their examples are in C#. I think I have the equivalent PHP function, but my SOAP requests are returning either 'Bad Request' or 'Unauthorized - Invalid API Key' - while the example page on the API page works with my keys and the request URLs look the same sans the digest message being passed. The API and client ID are definitely correct.
Here is the C# code:
private string GenerateDigest(long currentTime)
    {
        SHA256Managed hashString = new SHA256Managed();
        StringBuilder hex = new StringBuilder();
        byte[] hashValue = hashString.ComputeHash(Encoding.UTF8.GetBytes(String.Format("{0}{1}", currentTime, txtApiKey.Text)));

        foreach (byte x in hashValue)
        {
            hex.AppendFormat("{0:x2}", x);
        }

        return hex.ToString();
    }

Here is the PHP function I wrote to try to do what C# is doing:
public static function generateDigest($api_key) {
  return hash('sha256', time() . mb_convert_encoding($api_key, 'UTF-8'));
}

I am not very fluent in C# so I assume where I am going wrong is where it is doing hex.AppendFormat(). I am not sure what this is supposed to be in PHP. The end result is a hash that is appended to a URL to generate a SOAP request, like this:
https://payments.homeaway.com/tokens?time=1387385872013&digest=1bd70217d02ecc1398a1c90b2be733ff686b13489d9d5b1229461c8aab6e6844&clientId=[redacted]
Edit:
Here is the currentTime variable being passed in C#.
// Request validation setup
TimeSpan timeSinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
long currentTime = (long)timeSinceEpoch.TotalMilliseconds;
string digest = GenerateDigest(currentTime);

A: I've the same problem coverting this to php code here's my code to solve the problem :
 function generateDigest($time, $api_key) {
    $hash = hash('sha256', $time . mb_convert_encoding($api_key, 'UTF-8'), true);
    return $this->hexToStr($hash);
}

function hexToStr($string){
    //return bin2hex($string);
    $hex="";
    for ($i=0; $i < strlen($string); $i++)
    {
        if (ord($string[$i])<16)
            $hex .= "0";
        $hex .= dechex(ord($string[$i]));
    }
    return ($hex);
}

A: If anyone is looking for this the answer has to do with time. PHP's time() function returns time in seconds where the call in C# returns milliseconds.
Therefore, the correct way to get $currentTime is
$currentTime = time() * 1000;

This has been tested with the API.


text:
Q: Harmonic functions proofs
a.) Show that if $v(x,y)$ is a harmonic conjugate of $u(x,y)$ in a
  domain $D$, then every harmonic conjugate of $u(x,y)$ in $D$ must be
  of the form $v(x,y)+a$, where $a$ is a real constant.
b.) Suppose that $f(z)$ is analytic and nonzero in a domain $D$. Prove
  that $ln|f(z)|$ is harmonic in $D$.

I know initutively why a is true, I also know that I must use Cauchy-Riemann equations to prove it but I do not know how to apply it correctly. For b, I am stumped.

A: (a)
Let $w$ be another such harmonic conjugate and so $z = u(x,y) + i w(x,y)$ where both $u$ and $w$ are real functions.  $u_x = w_y$ so $u = \int w_y dx + C(y)$ where $C(y)$ is a pure real function of $y$.
Similarly, $u_y = -w_x$ so $u = -\int w_x dx + D(x)$ where $D(x)$ is a pure real function of $x$.
You know one possible antiderivative corresponding to $\int w_y dx$ and $-\int w_x dx$ already, namely $v(x,y)$ and so $C(y) = D(x)$.  This is only possible when $C(y) = D(x) = a$, with $a$ a real constant.
(b)
$\ln f(z) = \ln|f(z)| + i \arg z$ and so it is the real part of an analytic function and so it is harmonic.  I don't know if you're expected to do more than this


text:
Q: Android http post works with string but not xstream I'm making a droid app that uses a web service.  I have it working when I pass in a string, but when I try and use Xstream it doesn't work.  I have printed out the xml strings from both the Xstream and my own and they are identical.  Without xstream it looks like this and works
`HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g6/login.php");
        Boolean response = false;
        try
        {

            String test = "<Login>" +
                    "<password>" + "lernrane" + "</password>" +
                    "<user_name>" + "jake@jake.com" + "</user_name>" +
                    "</Login>";

            StringEntity se = new StringEntity(test,
                    HTTP.UTF_8);
            se.setContentType("text/xml");
            httppost.setEntity(se);
            System.out.println("MADE IT TO RESPONSE");
            HttpResponse httpresponse = httpclient.execute(httppost);
            HttpEntity resEntity = httpresponse.getEntity();
            String resp = EntityUtils.toString(resEntity);
            System.out.println(resp);
            response = convertToBool(resp);`

But when I use xstream it looks like this and fails
HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g6/login.php");
        Boolean response = false;
        try
        {
            LoginObject login = new LoginObject();
            login.setUserName("jake@jake.com");
            login.setPassword("lernrane");
            XStream xstream = new XStream();
            xstream.alias("Login", LoginObject.class);
            String xml = xstream.toXML(login);
            System.out.println(xml);

            StringEntity se = new StringEntity(xml,
                    HTTP.UTF_8);
            se.setContentType("text/xml");
            httppost.setEntity(se);
            System.out.println("MADE IT TO RESPONSE");
            HttpResponse httpresponse = httpclient.execute(httppost);
            HttpEntity resEntity = httpresponse.getEntity();
            String resp = EntityUtils.toString(resEntity);
            System.out.println(resp);
            response = convertToBool(resp);

My web service looks like this
 $dom = new domDocument;
 $dom = simplexml_load_file('php://input');
 $xml = simplexml_import_dom($dom);
 $user = Users::find_by_user_name($xml->user_name);

 if($user)
 {
if($user->password == $xml->password)
{
    echo "TRUE";
}
 }
 else
     echo "FALSE";

Ignore the odd looking query, I am using active record and I know it works correctly...thanks

A: I figured it out... When I printed out my xml user_name looked like this user__name eventhough it was clearly named user_name.  There must be some type of char set conflict so I just renamed it without the underscore.


text:
Q: How to make a temperature selector in html with css and javascript? I want to achieve a similar effect to this how could I achieve this in HTML with CSS and javascript?
<button onclick="addTemp()">ᐱ</button>
<input id="TempBox" value="15" type="text">
<button onclick="remTemp()">ᐯ</button>

I also want to make it so that if it surpasses 28 to say MAX on the next click and if it goes below 15 to make it say MIN.
Also I don't know how to achieve that look with css, the buttons to set the temperature higher or lower can be any size, but the maximum the entire thing can be is 120px high.
Logically the javascript doesn't work as I don't know how to implement it to work :/
Thanks in advance!

P.S if needed/if you want to, use JQuery

A: First, setting the .innerHTML property of an <input> element has no effect. You should be changing the value:
document.getElementById("TempBox").value = ...

Second, since the value is a string, using the + operator will cause the result to be concatenated, not added numerically. You must first turn the value into a number, before adding (or subtracting) 1 to it:
Number(document.getElementById("TempBox").value)

Alternately:
parseInt(document.getElementById("TempBox").value)

So your addTemp() function would become:
function addTemp() {
    document.getElementById("TempBox").value = Number(document.getElementById("TempBox").value) + 1;
}

You are then left with the task of adding the event handlers. Without jQuery, here is one way:
document.querySelector('button').click = addTemp;
document.querySelector('button:nth-of-type(2)').click = remTemp;

As for making it say "MAX" or "MIN" when you are at the limits, that's probably not the best UX since how does the user know what value was selected as the max or min? Also, by putting a string in a field that should hold a number, you are making it more difficult to parse and then turn into the corresponding number. It would be better to put the MIN/MAX warning outside the <input> field. Here is how I would add that logic:
function addTemp() {
    document.getElementById("TempBox").value = Math.Min(28, Number(document.getElementById("TempBox").value) + 1);
    if (document.getElementById("TempBox").value >= 28) {
        // Alert the user that they are at the max
    }
}

A: Added the basic working functionality & styling to increase & decrease the temperature, further you can explore & try to add more functionality and try to make it yourself,
Here is the Demo for your ref:

const maxTemp=28,
minTemp =15;

let tempBox = document.getElementById("TempBox");
let tempValue=  Number(tempBox.value);

function addTemp() {
  if(maxTemp > tempValue){
    tempValue += 1;
    tempBox.value = tempValue;
  }
}

function remTemp() {
  if(minTemp < tempValue){
    tempValue -= 1;
    tempBox.value = tempValue;
   }

}
.temp-selector{
  height:120px;
  width:80px;
  background-color:#000;
  position:relative;
}
button {
width:100%;
height:30px;
background-color:#000;
border:none;
color:#fff;
font-size:20px;
cursor:pointer;
}

input{
width:100%;
height:60px;
background-color:#000;
border:none;
color:#fff;
font-size:44px;
padding:0;
text-align:center;
}
.degree{
color:#fff;
position:absolute;
top:30px;
right:10px;
font-size:24px;
}

<button onclick="addTemp()">ᐱ</button>
<input id="TempBox" value="20" type="text">
°
<button onclick="remTemp()">ᐯ</button>

A: Use some font-awesome icons and functions to increase decrease number of degrees.
Take value from the div and then put limits of min. 15 and max. 28 limits .
Used some basic JavaScript . If you face any problem within that feel free to contact in comments .

It can work without input too and if you wanted to use input than it is just simple as Replace div tag with input tag and innerHTML with value . Then restyle according to it.

document.querySelector(".decTempUnits").addEventListener("click", decreaseUnits);

function decreaseUnits() {
  var units = document.getElementsByClassName("temp")[0].innerHTML
  if (units > 15) {
    units--;
    document.getElementsByClassName("temp")[0].innerHTML = units;
    document.querySelector(".demo").innerHTML = "";
  } else if (units == 15) {
    document.querySelector(".demo").innerHTML = "Minimum limit reached";
  }
}

document.querySelector(".incTempUnits").addEventListener("click", increaseUnits);

function increaseUnits() {
  var units = document.getElementsByClassName("temp")[0].innerHTML
  if (units < 28) {
    units++;
    document.getElementsByClassName("temp")[0].innerHTML = units;
    document.querySelector(".demo").innerHTML = "";
  } else if (units == 28) {
    document.querySelector(".demo").innerHTML = "Maximum limit reached";
  }
}
.contaitner {
  user-select: none;
  width: 120px;
  height: 120px;
  background-color: black;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column;
}

.tempContaitner {
  font-size: 55px;
  position: relative;
}

.degree {
  position: absolute;
}

.units {
  font-size: 24px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

20°


text:
Q: Vertica Connection Error: [Vertica][VJDBC](100071) from DBeaver Am trying to connect vertica from DBeaver, but am getting below connection error. Initially it was working fine, but suddenly its throwing connection error.
Error Message:
    [Vertica][VJDBC](100071) GSS authentication failed due to problems establishing a TGT with JAAS using configuration verticajdbc; reason: Message stream modified (41).
  Message stream modified (41)
  Message stream modified (41)

I am not able to establish the connection now. Can anyone please help me on it.

A: The main issue I see with vertica users struggling to connect relate to the drivers used or where the host has changed. Have you updated vertica recently or has there been a change to the host name are just a couple of things you should check.
Sorry I cant be more specific its hard to troubleshoot when I dont have all the information.
Thanks


text:
Q: Android: Squared button How can I obtain a squared button in Android?
I tried to create a custom button extending the Button class as provided by this link.
I used the following code:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

public class SquareButton extends Button {

    public SquareButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public SquareButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareButton(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int w = MeasureSpec.getSize(widthMeasureSpec);
        int h = MeasureSpec.getSize(heightMeasureSpec);

        w = Math.min(w, h);
        h = w;

        setMeasuredDimension(w, h);
    }
}

I obtain squared button, but they are too big as show here, in this case there is too much margin.
How can I draw squared button with an appropiate dimension like this, with an appropiate margin dimension?
Thanks.

A: You could use a standard Button and set its width and height in XML code. To easily change the size later on and have Buttons of different sizes you can put the values in the file res/values/dimens.xml like this:
<resources>
  <dimen name="square_button_normal">50dp</dimen>
  <dimen name="square_button_large">70dp</dimen>
</resources>

and then use it like this in yout layout file:
<Button
    android:layout_width="@dimen/square_button_normal"
    android:layout_height="@dimen/square_button_normal"
    android:text="1"/>


text:
Q: Add new field to existing index in Elasticsearch Ok I've created an elastic search index called users that looks like this:
$response = $client->index([
        'index' => 'users',
        'type' => 'user',
        'id' => Auth::user()->id,
        'body' => [
            'username' => Auth::user()->username,
            'name' => Auth::user()->name,
            'city' => Auth::user()->getCity(),
        ],

    ]);

I already indexed some data. I want to add a new field called 'location' to this index so that it will now be:
$response = $client->index([
        'index' => 'users',
        'type' => 'user',
        'id' => Auth::user()->id,
        'body' => [
            'username' => Auth::user()->username,
            'name' => Auth::user()->name,
            'city' => Auth::user()->getCity(),
            'location' => [$origin],
        ],

    ]);

my question is how do I add that field to the already existing data. I already have users , but without the location field. I need to add that field to the old users data so that when a user updates their info, They don't get any shard missing errors
{"error":{"root_cause":[{"type":"document_missing_exception","reason":"[user][130]: document missing","shard":"0","index":"users"}],"type":"document_missing_exception","reason":"[user][130]: document missing","shard":"0","index":"users"},"status":404}

A: You can achieve that by using the Update API
If that's a new index - the update will fail.
In order to avoid that - use upsert.

A: I am not sure why you are seeing shards missing errors for something like this.  With Elasticsearch, mappings are dynamic by default (see Dynamic Mapping). This means you should be able to hit the index API as you are already doing to add new location information to existing and to new user documents and be able to search this information.
The downside to this is that you may have indexed a document where location information was assigned a certain type in the mapping and subsequent documents have location information that do not match this type (see Field datatypes). Perhaps, you might want to look into having a great control over the Elasticsearch mappings to avoid running into issues like that or maybe the issue is something else entirely.
EDIT: based on more details provided in the question recently regarding the document_missing_exception, this is not as relevant.

A: If you want your field to be populated with already indexed data, you should create a new index with desired mapping and reindex all your data. A good example is shown at https://www.youtube.com/watch?v=YSd1aV3iVhM&list=PL_mJOmq4zsHbcdoeAwNWuhEWwDARMMBta&index=23


text:
Q: Html get color in Rgb Well i need to do a little projet in webgl and need to pass the color from the html to the javascript, the thing is that i need that color in Rgb to working direcrly with webGl, what i need to know is if there is a way using html5 to get the color in rgb from the input.
Im doing this:
<input type="color" onchange="cor()" id="color">

the prob here is if i try to get this color he gives me the hexadecimal value, i know that via javascript with a function i can convert the hexadecimal to rgb but i need to know if there is a easier way to do this and put to work.

A: Fortunately color values in HTML5 are only valid if they're in the #XXXXXX format (meaning rgb(...) and #XXX are invalid). We can use this to our advantage as we always know exactly where the RGB positions will be in the resulting value:
#XXXXXX
#RRGGBB

To convert this to rgb(...), we simply need to strip out the # character and convert the RR, GG and BB values to decimal:
// #XXXXXX -> ["XX", "XX", "XX"]
var value = value.match(/[A-Za-z0-9]{2}/g);

// ["XX", "XX", "XX"] -> [n, n, n]
value = value.map(function(v) { return parseInt(v, 16) });

// [n, n, n] -> rgb(n,n,n)
return "rgb(" + value.join(",") + ")";

And with the beauty of JavaScript, we can do this all on one line of code:
return "rgb(" + "#FF0000".match(/[A-Za-z0-9]{2}/g).map(function(v) { return parseInt(v, 16) }).join(",") + ")";
-> "rgb(255,0,0)"


text:
Q: React forwardRef - Property does not exist on type IntrinsicAttributes I have a problem with ref.
My Component:
type DateInputProps = {
  label?: string;
  name: string;
  defaultValue: Date | null;
  maxDate?: Date;
  minDate?: Date;
  noMargin?: boolean;
  forwardRef?: React.RefObject<HTMLInputElement>;
  onChange: (date: Date | null) => void;
};

export const DateInput: FC<DateInputProps> = forwardRef<HTMLInputElement, DateInputProps>(
  ({ defaultValue, label, name, noMargin = false, maxDate, minDate, forwardRef, onChange, ...props }, ref) => {

...

  const CustomInput = ({ value, onClick }: { value?: Date; onClick?: () => void }) => (
      <Input
        ref={ref}
        name={name}
        defaultValue={value}
        onBlur={onBlur}
        alignment={InputAlignment.Right}
        iconRight={{ onClick, icon: 'calendar' }}
        iconLeft={value ? { icon: 'close', onClick: () => setDateValue(null) } : undefined}
      />
    );

...

I get the follow errors:
error TS2322: Type '{ ref: (ref: HTMLSelectElement | HTMLInputElement | HTMLTextAreaElement | CustomElement<Record<string, any>> | ... 12 more ... | null) => void; ... 4 more ...; maxDate: Date | undefined; }' is not assignable to type 'IntrinsicAttributes & DateInputProps & { children?: ReactNode; }'.
Property 'ref' does not exist on type 'IntrinsicAttributes & DateInputProps & { children?: ReactNode; }'.
I also tried with forwardRef as Property - same result.
React Version: 16.14.0

A: Solution: react.ForwardedRef<HTMLInputElement>


text:
Q: How to hide date in Date picker I am using the below code to hide Date in Date picker. This code works fine for Android Marshmallow, Lollipop versions. But it crashes when I try it in Android Nougat device.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
    MyDatePickerDialog myDatePickerDialog = new MyDatePickerDialog(this, android.R.style.Theme_Holo_Light_Dialog, onDateSetListener, y, m, d);
    myDatePickerDialog.setPermanentTitle("Date Picker");
    ((ViewGroup) myDatePickerDialog.getDatePicker())
            .findViewById(
                    Resources.getSystem().getIdentifier("day", "id",
                            "android")).setVisibility(View.GONE);
    DatePicker datePicker = myDatePickerDialog.getDatePicker();
    datePicker.setCalendarViewShown(false);
    datePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
    return myDatePickerDialog;
}

The crash is found in the following code.
 ((ViewGroup) myDatePickerDialog.getDatePicker())
     .findViewById(Resources.getSystem().getIdentifier("day", "id",
          "android")).setVisibility(View.GONE);


text:
Q: Set begin index in freemarker list How to set begin index in freemarker list?
like jstl
<c:forEach var="item" items="${screenshot.results}" begin="2">
    <a href="${item.image}"
       class="fresco"
       data-fresco-group="game-detail-pic">
    </a>
</c:forEach>

I want to start with the second index.

A: You can use sequence builtin

applying the sequence built-in allows all sequence operations, such as seq[index], seq[range], or seq?size. If these operations are directly applied on a sequence that was converted from a collection, then FreeMarker optimizes out actually creating the sequence in memory. So these won't consume much memory regardless of the size of the filtered hugeTable:
hugeTable?filter(predicate)?sequence[index]: FreeMarker will just fetch and drop the elements till it reaches the element at the desired position.
hugeTable?filter(predicate)?sequence[0..9]: FreeMarker will just collect the first 10 elements.

Example:
<#assign a=[1,2,3,5,6]>
<#list a?filter(x ->  x > 0)?sequence[1..4] as x>${x} </#list>


text:
Q: Clojure to JavaScript Converter (Leiningen) I have Leiningen installed and the project all set up. Someone told me to use the "lein cljsbuild once" command to convert Clojure to JavaScript. This did not fully answer my question because I'm having trouble understanding the folder structure of the project.
This is my project.clj:
    (defproject proj "2.3.4"
  :plugins [[lein-cljsbuild "1.0.1-SNAPSHOT"]]
  :cljsbuild {
    :builds [{
        ; The path to the top-level ClojureScript source directory:
        :source-paths ["src"]
        ; The standard ClojureScript compiler options:
        ; (See the ClojureScript compiler documentation for details.)
        :dependencies [[org.clojure/clojure "1.5.1"]]
        :main project.clj
        :compiler {
          :optimizations :whitespace
          :pretty-print true}}]})

The way I understand it is that it automatically detects files found in the "src" folder and outputs them to target/clojurescript-main.js (or something similar). I put the file I want to convert into the src folder and it seems to compile something. When I check the target folder it contains the file set in the project.clj but it does not contain the JavaScript code I am expecting (all I see is goog. methods that have nothing to do with the file I want to convert).
My question is: What is the proper folder structure? Do I have to set my source path to e.g. "src/filename.clj"?
Thanks in advance

A: i think that you have to give a reading to the docs
https://github.com/clojure/clojurescript/wiki/Quick-Start
and this also will help you:
http://swannodette.github.io/2013/10/27/the-essence-of-clojurescript/


text:
Q: Find all natural solutions of $14x+21y=91$
Find all natural solutions of $14x+21y=91$ where $x,y\in \mathbb N$

My attempt:
Divided by $7$:
$$2x+3y=13$$
And $\gcd(2,3)=1\mid13$
I found a private solution $x_0=\color{blue}5,\quad y_0=\color{blue}1$
$$2\cdot \color{blue}5+3\cdot \color{blue}1=13$$
So the general solution:
$$\begin{cases}x=5+2t\\
y=1-3t\end{cases}$$
Where $t\in \mathbb Z$
But WA's answer is diffrent, why?

A: WA says
$$
2 + 3k\\
3 - 2k
$$
You say
$$
1 - 3t\\
5 + 2t
$$
You're close, but wrong, because pugging in $t = 1$, you get
$$
x = 7\\
y = -2
$$
and
$$
2 \cdot 7 + 3 \cdot -2 \ne 13.
$$
So that's where you went wrong. The difficulty is that it should probably be
$$
x = 5 - 3t \\
y = 1 + 2t
$$
instead.

A: There are an infinite number of ways to parametrize equations so two sets of equations could both generate the same set.  Your parametrization of the equation is just a different from that WA's.  For your purpose both answers are correct.
Many problems that ask you to parametrize something will give you constraints.  It is often related to the $df/dt$ but these are unique to each area of study.


text:
Q: Dedekind-MacNeille completion is a complete lattice Let $\mathscr{P}$ be a poset and $DM(\mathscr{P}) = \{ A \subseteq \mathscr{P} | A = A^{\mathscr{u}\mathscr{l}} \}$. Here $x \in A^{\mathscr{u}\mathscr{l}}$ if and only if it is a lower bound of all upper bounds of $A$.
Then $DM(\mathscr{P})$ is a complete lattice. But how to finish the following proof?
Minimum element of $DM(\mathscr{P})$ is $\emptyset^{\mathscr{u}\mathscr{l}}$.
(Why? Because $\emptyset^{\mathscr{u}} = \mathscr{P}$ and $\mathscr{P}^{\mathscr{l}} = \bot$?)
Let $\mathcal{A} = \{ A_i | i \in I \} \subseteq DM(\mathscr{P})$. So $\mathcal{A}$ consists of sets $A_i$ so that $A_i = A_i^{\mathscr{u}\mathscr{l}}$ and $A_i \subseteq \mathscr{P}$.
And let $A = \bigcup_{i \in I} A_i$.
Lets show that for every $\mathcal{A} \subseteq DM(\mathscr{P})$ there exists $\bigvee \mathcal{A}$ $(=A^{\mathscr{u}\mathscr{l}})$.
Now $A^{\mathscr{u}\mathscr{l}} \in DM(\mathscr{P})$ and $A^{\mathscr{u}\mathscr{l}}$ is an upper bound of $\mathcal{A}$. (How to prove these?)
Consider a subset $B \in DM(\mathscr{P})$ that is also an upper bound of $\mathcal{A}$, so $A \subseteq B$. Then $B^{\mathscr{u}} \subseteq A^{\mathscr{u}}$ and $A^{\mathscr{u}\mathscr{l}} \subseteq B^{\mathscr{u}\mathscr{l}}$. Hence $A^{\mathscr{u}\mathscr{l}}$ is the least upper bound of $DM(\mathscr{P})$.
Therefore for every $\mathcal{A} \subseteq DM(\mathscr{P})$ there exists $\bigvee \mathcal{A}$
and so $DM(\mathscr{P})$ is a complete lattice.

A: Yes, $\varnothing^{\text{ul}}$ is the minimum element of $DM(\mathscr{P})$, but there are two possibilities. If $\mathscr{P}$ has a minimum element $0$, then $\varnothing^{\text{u}}=\mathscr{P}$ and $\varnothing^{\text{ul}}=\{0\}$; if not, $\varnothing^{\text{u}}$ is still $\mathscr{P}$, but $\varnothing^{\text{ul}}=\varnothing$. In either case $\varnothing^{\text{ul}}$ is clearly a subset of every element of $DM(\mathscr{P})$.
Now let $A=\bigcup_{i\in I}A_i$, where each $A_i\in DM(\mathscr{P})$. For each $i\in I$ we have $A_i\subseteq A$, so $A_i^{\text{u}}\supseteq A^{\text{u}}$, and therefore $A_i=A_i^{\text{ul}}\subseteq A^{\text{ul}}$, so $A^{\text{ul}}$ is an upper bound for $\mathscr{A}=\{A_i:i\in I\}$.


text:
Q: Short circuit and voltage source
I don't understand why when you replace a wire between a and b with a short circuit, you could just ignore 160 Ix voltage source.
I understand that those two resistors in parallel will be shorted, but why the voltage source? And if that voltage source was to the left of a 20 ohm resistor, would it still be shorted?

A: We can ignore the \$160I_x\$ voltage source because \$I_x\$ is zero. \$I_x\$ is the current through the \$40\Omega\$ resistor and when we short circuit that resistor no current will pass through it, all the current will pass through the wire.


text:
Q: Como agregar una array a una collection Tengo este esta collection obtenida desde la base de datos y deseo agregar un nuevo arreglo y que éste tome la posición 0 con esta estructura:
0 => {#322 ▼
      +"idcategoria": nuevo valor
      +"nombre": "nuevo valor "
      +"descripcion": nuevo valor
      +"condicion": "nuevo valor "
    }

Collection {#306 ▼
  #items: array:12 [▼
    0 => {#322 ▼
      +"idcategoria": 1
      +"nombre": "Memorias"
      +"descripcion": null
      +"condicion": "Activo"
    }
    1 => {#318 ▼
      +"idcategoria": 2
      +"nombre": "Audio"
      +"descripcion": null
      +"condicion": "Activo"
    }
  ]
}

A: Para agregar un elemento a la colección y que tome la primera «posición», utiliza el método prepend():
$collection->prepend([
    "idcategoria" => 10,
    "nombre" => "bla",
    "descripcion" => "...",
    "condicion" => "nuevo"
]);

Más información en https://laravel.com/docs/5.7/collections#method-prepend


text:
Q: Django: when trying domain.com/admin gives 404 with an old unexisting urls file I had at some point an urls file that looked like that:
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
# Example:
url(r'^$', 'girls.views.home', name = 'home'),
url(r'^registerasboy$', 'girls.views.regb', name= 'regb'),
#url(r'^registerasgirl$', 'girls.views.reg', name= 'regg'),
url(r'^thankyou$', 'girls.views.thankyou', name= 'thankyou'),
url(r'^newchick$', 'girls.views.newchick', name= 'newchick'),
url(r'^chicks$', 'girls.views.chicks', name= 'chicks'),
#url(r'^thankyou$', 'generalsettings.views.thankyou', name = 'thankyou'),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
#url(r'^reg$', 'generalsettings.views.home'),
# Uncomment the next line to enable the admin:
#(r'^admin/', include(admin.site.urls)),
#(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root':     settings.MEDIA_ROOT}),
)

And the site worked. I didn't have an admin. So i decided to uncomment the admin line, and i would get error 404

Page not found (404)
  Request Method: GET
  Request URL: http://chicklister.com/admin

Using the URLconf defined in chick.urls, Django tried these URL patterns,
in this order:
^$ [name='home']
^registerasboy$ [name='regb']
^thankyou$ [name='thankyou']
^newchick$ [name='newchick']
^chicks$ [name='chicks']
^/(?P<path>.*)$
The current URL, admin, didn't match any of these.

which is weird, because the admin line is missing here. Now, i Updated further my urls to:

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),)

and yet i get for admin:
Using the URLconf defined in chick.urls, Django tried these URL patterns,
in this order:
^$ [name='home']
^registerasboy$ [name='regb']
^thankyou$ [name='thankyou']
^newchick$ [name='newchick']
^chicks$ [name='chicks']
^/(?P<path>.*)$
The current URL, admin, didn't match any of these.

and yet, any other url works such as www.domain.com/thankyou according to the lines in the printed url  file
How is this possible? It seems like it has been remembered somewhere.
Steps i did:
searched the whole folder in www for 'registerasboy' and returned nothing anymore.
i changed the text on the template, to make sure i am updating the right copy.
i have the following settings in the settings.py:

ROOT_URLCONF = 'urls'
  which i noticed didn't really do anything, since in the beginning it was chic.urls

What am i doing wrong? i don't seem to even a file with such content anymore...

A: Just a shot in the dark:
Did you add the admin in your INSTALLED_APPS, do a syncdb and restarted the server ?
Restarting the server is useful if you use Apache with mod_wsgi. It does not detect the changes in the code so you need to reload it manually.
The development server reloads code automatically.
Here is the complete information about this issue :
http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode


text:
Q: How do i execute a method in a class from another method in a different class? I would like a text to be updated when i press the search button. But I can't figure out how. Can someone explain what Im doing wrong on a kindergarden level?
Here is some code, I guess it explains what I like to do.
class One():
  def setText(self, text):
    self.text.config(state=NORMAL)
    self.text.delete(1.0,END)
    self.text.insert(END, text)
    self.text.config(state=DISABLED)
  def print(self):
    self.setText('You are now searching.')
class PopUp():
  def __init__(self, master):
    self.searchButton = Button(command=self.onSearch, text ='search')
  def onSearch(self):
    mainClass = One()
    mainClass.print()


text:
Q: Xcode - Swift - UILabel in TableViewCell Expansion I have a UILabel in a custom UITableViewCell called "ScheduleCell", like so:

Here is the code for ScheduleCell:
import UIKit

class ScheduleCell: UITableViewCell {

@IBOutlet weak var titleLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

I want the tileLabel to expand based on its text and I want the ScheduleCell to expand with it. Here are the attributes of the titleLabel:

Here are the attributes of the cell prototype, which is linked to the ScheduleCell class:

Here is some relevant code for the ViewController:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 160.0

And
func tableView(tableView: UITableView!,cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! ScheduleCell

    cell.backgroundColor = UIColor(rgb: 0xF6FBFE)

    cell.titleLabel.text = (Globals.scheduleArr[indexPath.row][3] as! String)
    cell.titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)

    return cell
}

All of the titles from "Globals.scheduleArr" fit on one line except one, which is "Jane Richards Grey Reads "To Kill a Mockingbird"". Here is what the ViewController looks like in the iOS Simulator:

As you can see, the label does not expand as necessary. Strangely enough, when I add a "\n" to the end of each of the titles, the label does expand. However, the cell doesn't seem to expand with the label:

Any help in resolving this issue would be greatly appreciated!

A: If you want to use UITableViewAutomaticDimension, you need to add Label-ContentView bottom constraint.
Add new bottom constraint and try again!


text:
Q: Adding tests to existing Yii project I have an already running project done with Yii. For the next development phase, i'd like to use a TDD methodolody. Now, I have been playing around a bit getting all the complicated stuff installed (PHP and Selenium RC, headaches!), and finally gottem up and working. When I create a SampleTest.php and run it from console phpunit SampleTest.php it works just fine.
Now the issue is that this sample test is in fact an example, it doesn't use any of the models defined in my project. I would like to create new instances of my models, populate them, etc. But how can I do that without including one by one all the models, controllers, etc?
I have in my hands "The definitive guide to Yii" which, under Test Environment Setup, it says that if i use yiic webapp to create the new app, then a whole list of files and directories will be created (here is a link to that part of the book). What if its my case? I already have the application generated? I'm kinda lost, any help is appreciated.
Thanks!

A: Just create your tests at your_application/protected/tests/ folder:
 - unit tests at unit/ folder
 - functional tests at functional/ folder
First try create unit tests by this manual - http://www.yiiframework.com/doc/guide/1.1/en/test.unit. It's quite easy.
All your models, components, etc will be included automatically by bootstrap script.
You can read more about it here (look at Part 3) - http://www.yiiframework.com/doc/guide/1.1/en/test.overview


text:
Q: Construct two sequences so that $ \lim_{n\rightarrow\infty } \frac{a_{n}}{b_{n}} \neq \lim_{n\rightarrow\infty } \frac{a}{b_{n}} $ Hey I am supposed to construct two sequences $(a_n)_{n=1}^{\infty}$ and $(b_n)_{n=1}^{\infty} $ such that
$$\lim_{n\rightarrow\infty } a_n = a,$$
but
$$ \lim_{n\rightarrow\infty } \frac{a_{n}}{b_{n}} \neq \lim_{n\rightarrow\infty } \frac{a}{b_{n}}.$$
I tried many different combinations with $1/n$, but nothing worked so far. Thanks!

A: How about $a_n=\frac{1}{n}$ and $b_n=\frac{1}{n^2}$? Actually, $a_n=b_n=\frac{1}{n}$ works as well...

A: Take $a_n = e^{-n}$, so that $a=0$, and $b_n = e^{-n}$. The first limit is then $1$, whereas the second is $0$.

A: You can just take $a_n=b_n=1/n$. The left hand side is 1 and the right hand side is zero.


text:
Q: How to block spam email by subject in zimbra How can I block spam email by subject?
I did tried following this, but it doesn't work.
It uses custom_header_checks and define some parameters, I did try such parameters and restart the services but it still doesn't works. Is there other ways to prevent spam in zimbra mail server please?
I use version 7.2.7 FOSS.

A: Do not use parentheses. For example (from the link in the question):
/^subject.*From U.S. Ambassador to Nigeria/ DISCARD #spam rule to msgs from Nigeria

A: The content in OP's link looks like it was copied from here:
The header checks lost their formatting so:
`/^Subject.*)From U.S. Ambassador to Nigeria/ DISCARD #spam rule no msgs from Nigeria`

Should look like:
`/^Subject:(.*)From U.S. Ambassador to Nigeria/   DISCARD #spam rule no msgs from Nigeria`


text:
Q: Push Notification for Shared Calendars I am doing this right now: https://developers.google.com/google-apps/calendar/v3/push
I set up watchers for a given user through oauth and I get a notification when there is an update to their calendar to poll for changes. But is there a way to get notifications for shared calendars that they have access to or other calendars that they create?
I am not getting any notifications for any events that are not the default user's calendar. Any help would be appreciated.

A: The user must make a watch request to the notification channel.
POST https://www.googleapis.com/calendar/v3/calendars/my_calendar@gmail.com/events/watch
Authorization: Bearer auth_token_for_current_user
Content-Type: application/json

{
"id": "01234567-89ab-cdef-0123456789ab", // Your channel ID.
"type": "web_hook",
"address": "https://example.com/notifications", // Your receiving URL.
...
"token": "target=myApp-myCalendarChannelDest", // (Optional) Your channel token.
"expiration": 1426325213000 // (Optional) Your requested channel expiration time.
}
}

NOTE:
Each notification channel is associated both with a particular user and a particular resource (or set of resources). A watch request will not be successful unless the current user owns or has permission to access this resource.


text:
Q: How to calculate index and tag fields lengths for a cpu cache? I study computer engeering notes for a cache memory and I try to understand what determines the length of the index and the tag fields. The first examples is for 64 bits and the second example is for 128 bits and I wonder if the tag field length is just chose arbitrarily or what is the reason for being 28 in the first case and 29 in the second case. In the first case the block size is 8 bytes and in the second case the block size is 16 bytes.

Why is the tag field length only 28 bits in the second case?
Source: http://www.ict.kth.se/courses/IS1500/2012/forel/2012-ce_f8ht.pdf

A: You seem to have a 32-bit address space.
To address one of 8 bytes you need a 3-bit address, so 29 bits remain to address the block.
To address one of 16 bytes you need a 4-bit address, so 28 bits remain to address the block.


text:
Q: Gitlab CI build not triggered on push to ssh remote We have gitlab ci currently setup (supposedly) to trigger a build whenever anything is pushed to remote. However, I have discovered that if someone pushes to an ssh remote (eg: git@gitlab.com:Project.git) the build is not triggered. If they push to an https remote (eg: https://gitlab.com/Project.git), the build is triggered fine. Any thoughts as to what our problem might be? Our .gitlab-ci.yml looks like this:
stages:
  - test
  - deploy

cache:
  paths:
  - node_modules/

run_project1_tests:
  stage: test
  script:
    - set -xe
    - wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
    - echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list
    - apt-get update -yqqq
    - apt-get install -y xvfb google-chrome-stable
    - npm i -g npm@3.7.5 && npm i -g gulp@3.9.1 && npm i -g typings@1.3.1
    - cd project1
    - npm i
    - typings install && gulp check.versions && npm prune
    - Xvfb :1 -screen 0 800x600x16 &
    - export DISPLAY=:1.0
    - npm test

run_project2_tests:
  stage: test
  script:
    - npm i -g npm@3.7.5 && npm i -g typings@1.3.1 && npm i -g jasmine
    - cd project2
    - npm i
    - npm test

deploy_to_docker:
  stage: deploy
  only:
    - develop
  script:
    - chmod +x /usr/local/bin/docker-compose
    - export DOCKER_HOST="tcp://REMOTE_IP:2375"
    - docker-compose up -d --build

Thanks in advance!

A: If HTTPS works, but SSH does not, then the problem is in Gitlab, not in your .gitlab-ci.yml.
Look into logs and search for errors, run gitlab-rake gitlab:check to see whether everything is ok. It sounds like gitlab-shell (its connection to Gitlab) does not work properly.
If everything looks fine, file a bug report at https://gitlab.com/gitlab-org/gitlab-ce/issues.


text:
Q: Not able to send the Toast Push notification in wp7 I always get the 404 error.Below is my complete code for sending the push notification of type Toast from the wcf service.Anything wrong with the message ?
        string channelURI = "http://db3.notify.live.net/throttledthirdparty/01.00/AgAAAAQUZm52OjBEMTRBNDEzQjc4RUFBRTY";
        HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(channelURI);

        //Indicate that you'll send toast notifications!
        sendNotificationRequest.ContentType = "text/xml";

        sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
        sendNotificationRequest.Headers.Add("X-NotificationClass", "2");

        sendNotificationRequest.Method = "POST";

        sendNotificationRequest.Headers.Add("X-MessageID",Guid.NewGuid().ToString());

        if (string.IsNullOrEmpty(message)) return "empty cannot be sent";

        //send it
        var msg = string.Format("sample toast message", "Toast Message", "This is from server");

        byte[] notificationMessage =  Encoding.UTF8.GetBytes(msg);
        sendNotificationRequest.ContentLength = notificationMessage.Length;

        //Push data to stream
        using (Stream requestStream = sendNotificationRequest.GetRequestStream())
        {
            requestStream.Write(notificationMessage, 0, notificationMessage.Length);
        }

        //Get reponse for message sending
        HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
        string notificationStatus = response.Headers["X-NotificationStatus"];
        string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
        string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
        return notificationStatus;

A: this code may help you
private static byte[] prepareToastPayload(string text1, string text2)
    {
        MemoryStream stream = new MemoryStream();

        XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8 };
        XmlWriter writer = XmlTextWriter.Create(stream, settings);
        writer.WriteStartDocument();
        writer.WriteStartElement("wp", "Notification", "WPNotification");
        writer.WriteStartElement("wp", "Toast", "WPNotification");
        writer.WriteStartElement("wp", "Text1", "WPNotification");
        writer.WriteValue(text1);
        writer.WriteEndElement();
        writer.WriteStartElement("wp", "Text2", "WPNotification");
        writer.WriteValue(text2);
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Close();

        byte[] payload = stream.ToArray();
        return payload;
    }
private void SendMessage(Uri channelUri, byte[] payload, NotificationType notificationType, SendNotificationToMPNSCompleted callback)
    {
        //Check the length of the payload and reject it if too long
        if (payload.Length > MAX_PAYLOAD_LENGTH)
            throw new ArgumentOutOfRangeException(
      "Payload is too long. Maximum payload size shouldn't exceed " + MAX_PAYLOAD_LENGTH.ToString() + " bytes");

        try
        {
            //Create and initialize the request object
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(channelUri);
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "text/xml; charset=utf-8";
            request.ContentLength = payload.Length;
            request.Headers[MESSAGE_ID_HEADER] = Guid.NewGuid().ToString();
            request.Headers[NOTIFICATION_CLASS_HEADER] = ((int)notificationType).ToString();

            if (notificationType == NotificationType.Toast)
                request.Headers[WINDOWSPHONE_TARGET_HEADER] = "toast";
            else if (notificationType == NotificationType.Token)
                request.Headers[WINDOWSPHONE_TARGET_HEADER] = "token";

            request.BeginGetRequestStream((ar) =>
            {
                //Once async call returns get the Stream object
                Stream requestStream = request.EndGetRequestStream(ar);

                //and start to write the payload to the stream asynchronously
                requestStream.BeginWrite(payload, 0, payload.Length, (iar) =>
                {
                    //When the writing is done, close the stream
                    requestStream.EndWrite(iar);
                    requestStream.Close();

                    //and switch to receiving the response from MPNS
                    request.BeginGetResponse((iarr) =>
                    {
                        using (WebResponse response = request.EndGetResponse(iarr))
                        {
                            //Notify the caller with the MPNS results
                            OnNotified(notificationType, (HttpWebResponse)response, callback);
                        }
                    },
                    null);
                },
                null);
            },
            null);
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                //Notify client on exception
                OnNotified(notificationType, (HttpWebResponse)ex.Response, callback);
            }
            throw;
        }
    }

protected void OnNotified(NotificationType notificationType, HttpWebResponse response, SendNotificationToMPNSCompleted callback)
    {
        CallbackArgs args = new CallbackArgs(notificationType, response);
        if (null != callback)
            callback(args);
    }
public class CallbackArgs
{
    public CallbackArgs(NotificationType notificationType, HttpWebResponse response)
    {
        this.Timestamp = DateTimeOffset.Now;
        this.MessageId = response.Headers[NotificationSenderUtility.MESSAGE_ID_HEADER];
        this.ChannelUri = response.ResponseUri.ToString();
        this.NotificationType = notificationType;
        this.StatusCode = response.StatusCode;
        this.NotificationStatus = response.Headers[NotificationSenderUtility.NOTIFICATION_STATUS_HEADER];
        this.DeviceConnectionStatus = response.Headers[NotificationSenderUtility.DEVICE_CONNECTION_STATUS_HEADER];
        this.SubscriptionStatus = response.Headers[NotificationSenderUtility.SUBSCRIPTION_STATUS_HEADER];
    }

    public DateTimeOffset Timestamp { get; private set; }
    public string MessageId { get; private set; }
    public string ChannelUri { get; private set; }
    public NotificationType NotificationType { get; private set; }
    public HttpStatusCode StatusCode { get; private set; }
    public string NotificationStatus { get; private set; }
    public string DeviceConnectionStatus { get; private set; }
    public string SubscriptionStatus { get; private set; }
}
public enum NotificationType
{
    Token = 1,
    Toast = 2,
    Raw = 3
}


text:
Q: Projection Error in Explorer for ArcGIS When I look at the map "Prefeitura de Manaus (Gestão de Obras - SEMINF)" on ArcGIS online, it shows perfect alignment between the lot lines (in blue) and the satellite basemap:

However, when I look at the same map in the Explorer for ArcGIS app, there appears to be a distortion in the projection of the lots onto the satellite map, with all lots being misalligned by a few meters:

Does anyone know why the projections differ between the app and online and if there is a way to correct the projection in the app?

A: The Satellite data in the two screenshots is different. The top screenshot is the Ortophoto layer and the bottom screenshot is the AGOL Imagery layer. All of the data in the WebMap (including Ortophoto) is shifted because it is in a different Datum than WGS 84 and has not had the correct transformation applied in order to be displayed on top of Web Mercator base maps. The bottom screenshot was likely taken before the Ortophoto layer finished loading. Hope this helps...


text:
Q: CodeDOM for creating classes from existing entity class I used CodeDOM to generate a class (entity class) from a given database table. I used this tutorial and made my application. It's OK and working fine. By using codeDOM can I edit an existing entity class and regenerate it against the table it's based on ? I searched for it but no luck. If so, can you point me to the direction. Or if not, How can I regenerate my existing class modified?

A: With CodeDom you can generate a code for a class at runtime, but you can't modify an existing class. The only way is to regenerate it from scratch based upon your table, and I think is the approach you can use in your case.


text:
Q: Graphql federation - Communication between subgraphs for validation I am trying to implement Graphql federation with multiple subgraphs using Nestjs + Apollo GraphQL.
So I have USER subgraph and Application subgraph as separate Graphql services. Everything seems to be working fine when its comes to querying from the supergraph.
But I am not able to figure out how to implement the following
As Application subgraph have the following mutation to add the new application
type Mutation {
  createApplication(
    createApplicationInput: CreateApplicationInput!
  ): Application!

}

input CreateApplicationInput {
  name: String!
  userId: Int!
}

Now while calling the above mutation I am able to add new application, but not able to validate if user exists on user subgraph or not.
So my question is how I can validate that user exists before insert to application at graphql side


text:
Q: In a mnesia cluster, which node is queried? Let's say you have a mnesia table replicated on nodes A and B. If on node C, which does not contain a copy of the table, I do mnesia:change_config(extra_db_nodes, [NodeA, NodeB]), and then on node C I do mnesia:dirty_read(user, bob) how does node C choose which node's copy of the table to execute a query on?

A: According to my own research answer for the question is - it will choose the most recently connected node. I will be grateful for pointing out errors if found - mnesia is a really complex system!
As Dan Gudmundsson pointed out on the mailing list algorithm of selection of the remote node to query is defined in mnesia_lib:set_remote_where_to_read/2. It is the following
set_remote_where_to_read(Tab, Ignore) ->
    Active = val({Tab, active_replicas}),
    Valid =
       case mnesia_recover:get_master_nodes(Tab) of
           [] ->  Active;
           Masters -> mnesia_lib:intersect(Masters, Active)
       end,
    Available = mnesia_lib:intersect(val({current, db_nodes}), Valid -- Ignore),
    DiscOnlyC = val({Tab, disc_only_copies}),
    Prefered  = Available -- DiscOnlyC,
    if
       Prefered /= [] ->
           set({Tab, where_to_read}, hd(Prefered));
       Available /= [] ->
           set({Tab, where_to_read}, hd(Available));
       true ->
           set({Tab, where_to_read}, nowhere)
    end.

So it gets the list of active_replicas (i.e. list of candidates), optionally shrinks the list to master nodes for the table, remove tables to be ignored (for any reason), shrinks the list to currently connected nodes and then selects in the following order:

*

*First non-disc_only_copies

*Any available node

The most important part is in fact the list of active_replicas, since it determines the order of nodes in the list of candidates.
List of active_replicas is formed by remote calls of mnesia_controller:add_active_replica/* from newly connected nodes to old nodes (i.e. one which were in the cluster before), which boils down to the function add/1 which adds the item as the head of the list.
Hence answer for the question is - it will choose the most recently connected node.
Notes:
To check out the list of active replicas on the given node you can use this (dirty hack) code:
[ {T,X} || {{T,active_replicas}, X} <- ets:tab2list(mnesia_gvar) ].

A: Well, node C would need to contact either node A or node B in order to do a query. Thus node C will have to decide itself which table copy to execute the query on.
If you need something more than this you would either need to have some algorithm which will decide which node to query on, or even replicate the table on node C (this would typically depend on what kind of characteristics you want / need).
If node A and node B form or are part of a database cluster, a good start is probably the round robin algorithm (or random, as you suggest).


text:
Q: loop a function a random number of times in javascript I have created a script to generate random sentences from words and phrases in an array. This works.
I want to make a paragraph from these random sentences. What I have done though is repeating the same sentence, rather than running the function again and again to create new sentences.
I think my error is in this part of the code.
const randParagraph = (len, end, words, wordLen) =>
[...Array(len)].map(() =>  addCommaAfter(fullSentWithEnd,sentLength(5,12)))
.join(' ') + (end || ' ');

fullSentWithEnd is the final function in generating the sentences.
const fullSentWithEnd = randSentence(ipsumText, sentLength(5,12), '.')

and addAfterComma is splitting the sentence to add a comma.
const addCommaAfter = (sentence, index) => {
word_split = sentence.split(" ");
word_split[index] = word_split[index]+",";
word_split[0] = word_split[0][0].toUpperCase() + word_split[0].slice(1);
return word_split.join(" ");

}
I thought in randParagraph the new array was saying run addCommaAfter and pass in fullSentWithEnd, and tell it to run a random number of times between 5 and 12. But now I am wondering if it is actually saying that, or if that is what is telling it to repeat the same result.
Would love some thoughts.

const ipsumText = ["adventure", "endless youth", "dust", "iconic landmark", "spontaneous", "carefree", "selvedge","on the road", "open road", "stay true", "free spirit", "urban", "live on the edge", "the true wanderer", "vintage motorcyle", "american lifestyle", "epic landscape", "low slung denim", "naturaL"];

const randInt = (lower, upper) =>
Math.floor(Math.random() * (upper-lower)) + lower

const randWord = (words) => words[randInt(0, words.length)]

const randSentence = (words, len, end) =>
[...Array(len)].map(() => randWord(words)).join(' ') + (end || ' ')

const randWordWithEnd = (end) => randWord(ipsumText) + end
const randWordWithFullStop = randWordWithEnd('. ')
const randWordWithComma = randWordWithEnd(', ')

const sentLength = (min,max) => {return Math.floor(Math.random() * (max - min + 1)) + min;};

const fullSentWithEnd = randSentence(ipsumText, sentLength(5,12), '.')
const fullSentNoEnd = randSentence(ipsumText, sentLength(5,12))
const fullSentComposed = fullSentNoEnd + randWordWithFullStop

const addCommaAfter = (sentence, index) => {
 word_split = sentence.split(" ");
 word_split[index] = word_split[index]+",";
 word_split[0] = word_split[0][0].toUpperCase() + word_split[0].slice(1);
 return word_split.join(" ");
}

console.log(fullSentWithEnd)
console.log(" ");
console.log(addCommaAfter(fullSentWithEnd,sentLength(3,8)));

const randParagraph = (len, end, words, wordLen) =>
[...Array(len)].map(() => addCommaAfter(fullSentWithEnd,sentLength(5,12)))
.join(' ') + (end || ' ');

console.log(randParagraph(sentLength(5,8), '', ipsumText, sentLength(5,12)));

A: I don't understand what exactly your code does, but I've got this little framework for generating random texts:

ucfirst = s => s[0].toUpperCase() + s.slice(1);

rand = (min, max) => min + Math.floor(Math.random() * (max - min));

sample = a => a[rand(0, a.length)];

times = (n, fn) => [...Array(n)].map(fn);

seq = (min, max, fn, sep) => times(rand(min, max), fn).join(sep);

// this will use random "words"

char = () => sample("abcdefghjiklmnopqrstuwvxyz");
word = seq(1, 10, char, '');

// this will use an array of predefined words

words = [
    'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'I', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do',
    'at', 'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one', 'all',
    'would', 'there', 'their', 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when', 'make',
    'can', 'like', 'time', 'no', 'just', 'him', 'know', 'take', 'person', 'into', 'year', 'your', 'good', 'some', 'could',
    'them', 'see', 'other', 'than', 'then', 'now', 'look', 'only', 'come', 'its', 'over', 'think', 'also', 'back', 'after',
    'use', 'two', 'how', 'our', 'work', 'first', 'well', 'way', 'even', 'new', 'want', 'because', 'any', 'these', 'give',
    'day', 'most', 'us'];

word = () => sample(words)

phrase = () => seq(3, 10, word, ' ');

sent = () => seq(1, 10, phrase, ', ');

sentence = () => ucfirst(sent()) + sample('.?!');

paragraph = () => seq(1, 10, sentence, ' ');

text = () => seq(2, 20, paragraph, '\n\n');

console.log(text())

A: you are seeding the addCommaAfter func from randParagraph func with same sentence. instead change the seeding with random sentences like following, it will create paragraph with random sentences.
const randParagraph = (len, end, words, wordLen) =>
    [...Array(len)].map(() => addCommaAfter(randSentence(words, sentLength(5, 12), '.'), sentLength(5, 12)))
        .join(' ') + (end || ' ');

Full code:

const ipsumText = ["adventure", "endless youth", "dust", "iconic landmark", "spontaneous", "carefree", "selvedge", "on the road", "open road", "stay true", "free spirit", "urban", "live on the edge", "the true wanderer", "vintage motorcyle", "american lifestyle", "epic landscape", "low slung denim", "naturaL"];

const randInt = (lower, upper) =>
    Math.floor(Math.random() * (upper - lower)) + lower

const randWord = (words) => words[randInt(0, words.length)]

const randSentence = (words, len, end) =>
    [...Array(len)].map(() => randWord(words)).join(' ') + (end || ' ')

const randWordWithEnd = (end) => randWord(ipsumText) + end
const randWordWithFullStop = randWordWithEnd('. ')
const randWordWithComma = randWordWithEnd(', ')

const sentLength = (min, max) => { return Math.floor(Math.random() * (max - min + 1)) + min; };

const fullSentWithEnd = randSentence(ipsumText, sentLength(5, 12), '.')
const fullSentNoEnd = randSentence(ipsumText, sentLength(5, 12))
const fullSentComposed = fullSentNoEnd + randWordWithFullStop

const addCommaAfter = (sentence, index) => {
    word_split = sentence.split(" ");
    if (index >= word_split.length) {
        index = word_split.length - 1;
    }
    word_split[index] = word_split[index] + ",";
    word_split[0] = word_split[0][0].toUpperCase() + word_split[0].slice(1);
    return word_split.join(" ");
}

console.log(fullSentWithEnd)
console.log(" ");
console.log(addCommaAfter(fullSentWithEnd, sentLength(3, 8)));

const randParagraph = (len, end, words, wordLen) =>
    [...Array(len)].map(() => addCommaAfter(randSentence(words, sentLength(5, 12), '.'), sentLength(5, 12)))
        .join(' ') + (end || ' ');

console.log(randParagraph(sentLength(5, 8), '', ipsumText, sentLength(5, 12)));