text:
Q: External Connection With MicrosoftIdentityWebApp And Identity I try to login User from Microsoft account into my app.
First : I'm following this info, and that'a working well.
https://learn.microsoft.com/fr-fr/azure/active-directory/develop/web-app-quickstart?pivots=devlang-aspnet-core
But, when I try merge it with the classic Identity Login, on the external Login, this function return null all the time. And the login info on the starup is correct. I think it was a schema problem but I try to change it and it was not.
 var info = await _signInManager.GetExternalLoginInfoAsync();

        public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
            }

            var userl = _signInManager.IsSignedIn(User);

            //ExternalLoginInfo info = new ExternalLoginInfo(User, "Microsoft", User.Claims.Where(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier").FirstOrDefault().Value.ToString(), "Microsoft");
            var info = await _signInManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                ErrorMessage = "Error loading external login information.";
                return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
            }
            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
            if (result.Succeeded)
            {
                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
                return LocalRedirect(returnUrl);
            }
            if (result.IsLockedOut)
            {
                return RedirectToPage("./Lockout");
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ReturnUrl = returnUrl;
                ProviderDisplayName = info.ProviderDisplayName;
                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                {
                    Input = new InputModel
                    {
                        Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                    };
                }
                return Page();
            }
        }

Startup.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(connectionString));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddRoles<IdentityRole>()
    .AddErrorDescriber<FrenchIdentityErrorDescriber>()
    .AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddRazorPages();
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services
    .AddControllersWithViews()
    .AddRazorRuntimeCompilation()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
        options.JsonSerializerOptions.PropertyNamingPolicy = null;
    });

builder.Services.AddMvc();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(8);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
    //options.Cookie.Name = "WebSignature.Session";
});

builder.Services.Configure<IdentityOptions>(options =>
{
    // Password settings.
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;
    options.Password.RequiredUniqueChars = 1;

    // Lockout settings.
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    options.Lockout.MaxFailedAccessAttempts = 5;
    options.Lockout.AllowedForNewUsers = true;

    // User settings.
    options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
    options.User.RequireUniqueEmail = false;
});

builder.Services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromHours(12);
    options.LoginPath = ApplicationRedirection.PageConnexion;
    options.LogoutPath = "/Identity/Account/Logout";
    options.AccessDeniedPath = "/Erreurs/403";
    options.SlidingExpiration = true;
});

builder.Services
    .AddAuthentication()
    .AddJwtBearer(options =>
    {
        var SecretKey = builder.Configuration.GetSection("JwtToken").GetValue<string>("SecretKey") ?? string.Empty;
        var Audience = builder.Configuration.GetSection("JwtToken").GetValue<string>("Audience") ?? string.Empty;
        var Issuer = builder.Configuration.GetSection("JwtToken").GetValue<string>("Issuer") ?? string.Empty;

        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ClockSkew = TimeSpan.Zero,

            ValidateAudience = true,
            ValidAudience = Audience,
            ValidateIssuer = true,
            ValidIssuer = Issuer,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey))
        };
    });

builder.Services.AddAuthentication()
    .AddMicrosoftIdentityWebApp(options =>
    {
        var config = builder.Configuration.GetSection("AzureAd");
        options.Instance = config["Instance"];
        options.Domain = config["Domain"];
        options.ClientId = config["ClientId"];
        options.TenantId = config["TenantId"];
        options.ClientSecret = config["ClientSecret"];
        options.CallbackPath = config["CallbackPath"];

        options.RequireHttpsMetadata = true;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.SaveTokens = true;
        options.UsePkce = true;
        options.ResponseType = OpenIdConnectResponseType.Code;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true
        };
    })
    .EnableTokenAcquisitionToCallDownstreamApi(builder.Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' '))
    .AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
    .AddInMemoryTokenCaches();

builder.Services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy(PolicyApplication.Administrateur, policy => policy.RequireAuthenticatedUser().RequireRole(RoleUtilisateur.Administrateur)/*.AddAuthenticationSchemes(IdentityConstants.ApplicationScheme)*/);
    options.AddPolicy(PolicyApplication.Utilisateur, policy => policy.RequireAuthenticatedUser().RequireRole(RoleUtilisateur.Utilisateur)/*.AddAuthenticationSchemes(IdentityConstants.ApplicationScheme)*/);

    /// Récupère tous les roles de la class
    var AllRole = typeof(RoleUtilisateur).GetFields().Select(x => x.GetValue(x.Name)?.ToString() ?? "").ToArray();
    options.AddPolicy(PolicyApplication.All, policy => policy.RequireAuthenticatedUser().RequireRole(AllRole)/*.AddAuthenticationSchemes(IdentityConstants.ApplicationScheme)*/);

    /// Pour l'API
    options.AddPolicy(PolicyApplication.API, policy => policy.RequireAuthenticatedUser().AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme));
});

builder.Services.Configure<GzipCompressionProviderOptions>(o => o.Level = CompressionLevel.Optimal);
builder.Services.AddKendo();
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();
var supportedCultures = new[] { new CultureInfo("fr-FR") };
app.UseRequestLocalization(new RequestLocalizationOptions()
{
    DefaultRequestCulture = new RequestCulture(new CultureInfo("fr-FR")),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures
});

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseSwagger();
app.UseSwaggerUI();

app.UseStatusCodePages(context =>
{
...

    return Task.CompletedTask;
});

app.UseSession();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

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

app.Run();

Value Null
I the problem is due to the claims who was empty. But i don't know why.
enter image description here
So what is wrong, any ideas ?

A: Finally I found.
Simply use that
builder.Services.AddAuthentication()
.AddMicrosoftAccount(options =>
{
    var config = builder.Configuration.GetSection("AzureAd");
    options.ClientId = config["ClientId"] ?? string.Empty;
    options.ClientSecret = config["ClientSecret"] ?? string.Empty;
    options.CallbackPath = config["CallbackPath"] ?? string.Empty;
});

than
builder.Services.AddAuthentication()
.AddMicrosoftIdentityWebApp(options =>
{
    var config = builder.Configuration.GetSection("AzureAd");
    options.Instance = config["Instance"];
    options.Domain = config["Domain"];
    options.ClientId = config["ClientId"];
    options.TenantId = config["TenantId"];
    options.ClientSecret = config["ClientSecret"];
    options.CallbackPath = config["CallbackPath"];

    options.RequireHttpsMetadata = true;
    options.GetClaimsFromUserInfoEndpoint = true;
    options.SaveTokens = true;
    options.UsePkce = true;
    options.ResponseType = OpenIdConnectResponseType.Code;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true
    };
})
.EnableTokenAcquisitionToCallDownstreamApi(builder.Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' '))
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();


text:
Q: Resizing image prevented I can't figure out why, but the background image resize is prevented by something.
I've the following code that adds image to div's background and I'm willing to show the whole image, not just the center of it.
Some how the image is zooming in and I would like to change that to full image view.
#section1{
  background-image: url(http://freevectorsite.com/wp-content/uploads/2013/09/Abstract-Hi-Tech-Background.jpg);
  background-size:     cover;
  background-repeat:   no-repeat;
  background-size: 100% 1000px;
  transform: translateZ(-1px) scale(2);
  z-index:-1;
}

HTML:

My Work

CodePen
How can I use background-size to view the whole image and not just part of it?

A: According to code you provided, height of the div isn't set manually, so its height is auto and equals to size(height) of its content. The div contains only child div and paragraph so it's size is small.
So you could try this:

My Work

#section1{
  background-image: url(http://freevectorsite.com/wp-content/uploads/2013/09/Abstract-Hi-Tech-Background.jpg);
  background-size:     cover;
  background-repeat:   no-repeat;
  transform: translateZ(-1px) scale(2);
  height: 100vh; /*This equals to whole viewport height, but you can try any size you want*/
  z-index:-1;
}

A: try this
#section1{
  background-image: url(http://freevectorsite.com/wp-content/uploads/2013/09/Abstract-Hi-Tech-Background.jpg);
  background-size:     cover;
  background-repeat:   no-repeat;
  background-size: 100%;
  transform: translateZ(-1px) scale(1);
  z-index:-1;
}
#section1 .text{
  transform: translateZ(-1px) scale(1.5);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: $n$ points on every line For which integers $n$ is it possible to find a subset $S$ of $\mathbb R^2$ such that every infinite line contains exactly $n$ points of $S$?

A: According to Gelbaum and Olmsted, Counterexamples in Analysis, Chapter 10, problem 21, page 144, "F. Galvin has shown the following: if $1\lt n\le\aleph_0$ then there is a non-measurable set in the plane such that the intersection of $S$ with any line consists of precisely $n$ points." Unfortunately, no bibliographic details are given.

A: I've not seen Galvin's argument, but here's one that works for the finite cases.
Fix $n>1$. Let $\mathscr{L}=\{L_\xi:\xi<2^\omega\}$ be an enumeration of the lines in the plane. Suppose that $\alpha<2^\omega$ and that for each $\beta<\alpha$ we have a set $A_\beta\subseteq\mathbb{R}^2$ such that
$\qquad(0)_\beta:\qquad$ $A_\xi\subseteq A_\beta$ for every $\xi<\beta$;
$\qquad(1)_\beta:\qquad$ $|A_\beta|\le |\beta|+\omega$;
$\qquad(2)_\beta:\qquad$ no $n+1$ points of $A_\beta$ are collinear; and
$\qquad(3)_\beta:\qquad$ for each $\xi<\beta$, $|L_\xi \cap A_\beta|=n$.
Let $A_\alpha'=\bigcup\limits_{\beta<\alpha}A_\beta$. If $\alpha$ is a limit ordinal, let $A_\alpha=A_\alpha'$; clearly $(0)_\alpha-(3)_\alpha$ hold.
If $\alpha=\xi+1$, $L_\xi$ intersects $A_\alpha'$ in $k$ points for some $k\le n$. If $k=n$, let $A_\alpha=A_\alpha'$; as before, $(0)_\alpha-(3)_\alpha$ hold. Otherwise, let $B$ be the union of the lines determined by collinear $n$-point subsets of $A_\alpha'$; there are fewer than $2^\omega$ such lines, so $|L_\xi\setminus B|=2^\omega$, and we may choose a set $F_\xi \subseteq L_\xi \setminus B$ of cardinality $n-k$. If we then set $A_\xi = A_\alpha'\cup F_\xi$, $(0)_\alpha-(3)_\alpha$ are satisfied.
Now let $A = \bigcup\limits_{\xi<2^\omega}A_\xi$; then each line in the plane intersects $A$ in exactly $n$ points.
(I suppose that it should be noted that $n=0$ also works!)


text:
Q: Modifying order of cases in dataframe R I have a problem with some R Code in terms of sports data over a number of years not being in a very logical order. I have a dataset with 42 variables and almost 80,000 cases, and one is paraphrased below:
dat <- c(2020, 2020, 2020, 2020, 2020, 2020, 2020)
r<- c("QF", "R1", "R15", "R2", "R25", "R3", "SF")
data <- data.frame(dat, r)

Obiously each case will have one of the round details, not all of them, and not only having 26 cases
The problem is that rather than ordering it in the above order of R1-R25, followed by QF, SF and GF, it is ordered in a manner of GF, QF, R1, R10-R19, R2, R21-R25, R3-R9, SF, obviously due to the numerical order of the first digit after the R, and letter order of each thing.
This is how i want it to look, but I cant go through 80,000 cases manuall like this:
dat <- c(2020, 2020, 2020, 2020, 2020, 2020, 2020)
r <- c("R1", "R2", "R3", "R15", "R25", "R3", "QF", "SF")
data <- data.frame(dat, r)

Thanks :)

A: Here's a tidyverse solution:
library(tidyverse)

data %>%
  mutate(r = str_sort(r, numeric = T))

Edit:
To arrange as "R, Q, S", you can substring your r variable and apply a custom sort using arrange and match:
data %>%
  mutate(r = str_sort(r, numeric = T)) %>%
  arrange(match(str_sub(r,1,1), c("R", "Q", "S")))

This gives us:
   dat   r
1 2020  R1
2 2020  R2
3 2020  R3
4 2020 R15
5 2020 R25
6 2020  QF
7 2020  SF

A: Since you want "QF" and "SF" at the end one option would be to extract the number from the r column and order them. "QF" and "SF" don't have numeric value in them so they would return NA and will ordered last.
result <- data[order(as.numeric(stringr::str_extract(data$r, '\\d+'))), ]

#   dat   r
#2 2020  R1
#4 2020  R2
#6 2020  R3
#3 2020 R15
#5 2020 R25
#1 2020  QF
#7 2020  SF

A: We may use parse_number
library(dplyr)
data %>%
   arrange(readr::parse_number(r))

-output
 dat   r
1 2020  R1
2 2020  R2
3 2020  R3
4 2020 R15
5 2020 R25
6 2020  QF
7 2020  SF


text:
Q: Убрать из названия раздела /index.php Убрать из названия раздела /index.php
Например страницу http://site.ru/razdel/index.php
Требуется редиректить на http://site.ru/razdel/

A: Примерно так
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^/?razdel/?$ /razdel/index.php [L]
</IfModule>

A: Если адрес по которому идет обращение заканчивается на index.php или index.html, то делаем переадресацию:
RewriteEngine On
RewriteCond %{REQUEST_URI} ^(.*)/index\.(php|html)$
RewriteRule .*  http://site.ru%1/ [R=301,L,QSA]

A: RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]

Только не забудьте включить mod_rewrite в PHP


text:
Q: Would Performing a T-Test between Nonequal Continuous Distributions Provide Valid Results? I have two samples, and in performing a Kolmogorov–Smirnov test the sample distributions are shown to be significantly different from each other.
In knowing that the two sample distributions are different, can I perform a t-test and expect valid results?
If not, is there another test that would provide better results to test central tendency between those two samples given the results of the aforementioned K-S test?
edit
The samples being tested are in essence A/B testing, and the motivation is to find their expected value per test arm category.
Unfortunately, the sample size is unavoidably small; 40 to 60 observations and are not normal.
When running both a t-test and k-s test the sample test are significant, but given the nature of the data, can anything be inferred as to each test arms respective central tendencies?


text:
Q: CSS selector when there is direct siblings I need to target every contiguous
 in css. Lemme explain. In my piece of code i have attached you can see one
 tag. Then comes the text. After that three
 tag then comes the text and it goes on.
My question is there is any css selector to select when there is continuous range of
 is present. When there is three continuous
 tag i want to select second and third
 tag. When there is four continuous
 tag i want to select second, third, fourth
 tag. Any ways to achieve it with CSS

div br:not(:first-child){
  margin-top:10px;
}

    how can i select a DOM

    which comes next to next

    Any Idea please suggest

    Thanks

A: Don't use  if you don't want unnecessary space of a line.
Instead you can use  or  because its automatically point the cursor to the next Line.


text:
Q: ASP.net MVC Model for clothing I'm trying to create a full MVC web app for a fake clothing website just for experience (first time using this framework).
I created a class in models named ClothingItem to manage each item of clothing being sold.
In this class I would like to store information such as:
- brand (seller will only be selling a limited range of clothing e.g. tommy/ralph and occasionally other random pieces)
- type of clothing (e.g. polo/tee/jacket)
- color/pattern
- size (XL+, XL, L, M, S, XS)
- price
It is clear to me that I should use a decimal type for the price, however, I am unsure as to what type I should be using for brand, type, color, and size.
I considered using enums (bearing in mind I would like the user to be able to filter clothing items by brand/size/type) for these but I am unsure as to whether I should do this or just use a string to store the type, I would like to know what I should be using, whether I am along the right track, or if I'm just taking a completely wrong approach to this? Thanks in advance
example of enum:
Public enum Brand {
   TommyHilfiger = 1,
   RalphLauren,
   Adidas,
   Nike
}

A: enums can be useful if your are just testing and you want to learn ASP.NET MVC
But for a real application it will be a bad solution, why ?
Imagine that you have to add a new Brand to your application, for example : Lacoste
You will need to open you source code and add the new value to your enum and recompile the application.
A better approach (but with more work to do) is to manage your brands via a table in database that will be mapped to a class in your model.
public class Brand {
    public string Name {get; set;}
}

For a filter, you will need to request the list of all brands as string and show them in Dropdown for example.
I'm sure there is many other solutions


text:
Q: Reading and displaying simple text from text file I am fairly new to iphone development and programming in general and am wondering how to read some text from a text file to be diplayed in a UITextView. I have tried various ways to do it but just can't seem to be able to get it to display:
- (void)viewDidLoad {
[super viewDidLoad];

NSString *filePath=[[NSBundle mainBundle] pathForResource:@"untitled" ofType:@"txt"];

NSString *someText=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
textView.text=someText;

Some sample code would be greatly appreciated. Thanks in advance

A: You shouldn't include the extension in the pathForResource: parameter:
[[NSBundle mainBundle] pathForResource:@"untitled.txt" ofType:@"txt"]
should be
[[NSBundle mainBundle] pathForResource:@"untitled" ofType:@"txt"].

A: I had to change the name of the text file to 'untitled.txt' from just plain 'untitled' in Xcode. It was a text file but didn't have the extension of .txt. This doesn't seem to be automatically appended if you create the text file in Xcode.

A: Is untitled.txt actually where you think it is? Try logging filePath and see if it's what you expect. (You could do [[NSFileManager defaultManager] isReadableFileAtPath:filePath] to be completely certain.)
If the path is correct then the problem must be with loading the text. One such problem could be that the file is not encoded in UTF8. Mike Ash recently blogged about character encoding. At the end of the post he describes how to handle text files of unknown encoding.


text:
Q: Adding easing to jquery css swap HI I am trying to add some easing to a script I'm am working on and I can't get it to work right.
var $mainlogo = jQuery('#mainlogo');
var $menuback = jQuery('.x-navbar');
jQuery(document).scroll(function() {
    $mainlogo.css({display: jQuery(this).scrollTop()>170 ? "block":"none"});
    $menuback.css({background: jQuery(this).scrollTop()>170 ? "rgba( 255, 255, 255, 0.7 )":"none"}, {
        easing: 'swing',
        duration: '2000'
    });
});

What Am I doing wrong? I just want it to fade in instead of an immediate appearance.


text:
Q: Running binary files I was able to download a binary file from internet and saved it at my Android device programmatically, the problem is selecting the proper location to be able to execute it, I picked both app internal and data directory but both gave me:

Cannot run program "/data/user/0/com.example.dl/app_mounted/server":
error=13, Permission denied

My code is:
MainActivity.kt
package com.example.dl

import android.content.Context
import android.content.ContextWrapper
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.dl.databinding.ActivityMainBinding
import kotlinx.coroutines.*
import java.io.*
import java.lang.RuntimeException
import java.net.URL
import java.util.*

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        val context = this
       val urlFile:URL = URL("https://drive.google.com/uc?export=download&id=" +
                "1kRtYw3_Yd7he0HjbgNlAAl9we9tQEGvm")

        binding.tvDownload.text = urlFile.toString()
        val tag = "Main Activity"
        val targetFileName = "server"

        val wrapper = ContextWrapper(context)
        /* ******************************** */
        /** What Directory Should I Select **/
        var directory = wrapper.getDir("${Environment.getExternalStorageState()}", Context.MODE_PRIVATE)
        /* ******************************** */
        var file = File(directory, targetFileName)

        binding.button.setOnClickListener { button ->
            lifecycleScope.launch {
                if (file.exists()) {
                    Log.i(tag, "$file does exist.")
                    // Runtime.getRuntime().exec("/system/bin/rm /$file")

                    Log.i(tag, "Setting file executable")
                    file?.setExecutable(true)
                    Log.i(tag, "Running executable file")
                    Runtime.getRuntime().exec(file.toString())

                    //   Runtime.getRuntime().exec("/bin/sh -c $file")

                    binding.tvSaved.text = file.toString()

                    button.isEnabled = true // enable button
                    binding.progressBar.visibility = View.INVISIBLE
                } else {
                    Log.i(tag, "$file does not exist.")
                    binding.tvSaved.text = ""

                button.isEnabled = false // disable button
                binding.progressBar.visibility = View.VISIBLE

                // perform these tasks off the main thread
                val savedUri: Uri? = withContext(Dispatchers.IO) {
                    // get / download bitmap from url
                    val fileStream: InputStream? = urlFile.toStream(context)
                    Log.i(
                        tag,
                        "Stream $fileStream collected, trying to save it"
                    )
                    fileStream?.saveToInternalStorage(context)
                }

                if (savedUri == null) {
                    Log.e(tag, "URI was null. Nothing to save")
                    return@launch
                }

                val execFile = File(savedUri.toString())
                Log.i(tag, "Stream saved")

                Log.i(tag, "Setting file executable")
                execFile?.setExecutable(true)
                Log.i(tag, "Running executable file")
                Runtime.getRuntime().exec(savedUri.toString())

                //   Runtime.getRuntime().exec("/bin/sh -c $savedUri")

                // show bitmap saved uri in text view
                binding.tvSaved.text = savedUri.toString()

                button.isEnabled = true // enable button
                binding.progressBar.visibility = View.INVISIBLE
            }

            }
        }
}

Download.kt
package com.example.dl

import android.content.Context
import android.util.Log
import java.io.*
import java.net.HttpURLConnection
import java.net.URL

// extension function to get / download bitmap from url
fun URL.toStream(context : Context): InputStream? {
    return try {
        val tag = "input stream"
            Log.v(tag, "downloadFile() invoked ")
            Log.v(tag, "downloadFile() fileUrl $this")
        //    Log.v(TAG, "downloadFile() directory $directory")
            val url = URL(this.toString())
            val urlConnection = url.openConnection() as HttpURLConnection
            urlConnection.connect()
            val inputStream = urlConnection.inputStream
        inputStream
    } catch (e: IOException){
        null
    }
}

SaveToInternal.kt
package com.example.dl

import android.content.ContentValues
import android.content.Context
import android.content.ContextWrapper
import android.net.Uri
import android.os.Environment
import android.util.Log
import java.io.*
import java.net.MalformedURLException

// extension function to save an image to internal storage
fun InputStream.saveToInternalStorage(context: Context): Uri?{
    return try {
        val tag = "Saving stream"
        Log.i(tag, "Saving the stream from the web")
        val MEGABYTE = 1024 * 1024
        val buffer = ByteArray(MEGABYTE)
        val targetFileName = "server"
        val wrapper = ContextWrapper(context)
         /* ******************************** */
        /** What Directory Should I Select **/
        var directory = wrapper.getDir("${Environment.getExternalStorageState()}", Context.MODE_PRIVATE)
        /* ******************************** */
        // create a file to save the downloaded one
        var file = File(directory, targetFileName)
        // get the file output stream
        val fileOutputStream: OutputStream = FileOutputStream(file)

        var bufferLength = 0
        while (this.read(buffer).also { bufferLength = it } > 0) {
            fileOutputStream.write(buffer, 0, bufferLength)
        }
        fileOutputStream.flush()
        fileOutputStream.close()
        Log.v(tag, "downloadFile() completed ${Uri.parse(file.absolutePath)}")
        Uri.parse(file.absolutePath)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
        Log.e(ContentValues.TAG, "downloadFile() error" + e.message)
        Log.e(ContentValues.TAG, "downloadFile() error" + e.stackTrace)
        null
    } catch (e: MalformedURLException) {
        e.printStackTrace()
        Log.e(ContentValues.TAG, "downloadFile() error" + e.message)
        Log.e(ContentValues.TAG, "downloadFile() error" + e.stackTrace)
        null
    } catch (e: IOException) {
        e.printStackTrace()
        Log.e(ContentValues.TAG, "downloadFile() error" + e.message)
        Log.e(ContentValues.TAG, "downloadFile() error" + e.stackTrace)
        null
    }
}

layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity"
    tools:viewBindingIgnore="false">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:backgroundTint="#7BB661"
        android:text="Download Image"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="@+id/button" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="350dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvDownload"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/tvDownload"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        tools:text="Download URL"
        style="@style/TextAppearance.MaterialComponents.Subtitle2"
        android:padding="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/tvSaved"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        tools:text="Saved Uri"
        android:padding="8dp"
        style="@style/TextAppearance.MaterialComponents.Subtitle1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

</androidx.constraintlayout.widget.ConstraintLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dl">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Dl">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

build.gradle (Module)
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-parcelize'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.dl"
        minSdkVersion 30
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildFeatures {
        dataBinding true
        viewBinding true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation 'com.android.volley:volley:1.2.0'
    // kotlin coroutine
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.8'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.8'

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

UPDATE
I saw the below as sample of using jniLibs libraries for calling native lib how can I do with executing native binary whre I do not have the source code
package com.example.dl

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

open class MainActivity : AppCompatActivity() {
    companion object {
        init {
            System.loadLibrary("native-lib")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Example of a call to a native method
        val tv: TextView = findViewById(R.id.tvDownload)
        tv.text = stringFromJNI()
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    private external fun stringFromJNI(): String?
}

The *.so files had been pushed with respective platform (arm64-v8a, armeabi-v7a, x86, x86_64) folder: app/src/main/jniLibs/armeabi-v7a/native-lib.so

A: That is not supported on modern versions of Android, for security reasons. Quoting the documentation:

Untrusted apps that target Android 10 cannot invoke exec() on files within the app's home directory. This execution of files from the writable app home directory is a W^X violation. Apps should load only the binary code that's embedded within an app's APK file.

Please note that what you are doing may also violate the terms of service of your desired app distribution channel.


text:
Q: Oauth2 multiple AuthorizationServers in one app Is it possible to declare many OAuth2 authorization servers in one Spring Boot 1.4.1 app? I tried to do so, but every time only one authorization server is working at the moment.
I need it because I have two types of users that can login to my app and each of them must be separated. It's not only matter of role in a system but a purpose of the particular type of user.
So there is a way to do it that way? Or maybe I need to host two separate app, which will be my authorization servers and resource server separately?


text:
Q: JQuery recursive function? How can I call a function from inside the function, so it becomes recursive? Here is my code, I have added a comment where I would like to start the recursion:
$('a.previous-photos, a.next-photos').click(function() {
    var id = $('#media-photo img').attr('id');
    var href = $(this).attr('href');
    href = href.split('/');
    var p = href[href.length - 1];
    var url = '/view/album-photos/id/' + id + '/p/' + p;

    $.get(url, function(data) {
        $('.box-content2').replaceWith('<div class="box-content2"' + data + '
');
    });

    // here I want to call the function again

    return false;
});

A: The top answer is out of date. Currently (Aug 2012) callee is deprecated at least in Firefox.Using callee is out of date. Currently (Aug 2012) callee is "... deprecated by ECMA-262."(see discussion)
There are two problems you are running into:

*

*the function handler will only be passed the event object.

*the function is not named, so you can't refer to it for recursion

Solution for 2:
This is the easier of the two. Typically the reason for using anonymous functions is to keep a namespace clean. Parentheses define a local namespace, so after giving the function a name it will not be accessible outside the parentheses. The following will work for you:
$('.someclass').onClick( function dosomething(){
    ... your code ...
    dosomething() //again
});
dosomething() // will cause scope error, function not defined

Solution for 1:
This is a little more difficult. Since the only thing passed to the function is the event object you will need to extend that to pass in values. Fortunately, it turns out that jQuery has a system just for this!
$('.someclass').on( 'click', {myvar: 0}, function dosomething(event){
    ... your code ...
    event.data.myvar = event.data.myvar + 1;
    dosomething(event) //again
});

Note: this is especially useful for when you must attach and detach a handler to prevent inifinite loops like with DOMSubtreeModified.
$('.someclass').on( 'DOMSubtreeModified.mynamespace', {myvar: 0}, function myfunc( event ){
    $(this).off( 'DOMSubtreeModified.mynamespace' );
    ... Some Code that changes .someclass subtree ...
    event.data.myvar = event.data.myvar + 1;
    $(this).on( 'DOMSubtreeModified.mynamespace', {myvar: event.data.myvar}, myfunc );
});

A: Something of this sort should do the trick, but there ought to be a nicer way to set it up:
function myfunc() {
    var id = $('#media-photo img').attr('id');
    var href = $(this).attr('href');
    href = href.split('/');
    var p = href[href.length - 1];
    var url = '/view/album-photos/id/' + id + '/p/' + p;

    $.get(url, function(data) {
        $('.box-content2').replaceWith('<div class="box-content2"' + data + '
');
    });

    if(!cond){//you need a condition, or it'll recurse indefinitely.
       myfunc();
    }

    return false;
}

$('a.previous-photos, a.next-photos').click(function(){myfunc();});

A: You can make a recursive call to an anonymous function by doing
arguments.callee( .... );

See here for more info.

A: From Javascript 1.2 onwards you can use arguments.callee(...) to effect a recursive call to an anonymous function
// here I want to call the function again
arguments.callee();

A: Put your code in a jQuery plugin format and call itself for example...
(function($) {
$.fn.togglethis = function () {
    $(this).animate({opacity:"1.0"}, 1000, function() {
        /* Code Here */
        return $(this);
    });

}
})(jQuery);
$(document).ready(function() {
    $("#togglethis").togglethis();
});

Insert your desired code where the comment is.


text:
Q: Sort array based on values in another array - Javascript I have the following array of objects:
arr1 =  [{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}]

arr2 =   [{Name: "XYZ"}, {Name: "ABC"}, {Name: "123"}]

How can I sort arr2 based on the value of the title of arr1?
The desired output would be:
[{Name: "ABC"}, {Name: "123"}, {Name: "XYZ"}]

A: You can use built-in sort method and use findIndex(). And sort() bases upon that index. I used a common function func for getting index of both arguments of sort.

const arr1 =  [{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}]

const arr2 =   [{Name: "XYZ"}, {Name: "ABC"}, {Name: "123"}];

const func = a => arr1.findIndex(b => b.chart.title === a.Name);

const res = [...arr2].sort((a,b) => func(a) - func(b));

console.log(res)

A: Instead of sorting arr2 assign new value to it based on values in arr1 :
[{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}].map(item => ({"Name" : item.chart.title }) );

A: You could take a Map for the indices.

var array1 = [{ chart: { field: "test", title: "ABC", type: 0 } }, { chart: { field: "test", title: "123", type: 1 } }, { chart: { field: "test", title: "XYZ", type: 2 } }],
    array2 = [{ Name: "XYZ" }, { Name: "ABC" }, { Name: "123" }],
    indices = new Map(array1.map(({ chart: { title }}, i) => [title, i]));

array2.sort(({ Name: a }, { Name: b }) => indices.get(a) - indices.get(b));

console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Just create a new array of arr2 from the arr1..
arr2 = arr1.map((result) => ({Name: result.chart.title}));

Thanks.

A: Try below solution

arr1 =  [{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}]

arr2 =   [{Name: "XYZ"}, {Name: "ABC"}, {Name: "123"}]

var newArr = [];
arr1.filter(item=>{
  newArr.push(arr2.find(element => element.Name === item.chart.title));
});

console.log(newArr);


text:
Q: How to call a function after all clicks are finished whether it is a single click or after 10 clicks in rapid secession? I have plus and minus quantity buttons on cart page like
https://codepen.io/nevcanuludas/pen/WbNbow
I want to call a function to update price based on quantity after user has completed all the clicks.
i.e if user has made a single click only then call the function or if users makes 10 clicks in rapid secession then call the function once ,meanwhile letting user see the quantity is updating after every click in input box
Edit:
Let me rephrase, if user clicks once and after 500 ms the function call is made, but before 500ms if user clicks then he should be allowed update quantity and after 500ms then functions is called
var count = 1;
var countEl = document.getElementById("count");
function plus(){
    count++;
    countEl.value = count;
}
function minus(){
  if (count > 1) {
    count--;
    countEl.value = count;
  }
}

A: Witch method do you want to be called once after user finished the clicking?
The fastest way you can resolve this is if you use mouseleave, mouseout, touchleave events. What means your user has moved his mouse off the interactive area of an element. (in your case he stops clicking and he moves his mouse out) so you can update your price "once"
More info about events you can find here.


text:
Q: Два задания с указателями на C++ Посмотрите пожалуйста правильно ли я делаю?
1.Напишите код изменяющий значение указателя:
#include <iostream>
int main(){
 int i = 10;
 int *p = &i;
 *p = 5;

 std::cout << *p;

}

2.Напишите код для изменения значения, на которое указывает указатель:
 #include <iostream>
    int main(){
     int i = 10;
     int *p = &i;
     i = 5;
     std::cout << *p;

    }

A: Мне кажется, что от вас хотят
в первом случае
#include <iostream>
int main(){
    int i = 10, j = 20;
    int *p = &i;

    std::cout << *p << std::endl;
    p = &j;
    std::cout << *p << std::endl;
}

Ну, а во втором -
#include <iostream>
int main(){
    int i = 10;
    int *p = &i;

    std::cout << i << std::endl;
    *p = 20;
    std::cout << i << std::endl;
}


text:
Q: Find the elements of an array based on minimum sum I've written a loop in C++ to give me 6 random numbers and store them in an array.
 What I would like to do is to sum the elements of the array until I get a value larger than a number, "x", but I would like to do this without necessarily adding all the elements.  The objective is to find the first elements which sum to the value of x.
For example, array is [1,2,3,4,5,6], and x = 6, so what I would be looking for are the elements [1,2,3].
I've looked at the standard library and have tried using the sum function from "valarray" but this just gives the sum of all the elements.  Any ideas on how to code this successfully would be greatly appreciated.

A: I'm assuming you just want the first X elements in the array, up until their sum meets or exceeds a threshold (the question was a little vague there).
If so, I don't know how to do that without your own loop:
int sum = 0;
int i = 0;
for( ; i < len; ++i ) {
    sum += array[i];
    if( sum >= 6 ) {
        break;
    }
}

Now "i" contains the index at which the sum met or exceeded your threshold.

A: Avoid the answers that suggest using find_if with a stateful predicate. Stateful predicates are dangerous as the STL algorithms assume it is safe to copy predicates. In this case, if copies are made of the predicate then each will have a different 'running total' and will not necessarily act on all values, or in the correct order.
Especially avoid the solution that implements its predicate's operator() member as a const member function but labels its members as mutable as this is fooling you into thinking it is not a stateful predicate, which is bad.
I'd suggest using either one of the answers that simply loops to find the answer, or the answer that uses an accumulator, as that is the most correct way to do it (even if the code looks a little unwieldy.
Note that the warnings may well not apply to C arrays and find_if; I just don't want you to learn that stateful predicates are the right way to solve your problem since you may end up using that incorrect solution in a situation where it is dangerous in future.
Reference: C++ Coding Standards: 101 Rules, Guidelines, and Best Practices, Item 87

A: Substract the numbers from x one by one, until you reach 0 or lower.
No additions, as you wished :)

A: Here's a slightly more generic version:
#include <iostream>
#include <algorithm>

// return an iterator _Last such that sum
// of all elements in the range [_First, _Last)
// satisfies the predicate Func
template<class InIt,
class Ty,
class Fn> inline
InIt accumulate_if(InIt First, InIt Last, Ty Val, Fn Func)
{
    for (; Func(Val) && First != Last; ++First)
        Val = Val + *First;
    return (First);
}

int main() {
    int num[] = {1, 2, 3, 4, 5, 6};
    int *last = accumulate_if(num, num + sizeof num / sizeof num[ 0 ],
                              0, std::bind2nd(std::less<int>(), 6));
    std::copy(num, last, std::ostream_iterator<int>(std::cout, "\n"));
    return 0;
}

A: Write a functor that does the addition.
#include <algorithm>
struct SumToo
{
     SumToo(int val):m_val(val),m_sum(0) {}
     int m_val;
     int m_sum;

     bool operator()(int next)
     {
         m_sum += next;
         return m_sum >= m_val;
     }
 };

 int main()
 {
       int data[] = {1,2,3,4,5,6};

       int* find = std::find_if(data,data+6,SumToo(6));
 }

A: Well, i would use a vector
T addUntil(T array[],size_t len,T thres){
    vector<T> vec = vector_from_array(array,len)
    T sum;
    for (size_t i=0;i< vec.size(),sum<thresh;i++){
          sum+= vec[i];
    }
    return sum;
}

T would need operator+ and operator< to be defined.

A: would be something like:
struct StopAtValue{
  StopAtValue(int sum) : m_sum(sum), m_accumulated(0){}
  bool operator()(int val){
    m_accumulated += val;
    return m_accumulated >= sum;
  }
  int m_sum;
  int m_accumulated;
}

int* pos = std::find_if(&array[0], &array[n], StopAtValue(6));

A: Here's hoping this works:
/* Returns an index i, given array valarray[0,1..n] and number x where i is an index to valarry such that sum over j of valarray[j] for j = 0 to i > x */
int getFirstSum(int *valarray, int n, int x)
{
   int i = 0;
   int sum = x;
   while(sum > x && i < n)
   {
      i++;
      sum -= valarray[i];
   }
   return i;
}

A: You could use std::find_if() along with a functor that maintains a running total, and only returtn true from the functor when you have found the element that puts you at or over the top.
For example:
#include <cstdlib>
#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
using namespace std;

// functor returns true when the running total >= findVal
struct running_total : public unary_function<int, bool>
{
    running_total(int findVal) : findVal_(findVal), runningTtl_(0) {};
    bool operator()(int rhs) const
    {
        runningTtl_ += rhs;
        if( runningTtl_ >= findVal_ )
            return true;
        else
            return false;
    }
private:
    mutable int runningTtl_;
    const int findVal_;
};

int main()
{

    int nums[] = {1, 2, 3, 4, 5, 6};
    size_t count = sizeof(nums)/sizeof(nums[0]);

    const int scanTtl = 6;  // running total to scan to
    int * pos = find_if(&nums[0], &nums[0]+count, running_total(scanTtl));

    cout << "Elements Totaling " << scanTtl << " : ";
    copy(&nums[0], pos+1, ostream_iterator<int>(cout, ", "));

    return 0;
}


text:
Q: Read from "non existing" (In disk) Excel with Java POI? I have a (third party) software that loads data dinamically to an Open Excel (Via Visual Basic, I believe, but I am not sure), this excel is not saved until it is complete.
On the other side, I have a Java GUI that must read data on real-time from that Excel and show it to the user.
Is there a way to do this using POI? I already have all the algorithms and GUI ready, but third party software just changed the way it works and I need to change this.
TL:DR: I need to read from an excel that is currently open (Exists in RAM), but is still not saved into disk, is it possible?
Thank you all for your answers.

A: After working with Apache POI for some time, I can confirm:
This is impossible.


text:
Q: Finding the set of values of the real number $a$ for which $\sum_{n=1}^{\infty} (\frac 1n - \sin \frac 1n)^a$ converges
Find the set of values of the real number $a$ for which $\displaystyle\sum_{n=1}^{\infty} (\frac 1n - \sin \frac 1n)^a$ converges.

I had been stuck on this problem for a while but now I have managed to deduce following :
Using Maclaurin series for $\sin$ function,
$$\sin \frac 1n=\frac 1n - (\frac 1n)^3 \frac {1}{3!} + (\frac 1n)^5 \frac {1}{5!} - (\frac 1n)^7 \frac {1}{7!}+\dots$$
which implies
$$\frac 1n - \sin \frac 1n = (\frac 1n)^3 \frac {1}{3!} - (\frac 1n)^5 \frac {1}{5!} + (\frac 1n)^7 \frac {1}{7!}-\dots$$
and finally
$$0 \le (\frac 1n - \sin \frac 1n)^a \le ((\frac 1n)^3 \frac {1}{3!})^a$$
where the first inequality follows from the result : $\sin x \le x \; \forall x\gt 0$.
Hence
$$ 0 \le \sum_{n=1}^{\infty} (\frac 1n - \sin \frac 1n)^a \le \sum_{n=1}^{\infty} ((\frac 1n)^3 \frac {1}{3!})^a=\sum_{n=1}^{\infty} (\frac {1}{3!})^a \frac 1{n^{3a}}=(\frac {1}{3!})^a\sum_{n=1}^{\infty}\frac 1{n^{3a}}.$$
Last inequality converges for $3a \gt 1.$
Thus the given series converges for $a \in (\frac 13, \infty).$
Are there any loopholes in this solution? What are other ways to think about this problem?

A: You did not prove that the series is not convergent for $a\leq 1/3$. Actually, by using a similar argument you can show that there are two positive constant $C_1$, $C_2$ and $N$ such that for all $n\geq N$,
$$\frac{C_2}{n^3}\leq \frac 1n - \sin \left(\frac 1n\right)\leq \frac{C_1}{n^3}$$
which implies that given series converges if and only if  $a>1/3$.
P.S. The existence of the above constants follows from the limit
$$\lim_{n\to \infty}\frac{\frac 1n - \sin \left(\frac 1n\right)}{\frac {1}{n^3}}=\frac{1}{6}.$$

A: For the divergence:
\begin{align*}
\sum_{n}\left(\frac{1}{n}-\sin\frac{1}{n}\right)^{a}&\geq\sum_{n}\left(\frac{1}{3!}\frac{1}{n^{3}}-\frac{1}{5!}\frac{1}{n^{5}}\right)^{a}\\
&=\frac{1}{(3!)^{a}}\sum_{n}\frac{1}{n^{3a}}\left(1-\frac{3!}{5!}\frac{1}{n^{2}}\right)^{a}\\
&\geq\frac{1}{(3!)^{a}}\frac{1}{2^{a}}\sum_{n\geq N}\frac{1}{n^{3a}}
\end{align*}
for large $N$, so it diverges for all $a\in(0,1/3]$. For $a\leq 0$ is clear, because the tail does not converge to zero.


text:
Q: How to get user defined language in Notepad++ to follow master formatting? I have successfully created a user defined language file in Notepad++ and this file has formatting, highlighting, etc.
What I am hoping to do however is tie these into the main theme is. But it looks like each of these are defined separately (see \Notepad++\themes*.xml files).
Is there a good way to incorporate a custom language into these? Or is my only bet to write a script to merge the userDefineLang.xml with the themes?

A: You can copy the style you want from the file stylers.xml and modify it into your own style. It is located in C:\Users\yourUserName\AppData\Roaming\Notepad++\stylers.xml.


text:
Q: Sparklyr configuration results in java.lang.OutOfMemoryError I am running sparklyr with R on a local instance with 8 cores and 64Gb RAM. My job is to left_join a [50 000 000, 12] dataframe with a [20 000 000, 3] dataframe, which I run with Spark.
# Load packages
library(tidyverse)
library(sparklyr)

# Initialize configuration with defaults
config <- spark_config()

# Memory
# Set memory allocation for whole local Spark instance
# Sys.setenv("SPARK_MEM" = "50g")

# Set driver and executor memory allocations
# config$spark.driver.memory <- "8g"
# config$spark.driver.maxResultSize <- "8g"

# Connect to local cluster with custom configuration
sc <- spark_connect(master = "local", config = config, spark_home = spark_home_dir())

# Read df1 and df2
df1 <- spark_read_parquet(sc,
                          path = "/mnt/df1/",
                          memory = FALSE, overwrite = TRUE)
df2 <- spark_read_parquet(sc,
                          path = "/mnt/df2/",
                          memory = FALSE, overwrite = TRUE)

# Left join
df3 <- df1 %>%
  dplyr::left_join(df2)

# Write or collect
sparklyr::spark_write_parquet(df3, path="/mnt/") # or
df3 <- df3 %>% collect()

No matter how I configure the Spark configuration file, the code fails with a java.lang.OutOfMemoryError: Java heap space.
Error: org.apache.spark.SparkException: Job aborted due to stage failure: Task 2 in stage 8.0 failed 1 times, most recent failure: Lost task 2.0 in stage 8.0 (TID 96, localhost, executor driver): java.lang.OutOfMemoryError: Java heap space

I have tried so far different combinations of
Sys.setenv("SPARK_MEM" = "50g")
config["sparklyr.shell.driver-memory"] <- "20G"
config["sparklyr.shell.num-executors"] <- 8
config$spark.driver.maxResultSize <- "8g"
config$spark.executor.memory <- "8g"
config$spark.memory.fraction <- 0.9

either in the R script or in the spark configuration file.
Similar questions have been asked 1
2
3 but none of these solved my problem.

A: You must specify a join key to left_join().
Otherwise you are trying to compute the cartesian product, which has size [1 000 000 000 000 000, 15] and surely overflows memory.
Also: avoid calling collect() on big datasets, since this will move all data back to the driver and has high chances of OOM on the driver.


text:
Q: mod_rewrite removing name of query string I have big problem with my urls. I know how to remove index.php form url, but problem is that I don't know to remove that "?act=" from url.
My link now is http: //localhost/doctrine/public/?act=test and I want to create it like http: //localhost/doctrine/public/test.
My current .htaccess file placed in public folder:
<IfModule mod_rewrite.c>
        RewriteEngine On

        # Removes index.php from ExpressionEngine URLs
        RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php/$1 [L]

</IfModule>

I need help how to do that.

A: Before your expression engine rule, you can add:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ /doctrine/public/?act=$1 [L]

To internally rewrite a request like http: //localhost/doctrine/public/test to /doctrine/public/?act=test. You need to make sure the links in your content look like /doctrine/public/test instead of the one with the query string. If there are links outside of your control (like google indexed pages) you can add this:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /doctrine/public/?\?act=([^&\ ]+)
Rewrite Rule ^ /doctrine/public/%1? [L,R=301]

to point browsers to the URL without the query string.
This unfortunately isn't going to be compatible with your expression engine URLs.

A: Use this code:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /doctrine/

    RewriteRule ^(public)/([^/]+)/?$ $1/?act=$2 [L,QSA,NC]

    # Removes index.php from ExpressionEngine URLs
    RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

</IfModule>


text:
Q: Is it possible to convert any size to base64 characters? I know my question is kinda awkward but i really couldn't find the answer till now.
Is it possible to convert any video format (whatever was the size) to base 64 characters ?
Yes or No ?
Thank you in advance :)

A: Yes. Base64 is a method for encoding arbitrary binary data into text. There is nothing inherent in the format that would limit the size.


text:
Q: Android RecyclerView after scrolling vertical showing last loaded images before load new content? I have a recyclerview showing list of images(download from API).when I scroll the view it first show the last loaded images and then load the new content.I don't want to show last loaded content again and again on scroll.
@Override
public void onBindViewHolder(ProductItemViewHolder holder, int position) {
    ProductItem item = dataSet.get(position);

    String url = new ApiCalls(holder.photo.getContext()).getBaseUrl() + item.getImages().getImageUrl().get(0);

    //to do

    new ImageViewLoader(taskObserver, holder.photo, url)
            .setDesiredRatio(1.0f)
            .setFallback(R.drawable.img_default_phone)
            .load();

    String percentage = item.getSalePercentage();
    if (percentage != null && !percentage.isEmpty()) {
        holder.badge.setVisibility(View.VISIBLE);
        holder.badge.setText(percentage);
    } else if (item.isNew()) {
        holder.badge.setText(holder.badge.getContext().getString(R.string.product_grid_item_badge_new));
    } else {
        holder.badge.setVisibility(View.GONE);
    }

    holder.productName.setText(item.getProductName());

    String salePrice = item.getSalePrice();
    if (salePrice != null && !salePrice.isEmpty()) {
        holder.price.setVisibility(View.VISIBLE);
        holder.price.setText(formatPrice(item.getCurrency(), item.getPrice()));
        holder.price.setPaintFlags(holder.price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

        holder.salePrice.setText(formatPrice(item.getCurrency(), salePrice));
        holder.salePrice.setTextColor(holder.salePrice.getContext().getResources()
                .getColor(R.color.red_100));
    } else {
        holder.price.setVisibility(View.INVISIBLE);
        holder.salePrice.setText(formatPrice(item.getCurrency(), item.getPrice()));
        holder.salePrice.setTextColor(holder.salePrice.getContext().getResources()
                .getColor(android.R.color.black));
    }
}

A: I'm not sure exactly what you mean by "it first show the last loaded images and then load the new content.", but I have two guesses:

*

*Since the parameter into onBindViewHolder is often a recycled view holder, it's state is kept as it is scrolled out of view. That means new items contain the the images & text of the recycled items unless you re-set them in onBindViewHolder.

*The ImageViewLoader which we don't see any source for, does it cancel the ongoing request if a new one is submitted for the same view holder? The effect you are seeing could be that the loader for the old image is still trying to download the image, but completes later on when the item has already been recycled.

A: Use recyclerView.scrollToPosition(dataSet.size()-1);


text:
Q: psql query number of rows in multiple tables and save in variable I'm trying to query the total number of records across multiple PostgreSQL tables in a shell script.
The shell script is to be executed by a build pipeline and the pipeline needs to know the number of total number of rows.
shell script
docker run -it postgres psql "host=xxx.com port=5432 dbname=xxx user=xxx password=xxxw" -f row_count.sql

row_count.sql
select SUM(row_count)
from (
    SELECT count(*) as row_count
    FROM "table_a"
    union all
    SELECT count(*) as row_count
    FROM "table_b"
    union all
    SELECT count(*) as row_count
    FROM "table_c"
) as total

I have tested my query and it's fine, but having difficulty reading the sql file from the psql command and I'm not sure how to save the number of records in a variable to be read by the pipeline.

A: to execute a command in an shell script, use backticks.
https://unix.stackexchange.com/questions/27428/what-does-backquote-backtick-mean-in-commands
So your command will look like that:
PGRESULT=`docker run -it postgres psql "host=xxx.com port=5432 dbname=xxx user=xxx password=xxxw" -f row_count.sql`

the result is stored in PGRESULT. Read the manpage to psql, maybe adding some parameters to psql helps further working with values in PGRESULT.

-t
--tuples-only
Turn off printing of column names and result row count footers, etc. This is equivalent to \t or \pset tuples_only.
-c command
--command=command
Specifies that psql is to execute the given command string, command. This option can be repeated and combined in any order with
the -f option. When either -c or -f is specified, psql does not
read commands from standard input; instead it terminates after processing all the -c and -f options in sequence.
-A
--no-align
Switches to unaligned output mode. (The default output mode is otherwise aligned.) This is equivalent to \pset format unaligned.
-F separator
--field-separator=separator
Use separator as the field separator for unaligned output. This is equivalent to \pset fieldsep or \f.


text:
Q: Error adjusting column name in a dataset in R Can you help me to adjust the code below, as I am not able to properly rename the columns of my data.
df<-structure(c(10839.2814863901, 2, 10227.8884004375, 187965), .Dim = c(1L,
4L), .Dimnames = list(NULL, c("X", "Y", "Z",
"W")))

            X Y        Z      W
[1,] 10839.28 2 10227.89 187965

df1<-df[,2:4]

    Y         Z         W
 2.00  10227.89 187965.00

colnames(df1) = c("Name1","Name2","Name3")

Error in `colnames<-`(`*tmp*`, value = c("Name1", "Name2", "Name3")) :
  attempt to set 'colnames' on an object with less than two dimensions

A: The issue is that df is not actually a data frame; df is a numeric matrix. When you subset the numeric matrix, it creates a numeric vector which does not take column names. You can fix things by converting df to a data frame.
df<-structure(c(10839.2814863901, 2, 10227.8884004375, 187965), .Dim = c(1L,
4L), .Dimnames = list(NULL, c("X", "Y", "Z",
"W")))

df <- as.data.frame(df)

df1<- df[,2:4]

colnames(df1) <- c("Name1","Name2","Name3")


text:
Q: Biztalk schema deployed as one way service, how? I have a Biztalk 2009 project with a receive location using a SOAP adapter. Now it uses a request-response schema and I want to refactoring it in a asynchronous design, by only using the request schema (a one way scenario).
If I want to use the Biztalk Web Services Publishing Wizard, but I must use a response schema to let the wizard go to finish the job.
Is it - in Biztalk - required to always have a response type for every SOAP call ?

A: No, you can use one-way services with the SOAP-adapter in BizTalk (WCF-receive and send are a bit different however). All you need to do is to remove the two default methods you'll get in the wizard, add a new one as one-way and set it to the schema you'd like to use. Done.

A: You can create a service that does not send an explicit response using the BizTalk WCF Publishing wizard (by adding a new, one-way service to the service when "creating WCF service from schemas"), but note that you aren't really creating an asynchronous WCF service.
Specifically, the WCF isOneWay flag is NOT set to "true", but rather, you are creating a WCF service that simply returns void.  This may not be an issue for your design, but good to be aware of (source: http://msdn.microsoft.com/en-us/library/bb226362(BTS.70).aspx).


text:
Q: set startDate of one datepicker as selected date from another datepicker I have two datepicker in my page to seletect From and To dates. From datepicker's end date is set to today and To datepicker's end date is set to today. Also i need to set startdate for To datepicker to selected date from From datepicker. Please help me.
here is my code
<input type="text" placeholder="From" id="reportFrom" name="reportFrom" value="<?php echo $reportFrom?>">
<input type="text" placeholder="To" id="reportTo" name="reportTo" value="<?php echo $reportTo;?>">

Script:
$('#reportFrom').datepicker({
        autoHide: true,
        autoclose: true,
        endDate: new Date(),
        onSelect: function(dateStr)
        {
            $("#reportTo").val(dateStr);
            $("#reportTo").datepicker("option",{ startDate: new Date(dateStr)});
        }
    });
    $('#reportTo').datepicker({
        autoHide: true,
        autoclose: true,
        //startDate : $('#reportFrom').val(),
        endDate: new Date()
    });

A: This is the HTML:
<input type="text" id="dateFrom" />
<input type="text" id="dateTo" />

and this is the jquery:
$(document).ready(function () {

    $("#dateFrom").datepicker({
        dateFormat: "dd-M-yy",
        minDate: 0,
        onSelect: function (date) {
            var date2 = $('#dateFrom').datepicker('getDate');
            date2.setDate(date2.getDate());
            $('#dateTo').datepicker('setDate', date2);
            //sets minDate to dt1 date
            $('#dateTo').datepicker('option', 'minDate', date2);
        }
    });
    $('#dateTo').datepicker({
        dateFormat: "dd-M-yy",
        onClose: function () {
            var dt1 = $('#dateFrom').datepicker('getDate');
            console.log(dt1);
            var dt2 = $('#dateTo').datepicker('getDate');
            if (dt2 == dt1) {
                var minDate = $('#dateTo').datepicker('option', 'minDate');
                $('#dateTo').datepicker('setDate', minDate);
            }
        }
    });
});


text:
Q: Android fragment slide out animation not working I have a two fragments top and bottom . On swipe down gesture, bottom fragment is hidden and on swipe up, it's shown again. swipe up slide up animation is working, but not the swipe down animation during swipe down.
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/baseLinear"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <RelativeLayout
        android:id="@+id/containerParent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/container1Parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/container1Parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true" >

        <FrameLayout
            android:id="@+id/container1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </RelativeLayout>

  case SimpleGestureFilter.SWIPE_UP:
    str = "Swipe Up";
 getSupportFragmentManager()
 .beginTransaction()
 .setCustomAnimations(R.anim.abc_slide_in_bottom,
 R.anim.abc_slide_out_bottom).show(bottomFragment)
    .commit();
   break;

abc_slide_in_bottom.xml
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="50%p"
android:interpolator="@android:anim/decelerate_interpolator"
android:toYDelta="0" />

abc_slide_out_bottom.xml
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toYDelta="50%p" />

NOTE : Bottom fagment takes up only 20 % of total screen


text:
Q: Jupyter Notebook does not sync with PyCharm Suppose that I create an .ipynb in PyCharm, and then start an IPython Notebook kernel. Then if I modify the notebook in the browser, how do I get the changes back to PyCharm?
There is a 'synchronize' function when I right-click the file name in PyCharm but it does not seem to do anything.

A: One possible solution is:

*

*Once started the Jupyter server started, make sure the file edited through Jupyter is closed in Pycharm

*Save the Jupyter Notebook: 'Save and checkpoint' method

*In Pycharm, synchronize the notebook

*The notebook can be now opened and the changes appear

I guess the reason of the error is that while the notebook is opened is pycharm, pycharm edit it and overwrite at anytime the modications done by the jupyter server. Yet, it is only a guess, I have no certainty about the origin of such behaviour.

A: Try to save using checkpoints. You can always go to the last checkpoint you added

A: In the browser, go to File, select Save and Checkpoint. It should appear a window saying: "The notebook file has changed on disk since the last time we opened or saved it. Do you want to overwrite the file on disk with the version open here, or load the version on disk (reload the page) ?"
Then press overwrite, and the changes are overwritten to the file on your pc. Apparently the syncro it's not realtime (I guess this is a bug, since a window pops up in pycharm, but it seems useless), if you have your ipynb open, you should close it and reopen it to see the update.

A: For me, invalidating the PyCharm cache worked.

*

*File > Invalidate Caches / Restart…

*Invalidate and Restart. (Just Invalidate might also work.)

A: To synchronize Jupyter with PyCharm, you must to add in Pycharm the path of the Jupyter interpreter.
For example, if you use an Anaconda/Conda environment and Python language, you must add the path of the Python that uses Anaconda in:

*

*File > Settings > Project Interpreter

*Click the '*' button (screw) > Add > Conda Environment

*Choose the correspondent path (e.g. '~/anaconda/bin/python')

*OK > Apply


text:
Q: Realign HTML using javascript I have a HTML like this :
"""<input type="submit" id="continue" value="CRA" name="continue" class="keyboard-enabled" tabindex="7">

    <input type="button" id="r1B" value="Back" role="option" aria-pressed="false" class="keyboard-enabled" tabindex="6">
"""

I want to move my first input down to <a using jquery replace or something like this in JS. How to achieve this ?
Expected output :

    <input type="button" id="r1B" value="Back" role="option" aria-pressed="false" class="keyboard-enabled" tabindex="6">

<input type="submit" id="continue" value="CRA" name="continue" class="keyboard-enabled" tabindex="7">

A: Try this : use .after()
$(function(){
  $('#r1A').after($('#continue'));
});


text:
Q: nextjs fetching data in a nested manner I have a function getTeamRoster and getPlayerProfile. I'm getting a list of players from getTeamRoster within getServerSideProps, which includes the id.
My question is how do I then get the data from getPlayerProfile function where I need to loop through getTeamRoster to capture the id and then pass it into getPlayerProfile.
async function getTeamRoster(id) {
    const res = await fetch("apidata.json", {
        method: "GET",
    });
    const data = await res.json();
    return data;
}

async function getPlayerProfile(id) {
    const res = await fetch("apidata/"+id+"/profile.json", {
        method: "GET",
    });
    const data = await res.json();
    return data;
}

export const getServerSideProps = async (context) => {
    const id = context.params.id;
    const teamRoster = await getTeamRoster();
    const playerProfile = await getPlayerProfile();

    return {
        props: {
            teamRoster,
            playerProfile
        }
    }
}

const Schedule = ({ teamRoster, playerProfile }) => {
    return (

                {teamRoster.players.map(async player => {

                    // would this be the correct way of doing it?
                    const playerStats = await getPlayerProfile(player.id);
                    return (

                            {player.full_name}

                )})}

    )
}

export default Schedule;


text:
Q: Why does my Ajax.BeginForm reload the entire page when I have specifically targeted an ID for replacement? Apologies in advance for the question, but though I found numerous suggestions here, none have worked out for me.  I'm feeling crazy, so...
I have an MVC 3 application that, when it first loads up, displays table with Model data for all users.  That part works fine.  I have two text boxes, one for account ID and another for user that allows me to requery the database for more specific user data.  When I use the submit button, I get the data back but the entire page refreshes and, while I get the form and table back with the correct data, the rest of the page is white.  No graphics I had previously or anything. Another interesting thing is that if i submit the form again, from the white page, with whatever valid parameters, the AJAX DOES work. I'm baffled.
The form looks like this:
@using (Ajax.BeginForm("TaskList", "Dispatch",
       new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "tblBody",
       InsertionMode = InsertionMode.Replace }, new { id = "frmTaskList" }))
{

                Ticket ID
                Date
                Customer Name

            @{for (var ix = 0; ix < Model.Value.Count - 1; ix++)
            {

                    @Model.Value[ix].TicketId
                    @Model.Value[ix].Created
                    @Model.Value[ix].ContactName

            }}

    <input type="text" id="hidAccId" name="hidAccId" value="" />
    <input type="text" id="hidUserId" name="hidUserId" value="" />
    <input type="submit" id="btnTaskList" value="Submit" />
}

Also the scripts I'm using, placed at the top of the page:

Side note: I have tried using @Url.Content instead of the src attribute to no avail.  I've also experimented using the following, again with no different result:

A: You have jQuery and jQuery-ui referenced twice. It's not necessary. The following should be enough:

You obviously should ensure that jquery-1.7.2.min.js is present in the Scripts folder. Out of the box ASP.NET MVC 3 comes only with jQuery 1.5. As far as the Microsoft* scripts are concerned, forget about those, they are no longer used in ASP.NET MVC 3.
Also you don't have a submit button in your form.
This:
<input type="button" id="btnTaskList" value="Submit" />

should be:
<input type="submit" id="btnTaskList" value="Submit" />

if you expect a form submission to happen.


text: Q: cant echo or touch into file.txt Read only File system Hi I cannot touch or Echo into file because it says Read only file system (these are the permissions from the Root directories) how to change file system so I can write files and so forth?


text:
Q: Authorize.Net Paypal Express PHP API: Issue with transaction not updating in Authorize.Net , nor capturing correct amount We've implemented the Paypal Express API through Authorize.Net  in PHP (https://developer.authorize.net/api/reference/features/paypal.html). It was finished over a year ago, and has been working fine. What we realized recently, is that the when the Paypal authorization is updated in step 2 "Authorization Only, Continued", it is not updated in Authorize.Net . When a capture takes place, it only captures the original amount, despite Paypal having the correct, updated amount.
Here is our flow (following the Authorize.Net/Paypal API instructions):

*

*We send a request to Authorize.Net/Paypal to create a transaction. Inside is the total cost of goods.

*Paypal returns a secure link, onto which we redirect the user

*Paypal redirects the user back to us with a token. We use the token to get shipping data for the user and to get the authorization/transaction ID.

*We calculate tax based on shipping data and send the user to a confirm page for review.

*When the user submits, we send the second authorization request (Authorization Only, Continued), as documented, using the gateway transaction ID to update the transaction with the new amount, etc.

Now the problem is, Authorize.Net still has the original amount (without the tax). When we run a capture on this transaction via the same API, for some reason it only captures the original amount, not the amount with the tax. We're making tons of transactions now, and not receiving the tax dollars for any of them.
Here is the same transaction in Paypal and Authorize.Net. Paypal's screen shows the authorization at $120, and the update at $130.xx with shipping.

And Authorize.Net shows it successfully captured at $120.

These are the same transaction, and we're only using the Authorize.Net Paypal Express API. How is Authorize.Net not getting the update? Why is it not capturing the full amount?

A:
When we run a capture on this transaction via the same API, for some reason it only captures the original amount, not the amount with the tax.

You need to either:

*

*Capture the second authorization, not the original transaction. This should be the correct solution.

*Send a capture request that includes the details of the new amounts you are capturing.


text:
Q: SwiftUI with MVVM + Realm database: How to create a list with elements? I want to use a realm database in my SwiftUI app and I would like to apply the MVVM pattern. Unfortunately when I create a list with the elements in my database I get a Fatal error: Unexpectedly found nil while unwrapping an Optional value: error message
DatabaseManager:
class DatabaseManager{

    private let realm: Realm
    public static let sharedInstance = DatabaseManager()

    private init(){
        realm = try! Realm()
    }

    func fetchData<T: Object>(type: T.Type) -> Results<T>{
        let results: Results<T> = Realm.objects(type)
        return results
    }
}

Model:
class FlashcardDeck: Object, Codable, Identifiable{
    @objc private (set) dynamic var id = NSUUID().uuidString
    @objc dynamic var title: String?
    var cards = RealmSwift.List<Flashcard>()

    convenience init(title: String?, cards: [Flashcard]){
        self.init()
        self.title = title
        self.cards.append(objectsIn: cards)
    }

    override class func primaryKey() -> String? {
        return "id"
    }
}

ViewModel
class FlashcardDeckViewModel: ObservableObject{
    let realm = DatabaseManager.sharedInstance
    @Published var decks: Results<FlashcardDeck>?

    public func fetchDecks(){
        decks = realm.fetchData(type: FlashcardDeck.self)
    }
}

View
struct FlashcardDeckView: View {
    private let gridItems = [GridItem(.flexible())]
    @StateObject var viewModel = FlashcardDeckViewModel()

    var body: some View {
        NavigationView{
            ScrollView{
                LazyVGrid(columns: gridItems, spacing: 30){
                    ForEach(viewModel.decks!) { item in // <----- ERROR APPEARS HERE
                        FlashcardDeckItem(deck: item)
                    }
                }
            }
            .navigationTitle("Flashcard decks")
        }
        .onAppear{
            self.viewModel.fetchDecks()
            print(self.viewModel.cards?[0].title) // <------ prints the title of the deck! So this element exists
        }
    }
}

I'm pretty sure that my database has an element and if I try to print the name of the deck in the fetchData()function it will be displayed. I know the line ForEach(viewModel.decks!)isn't beautiful code, but this is just for testing/debugging now.

A: Include it conditionally, like
    NavigationView{
      if viewModel.decks == nil {
        Text("Loading...")
      } else {
        ScrollView{
            LazyVGrid(columns: gridItems, spacing: 30){
                ForEach(viewModel.decks!) { item in // <----- ERROR APPEARS HERE
                    FlashcardDeckItem(deck: item)
                }
            }
        }
        .navigationTitle("Flashcard decks")
      }
    }


text:
Q: How to make a method that finds every object by id in angular Please help,
I want to make a method findChildByIdInData(data:any, childId:string) where the data is any JSON main node that has children with Ids.
Simply, how to make a method that receives JsonNode and its child Id as parameters to find that object using angular.
In my case, I have a data as a node where I want to find its children's objects (may be nested) by id.
Thanks for your time :)

A: To implement lodash
https://stackoverflow.com/a/41992126/18762612
import { get } from "lodash";

variable in component
deepObj = {a:{b:{n:{e:100, c: 120}}}

example of get
constructor(){
 get(deepObj, 'a.b.n.e');
}

A: Got the result by using the  Recursively Traverse an Object method:
this link helps me: https://cheatcode.co/tutorials/how-to-recursively-traverse-an-object-with-javascript.
the backendService:
// Verify the object
     isObject(value): any {
        return !!(value && typeof value === "object");
      };

      // Find object in node
      findNestedObject(object: {}, keyToMatch: String, valueToMatch: String): any {
        if (this.isObject(object)) {
          let entries = Object.entries(object);

          for (let i = 0; i < entries.length; i += 1) {
            const [objectKey, objectValue] = entries[i];

            if (objectKey === keyToMatch && objectValue === valueToMatch) {
              return object;
            }

            if (this.isObject(objectValue)) {
              let child = this.findNestedObject(objectValue, keyToMatch, valueToMatch);

              if (child !== null) {
                return child;
              }
            }
          }
        }

        return null;
      };

and call that method in component as:
 // Find the nested object by passing node, key, & value
        // the this.shop is your backend data or json
        let  result = this.backendService.findNestedObject(this.data, "id", "dataId");
        console.log("Result: ", result);


text:
Q: Set RadioButton checked onResume Creating app in which i am setting data in recyclerview list and showing that data using radiobutton in radiogroup and text.I am able to check radiobutton,but when i again open that activity my checked radiobutton is unchecked,but i want that when i again open activity my radiobutton shoulde be checked.
Here is my Adapter class :
holder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton checked_rb = (RadioButton) group.findViewById(checkedId);
                    holder.radioButton.setChecked(true);

                if (lastCheckedRB != null) {
                    lastCheckedRB.setChecked(false);
                }
                if(selectedId!=0)
                {
                    holder.radioButton.setChecked(true);
                }

                //store the clicked radiobutton
                if(holder.radioButton.isChecked())
                {
                    teamList.clear();
                    lastCheckedRB = checked_rb;
                    teamList.add(name);

                    int checkedIndex = group.indexOfChild(checked_rb);
                }
                else
                {
                    holder.radioButton.setChecked(false);
                }
                int selectedId = holder.radioGroup.getCheckedRadioButtonId();

            }

Here is my Activity class :
protected void onResume() {
    super.onResume();
    try {
        adapter.lastCheckedRB.setChecked(true);
        }
        adapter.notifyDataSetChanged();
    } catch (NullPointerException e) {

    }
}

A: Because u activity is not have focus.
https://lh6.googleusercontent.com/-cRgfIY8Y0pE/ToyPWqE3L4I/AAAAAAAAAbM/mfpvj5yabiA/s800/20111005_L0023_L_StatesSchema.jpg


text:
Q: Trying to Right an AND-ed SQL Expression I'm trying to create a SQL expression for an INSERT policy for a resource_authors table (a JOIN table linking resources and users):
CREATE POLICY insert_resources_authors ON public.resource_authors
    FOR INSERT TO public_user
    WITH CHECK (*some expression*)

What I'd like to say is "the user must be logged in and there must not be an existing author record for that resource yet".  I can express the first part using a custom current_user_id function I have:
current_user_id() IS NOT NULL

And I can get the second with:
SELECT count(user_id) > 0
FROM resource_authors
WHERE resource_id = resource_id

... but I can't figure out how to combine them.  Can anyone clue me in to how I can select both, as a single boolean?

A: Literally place an AND between them (and wrap them in parenthesis to make clear they're subqueries):
(current_user_id() IS NOT NULL)
AND
NOT (SELECT count(user_id) > 0
  FROM resource_authors
  WHERE resource_id = resource_id)

I'd write
CREATE POLICY insert_resources_authors ON public.resource_authors
    FOR INSERT TO public_user
    WITH CHECK (
        current_user_id() IS NOT NULL
        AND
        NOT EXISTS (SELECT *
            FROM resource_authors ra
            WHERE ra.resource_id = resource_authors.resource_id
        )
    );

However I find it questionable to allow anyone to make themselves author of any authorless resource. I'd rather record the author via a trigger when they create the resource.


text:
Q: Cookie Overflow in Rails 4 even with memcachd server I'm converting a Rails 3 app, which used active_record_store for storing session information that was too large for regular cookies, to Rails 4, which has deprecated active_record_store. My Rails 4 app is raising the error...
ActionDispatch::Cookies::CookieOverflow (ActionDispatch::Cookies::CookieOverflow):

that caused me to switch to active_record_store in Rails 3. What can I do in Rails 4 if my session information exceeds the allowable limits?
Update. I started the memcache server on my local machine and configured it like so in the development file
config.cache_store = :mem_cache_store, 'localhost', '127.0.0.1:11211',
{:namespace => 'myapp123'}

In the console, when I do Rails.cache, it shows this (followed by a lot of data)
=> true
>> Rails.cache
=> #<ActiveSupport::Cache::MemCacheStore:0x007f80ebe10500 @options={}, @data=#<Dalli::Client:0x007f80ebe0fd08 @servers=["localhost:11211"]

However I'm getting the same error when I'm running the application
ActionDispatch::Cookies::CookieOverflow (ActionDispatch::Cookies::CookieOverflow):
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/cookies.rb:455:in `[]='
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/session/cookie_store.rb:109:in `set_cookie'
  rack (1.5.2) lib/rack/session/abstract/id.rb:350:in `commit_session'
  rack (1.5.2) lib/rack/session/abstract/id.rb:226:in `context'
  rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/cookies.rb:486:in `call'
  activerecord (4.0.0.rc2) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.0.0.rc2) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call'
  activerecord (4.0.0.rc2) lib/active_record/migration.rb:369:in `call'
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.0.0.rc2) lib/active_support/callbacks.rb:373:in `_run__1963944942928963409__call__callbacks'
  activesupport (4.0.0.rc2) lib/active_support/callbacks.rb:80:in `run_callbacks'
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/reloader.rb:64:in `call'
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.0.0.rc2) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.0.0.rc2) lib/rails/rack/logger.rb:21:in `block in call'
  activesupport (4.0.0.rc2) lib/active_support/tagged_logging.rb:67:in `block in tagged'
  activesupport (4.0.0.rc2) lib/active_support/tagged_logging.rb:25:in `tagged'
  activesupport (4.0.0.rc2) lib/active_support/tagged_logging.rb:67:in `tagged'
  railties (4.0.0.rc2) lib/rails/rack/logger.rb:21:in `call'
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.0.0.rc2) lib/active_support/cache/strategy/local_cache.rb:83:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.0.0.rc2) lib/action_dispatch/middleware/static.rb:64:in `call'
  railties (4.0.0.rc2) lib/rails/engine.rb:511:in `call'
  railties (4.0.0.rc2) lib/rails/application.rb:97:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  /Users/mm/.rbenv/versions/1.9.3-p327/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
  /Users/mm/.rbenv/versions/1.9.3-p327/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
  /Users/mm/.rbenv/versions/1.9.3-p327/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'

A: you can only store 4kb in session if you are using cookie store. You have two options.

*

*Look at reducing the information you are storing in session. If you are storing a model object in session, change it to store just the id.

*Use mem_cache_store
config.action_controller.session_store = :mem_cache_store
Also you need to setup a mem cache server and configure it as below:
config.cache_store = :mem_cache_store, 'localhost', '127.0.0.1:11211',
{:namespace => 'myapp123'}

A: Can you show me the content of config/initializers/session_store.rb seems like you still use the cookie store there.
When you define the cache store, you still have to change the session_store
config.session_store = :mem_cache_store


text:
Q: How can I get size of array after innerHTML.split? I got a string "Testing - My - Example"
And I want to split it with " - ".
like this:
variable = innerHTML.split(" - ");

how do i get the size of the array?

A: variable.length

A: Try this:
variable.length


text:
Q: Merging sets in C++, also overloading operators I'm trying to merge two sets of quartets (a class which I've defined).
Before I go into the merging, let me ask a question about operator overloading. If I want to overload the operator of a class, does it make a difference whether I do it within the class or outside the class?
For instance, if I did it within the class, my function header would be
bool quartet::operator<(const quartet& other)

But if I did it outside of the class, my function header would be
bool operator<(const quartet& one, const quartet& two);

I've been switching between the two because I believe it eliminated some error in one place but created another, although I could not replicate them at the time of writing this.
OK, now onto merging.
Right now the following code is working (where A,B,C, and D are defined above, and A==C)
  set<quartet> Qset;
  set<quartet> result;
  Qset.insert(A);
  Qset.insert(B);
  set<quartet> Qset2;
  Qset2.insert(C);
  Qset2.insert(D);
  merge(Qset.begin(), Qset.end(), Qset2.begin(), Qset2.end(), inserter(result, result.end()));
  printSet(result);

So, my first question is, if I change the last parameter of merge from inserter(result, result.end()) to result.begin(), I get the compiler error:
/usr/include/c++/4.6/bits/stl_algobase.h:299:6: error: passing 'const quartet' as 'this' argument of 'quartet& quartet::operator=(const quartet&)' discards qualifiers [-fpermissive]
make: *** [quartet.o] Error 1

Why do I get this error? My understanding is that the last parameter of merge takes an iterator to where the elements should be merged to, so why would that not be result.begin()? Furthermore, what exactly is inserter?
More generally, I'm eventually going to be working with large, sorted sets. Would it be faster to call merge or to call set_union? What is the difference between the two?
Finally, could I not just call set2.insert(set1.begin(), set1.end()) to merge the two sets together?
Thank you

A: The difference between declare the overloading operator in C++ inside the class and outside of it rely on call semantic and order of objects implied.
This call need that the left most object be a quartet type.
bool quartet::operator<(const quartet& other)

While this call, allow anything that can be converted to quartet via automatic type conversion.
bool operator<(const quartet& one, const quartet& two);

see C++ overloading conversion operator for custom type to std::string
By second question, related to error, you're getting it because you need to specify that the < operator could not modify the class. You need to specify the function as const:
bool quartet::operator<(const quartet& other) const

and the you could use insert to merge these two sets.

A: You're getting that error because you need to tell the compiler that your < operator does not modify the class. You do that by declaring the member function as const:
bool quartet::operator<(const quartet& other) const

Also set2.insert(set1.begin(), set1.end()) seems like it would work just fine.


text:
Q: Angular 4: Scroll to top of page programmatically Does anyone know how to use Angular 4 and programmatically scroll the page to the top?  My usescase is that I have a search page, and the input is at the top, and links to the other search results pages are at the bottom.  When the user clicks a link (2,3,4...) I would like the page to populate with the new results (functionality is complete) and then scroll to the top of the page to show the results (this functionality is not complete).
I've see that this is possible with JQuery (Scroll to top of page) but I was wondering if there was a way to stay in the Angular 4 stack.
Any help is greatly appreciated.

A: You don't need additional library to do this. A standard HTML tag will be sufficient by using below syntax

   Something.....

Click Here .....!

A: Just use the native JavaScript window.scrollTo method -- passing in 0,0 will scroll the page to the top left instantly.
window.scrollTo(xCoord, yCoord);

Parameters

*

*xCoord is the pixel along the horizontal axis.

*yCoord is the pixel along the vertical axis.


text:
Q: postgresql latitude longitude belgium I have a table with two columns (real type) for latitude and longitude respectively.
I would like to know if these points are located in Belgium, directly from a SQL query (postgreSQL).
I've already seen some things in python (Geopy) but the number of requests is limited (geopy.exc.GeocoderServiceError: HTTP Error 429: Too Many Requests
) ...
Any idea ?
Kind regards

A: You can do it directly in Postgres with the PostGIS extension. You would need to store the shape for Belgium in a table.
The function to call is ST_CONTAINS, which returns True or False if the first geometry contains the second one.
SELECT layer_pt.* FROM layer_belgium, layer_pt WHERE ST_Contains(layer_belgium.geom,  layer_pt.geom);

The first geometry would be the shape of Belgium and the second one would be your point. You may have to restrict the query to get only Belgium should you have other countries in it.
Since you don't have a point geometry but only its coordinate, you would also have to create the point geometry on the fly.
SELECT layer_pt.* FROM layer_belgium, layer_pt WHERE ST_Contains(layer_belgium.geom,  ST_GeomFromText('POINT(' || layer_pt.y || ' ' || layer_pt.x || ')', 4326));

Should you need more help with PostGIS, have a look at the GIS StackExchange


text:
Q: Sftp cannot see folder in destination server I'm using sftp to connect from a Windows server (User ID is ssh1) to AIX server (User ID is ftpeapsg) to access /sftp/ftphrssg/HRSSG/EAPSG in AIX server.
User ftpeapsg is created on AIX server.
Able to connect to AIX server fine without the need for password however not able to see the folder /sftp/ftphrssg/HRSSG/EAPSG
For /sftp/ftphrssg/HRSSG/EAPSG, owner is ftphrssg and group is geapsgtp
ftp user is ftpeapsg and group is geapsgtp
Both /sftp/ftphrssg/HRSSG/EAPSG and ftpeapsg belong to group geapsgtp.
Any idea why I'm not able to see /sftp/ftphrssg/HRSSG/EAPSG in the AIX server?