text:
Q: Baseline Profiles fail at profile generation with Shell.isSessionRooted I am trying to integrate the newly introduced baseline profiles into our app. I am using the following simple snippet to generate a baseline profile.
@RunWith(AndroidJUnit4::class)
class BaseProfileGenerator {

    @get:Rule
    val baselineProfile = BaselineProfileRule()

    @Test
    fun appStartup() {
        baselineProfile.collectBaselineProfile(packageName = InstrumentationRegistry.getInstrumentation().context.packageName) {
        pressHome()
        startActivityAndWait()
     }
   }
}

However, on running the test on a gradle managed device/emulator, I am getting the following exception:
java.lang.ExceptionInInitializerError
    at androidx.benchmark.Shell.isSessionRooted(Shell.kt:165)
    at androidx.benchmark.macro.BaselineProfilesKt$collectBaselineProfile$killProcessBlock$1.invoke(BaselineProfiles.kt:64)
    at androidx.benchmark.macro.BaselineProfilesKt$collectBaselineProfile$killProcessBlock$1.invoke(BaselineProfiles.kt:60)
    at androidx.benchmark.macro.BaselineProfilesKt.collectBaselineProfile(BaselineProfiles.kt:69)
    at androidx.benchmark.macro.junit4.BaselineProfileRule.collectBaselineProfile(BaselineProfileRule.kt:94)
    at androidx.benchmark.macro.junit4.BaselineProfileRule.collectBaselineProfile$default(BaselineProfileRule.kt:88)
    at com.package.name.baselineprofile.BaseProfileGenerator.appStartup(BaseProfileGenerator.kt:28)
    ... 36 trimmed
Caused by: java.io.IOException: Operation not permitted
    at java.io.UnixFileSystem.createFileExclusively0(Native Method)
    at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
    at java.io.File.createTempFile(File.java:2007)
    at androidx.benchmark.ShellImpl.createShellScript(Shell.kt:507)
    at androidx.benchmark.ShellImpl.<clinit>(Shell.kt:471)
    ... 44 more

According the the docs, it was stated that we need a userdebug/rooted device in order to generate the profile and I was under the impression gradle managed devices with aosp system image will satisfy that need.
For reference, here's the device in my build.gradle.kts:
managedDevices {
    devices {
        add(
            ManagedVirtualDevice("pixel2Api31").apply {
                device = "Pixel 2"
                apiLevel = 31
                systemImageSource = "aosp"
            }
        )
    }
}

Android Gradle Plugin = v7.3.1 macroBenchmarVersion = v1.2.0-alpha07 profileInstallerVersion = 1.3.0-alpha01
Any idea what might be happening here? I searched around but couldn't find anything relevant.
I tried updating the dependencies to the latest alpha versions since apparently according to the release notes, baseline profiles no longer need rooted devices but even then its failing with the same exception.


text:
Q: Find all occurrences of a string in a file Please keep in mind the file I am opening can be 10mb to 125mb.  I have researched various ways to open a file and am still not sure as to the best approach if any one is best. Please advise!
I am opening a large file and trying to extract the text between two strings each time the first occurs.  I can find the first string and extract the text to the second string, however, my loop gives me that result 12 times (number of times string occurs in this file.  I can see what I am doing wrong in the loop, basically finding the first occurrence and repeating its output 12 times.   How can I loop through the file and get the text between the 2-12th occurrences?
Also, any tips for proper opening of large files and handling memory limits would be great.
If this is put in an array, do I lose the whitespace? I am using PRE to display it correctly as it is.  Ultimately, I want to parse each string found into smaller elements either in an array or a db.  I don't want to get ahead of myself, so ignore the array comments if necessary.
<?php
ini_set('memory_limit', '-1');

/*
Functions
*/

function get_string_between($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

/*
Pre Loop
*/

$string1 = "String 1";
$string2 = "String 2";

$report = file_get_contents('report.rpt','r');

$cbcount = substr_count($report,$string1);

echo $cbcount;

/*
Loop
*/

for ($i=0; $i<$cbcount; $i++){

$output = get_string_between($report, $string1, $string2);

echo "
".$output."
";

}

?>

A: You're never actually advancing any pointer of any kind, so it has no way of knowing that it already found the first match.
Now, depending on your input, you may be able to just use a regex:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$report,$matches);

(Replace the entire loop with this)
Then you can var_dump($matches[0]) to see your output.

A: $startfrom = 0;
while (($start = strpos($string1, $report, $startfrom)) !== false) {
    $end = strpos($string2, $report, $start);
    echo "
".substr($report, $start, $end-$start)."
";
    $startfrom = $end + 1;
}

Regarding dealing with large files, instead of reading the entire thing into memory, you can use fopen() and fgets() to read it line by line. When you find a line containing the $string1 you start accumulating lines in in a variable, until you find the line containing $string2. This only works simply if the match strings cannot contain newlines.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with result of a find function in a bash script I have a problem with a script in bash. My for function is using the results of the find function.
Long story short: in SSH, find the function returns 2 results and in a bash script a single result.
I tried both of the following codes.
for f in $(find $path -name *.properties)
do
echo $f
done

OR
list=$(find $path -name *.properties)
for f in $list;
do
echo $f
done

In the specified path there are several folders and files, two of the files have the extension that i am looking for. If I run one of these commands in SSH I find both files, but if I run the command from a bash script the result contains a single file.
The for function is working fine, the problem is the find function. I run the following code in a script bash and i still have one result.
list=$(find $path -name *.properties)
echo $list

I run the following code in SSH and I found 2 files:
[root@was85 ~]# for f in $(find $path/temp/ -name *.properties); do echo $f
> done

Can anyone help me?
Thank you!

A: If using BASH better to use this while loop using process substitution and proper quoting and use -print0 option:
while IFS= read -rd '' f; do
   echo "$f"
done < <(find "$path" -name '*.properties' -print0)

A: If using bash 4 or later, use the globstar operator rather than a vanilla call to find to simply recurse through a file hierarchy.
shopt -s globstar
for f in "$path"/**/*.properties; do
    echo "$f"
done

(If the body really is just echo $f, then printf "%s\n" "$path"/**/*.properties will suffice instead of using the loop.)


text:
Q: Should I use history.js? I am working on dinamic web site it works fine with History API but I heard about some browsers issue about it.Which browsers support it?Then I decided to use history.js but it contains eval function and I know it is dangerous and slow.Shoul I use history.js or how?

A: Unless you need to worry about supporting IE8 or earlier, or Opera Mini (at all) you should be fine with just the History API. Please see http://caniuse.com/#feat=history for more information.
In general, if you want to know if it's OK to use any browser APIs you'll find the answer on http://caniuse.com.


text:
Q: C Dynamic Memory Allocation in Struct pointers I am unfamiliar with C language and I'm performing on a task related to the C-language structure pointer. I have to be input in the order of date((yyyyMMdd) time(hhmm) name(title) importance(1~10) content. It must be output in the order of date (yyyy.MM.dd.) time (hh:mm) importance content.
and here is my code. This code generates C4047, C4024 errors on the 27,28th line. and If I ignore the error message and debug it, an error of 'wntdll.pdb not loaded' is occur. what should i do?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Calender
{
    int day, time;
    int imt; //importance
    char tle[127]; //title
    char cnt[127]; //contents
};
void input_calender()
{
    char title[127];
    char contents[127];
    struct Calender* a = malloc(sizeof(struct Calender));
    scanf("%d", &(a->day));
    scanf("%d", &(a->time));
    scanf("%d", &(a->imt));
    scanf("%hhd", &title);
    scanf("%hhd", &contents);

    a->day = 8;
    a->time = 4;
    a->imt = 1;
    strcpy(a->tle, &title);
    strcpy(a->cnt, &contents);

    free(a);
}
void print_calender(struct Calender* a)
{
    int i;
    for (i = 0; i < 8; i++)
    {
        if (i == 4 || i == 6)
            printf(".");
        printf("%c", ((a->day) + i));
    }
    printf(" ");
    for (i = 0; i < 4; i++)
    {
        if (i == 2)
            printf(":");
        printf("%c", ((a->time) + i));
    }
    printf(" ");

    printf("%d ", a->imt);
    printf("%s ", a->tle);
    printf("%s\n ", a->cnt);
}
int main(void) {
    int num=0;
    int i;
    struct Calender* p = malloc(sizeof(struct Calender) * (num + 1));
    scanf("%d", &num);
    //입력
    for (i = 0; i < num; i++)
    {
        input_calender(p + i);
    }
    //출력
    for (i = 0; i < num; i++)
    {
        print_calender(p + i);
    }
    free(p);

} ```


text:
Q: Is intmax_t the same as long long int? By POSIX, intmax_t designates a signed integer type capable of representing any value of any signed integer type.
Would it be correct that in C99/C11 that intmax_t is always the same size as long long int?

A: C99 N1256 standard draft
6.2.5 Types tells us about "extended signed integer types":

4 There are five standard signed integer types, designated as signed char, short
  int, int, long int, and long long int. (These and other types may be
  designated in several additional ways, as described in 6.7.2.) There may also be
  implementation-defined extended signed integer types
  The standard and extended
  signed integer types are collectively called signed integer types. 29)
29) Therefore, any statement in this Standard about signed integer types also applies to the extended
  signed integer types.

7.18.1.5 Greatest-width integer types says that intmax_t is the largest possible "signed integer type", thus including extended ones:

1
  The following type designates a signed integer type capable of representing any value of
  any signed integer type:
intmax_t

6.4.4.1 Integer constants then makes it pretty clear that the extended integer types might be larger than any of the standard ones:

6 If an integer constant cannot be represented by any type in its list, it may have an
  extended integer type, if the extended integer type can represent its value.

A: If long and long long have the same width and representation, which they often do, long could be chosen for intmax_t.

A: No. intmax_t can be an extended integer type larger than long long. I'm not aware of any systems that have it defined as such, but you should not assume in application code that they're the same. (Assuming they're the same in OS code may be acceptable if your OS always guarantees that, but it's still probably a bad idea.)


text: Q: IIS Website With SQL Server Express Is their a setting in IIS that needs to be set-up?  I have my site writing details to a SQL Server Express table before the page is "finished" which works to perfection when I test locally or even if I run internally from within my network.  BUT if I access the page from any device outside of the computer it is hosted on, NOTHING will be written to the sql server table?


text:
Q: How to show that $X_n + Y_n \to X + Y$ holds in the $L^1$ norm? Let $X_n$ and $Y_n$ be sequences of random variables. Show that
$X_n + Y_n \to X + Y$ (1)
$X_nY_n \to XY$ (2)
If $\mathbb{P}(X=0) = 0, \;  \frac{Y_n}{X_n} \to \frac{Y}{X}$ (3)
are true for convergence in probability and and convergence almost everywhere, and (1) hold for convergence in $L^1$ aswell.
I have tried the approach with Boole's inequality, interchanging intersections and limits by the monotone convergence theorem, some other stuff, but can't quite seem to get there completely.
As for the $L^1$ convergence, it's my understanding that $X_n \in L^1$ if the sequence is absolutely convergent, and $\int |X_n-X| = 0$.
I remember $L^1$ convergence not being preserved by continuous transformations, and so are there examples where convergence in $L^1$ does not hold for (2) and (3)?

A: These are standard exercises. So, let me leave behind the ingredients that OP can utilise to formally construct the proofs.
Let $(\Omega, \mathfrak A, \mathbf P) $ be the probability measure space. Let $\langle X_n\rangle_{n\in N},~\langle Y_n\rangle_{n\in \mathbb N}$ be two sequences of extended real valued random variables on a set $D\in\mathfrak A$ converging almost surely on $D$ to the real-valued $X, ~Y$ respectively. That means there exists a null set $N_X: ~X:= \lim X_n(\omega) \in \mathbb R$ for every $\omega\in D\setminus N_X. $ Let $N_Y$ be defined in the same way.
The first two assertions (viz. convergence of sum, product) can be shown readily for all $\omega \in (N_X\cup N_Y) ^\complement.$
Now, let the sequence of extended real-valued random variables $\langle X_n\rangle_{n\in\mathbb N},~\langle Y_n\rangle_{n\in \mathbb N}$ converge in probability measure on $D$ to real-valued random variables $X, ~Y$ i.e. $X_n\overset{\mathbb P}{\rightarrow} X,~  Y_n\overset{\mathbb P}{\rightarrow} Y .$ Then by definition, $\forall \varepsilon >0,$ $$\lim_{n\to\infty}\mathbb P\{D:| (X_n + Y_n) - (X+Y)| \geq \varepsilon\}=0.\tag 1$$
Now, \begin{align}|(X_n + Y_n) -(X+Y) |&\leq |(X_n-X) |+|(Y_n-Y) |\\\implies\{D: |(X_n + Y_n) -(X+Y) |\geq \varepsilon\}&\subset \{D: |(X_n-X) |+|(Y_n-Y) |\geq \varepsilon\}\tag{2.i}\\\wedge~~ \{D: |(X_n-X) |+|(Y_n-Y) |\geq \varepsilon\}& \subset \{D:|(X_n-X) |\geq \varepsilon/2\}\cup \{D:|(Y_n-Y) |\geq \varepsilon/2\}.\tag{2.ii}\end{align}
From $(2) ,$
\begin{align}\mathbf P \{D: |(X_n-X) |+|(Y_n-Y) |\geq \varepsilon\}\leq \mathbf P\{D:|(X_n-X) |\geq \varepsilon/2\}+\mathbf P\{D:|(Y_n-Y) |\geq \varepsilon/2\};\tag 3\end{align}
Apply limits on both sides.
For the product, few results have to be consolidated.
Proposition $1.$ (Riesz) If a sequence of extended real-valued random variables $\langle X_n\rangle_{n\in \mathbb N}$ on $D\in\mathcal A$ converge in probability measure on $D$ to the real-valued $X,$ then there exists a subsequence $\langle X_{n_k}\rangle_{k\in \mathbb N}$ which converges almost surely to $X$ on $D.$
By assumption, for every $\varepsilon> 0, $ there exists $N_\varepsilon\in \mathbb N$ such that $\mathbf P\{D:|X_n -X|\geq \varepsilon\}<\varepsilon$ for $n>N_\varepsilon.$ Take $\varepsilon_k=1/2^k.$ Inductively it can be inferred $\mathbf P\left\{D:|X_{n_k} -X|\geq 1/2^k\right\}<1/2^k$ for $n_k>n_{k-1}.$ Whence $\sum_k \mathbf P\left\{D:|X_{n_k} -X|\geq 1/2^k\right\} <\infty.$ That completes the proof by application of Borel-Cantelli Lemma. $\square$
Observation $1.$ If every subsequence $\langle X_{n_k}\rangle_{k\in\mathbb N}$ of the sequence $\langle X_n\rangle_{n\in\mathbb N}$ has a subsequence $\langle X_{{n_k}_\ell}\rangle_{\ell \in \mathbb N}$ converging almost surely to $X$ on $D,$ then $X_n \overset{\text{a.s.}}{\rightarrow}X.$
Since almost sure convergence implies convergence in probability measure, then every $\langle X_{n_k}\rangle_{k\in\mathbb N}$ of $\langle X_n\rangle_{n\in\mathbb N}$ has a subsequence $\langle X_{{n_k}_\ell}\rangle_{\ell \in \mathbb N}$ which converges in probability measure to $X$ on $D.$ The implication follows. $\square$
To show $X_nY_n \overset{\mathbb P}{\to}XY, $ by Observation $1, $ it suffices to show every subsequence $\langle X_{n_k}Y_{n_k}\rangle_{k\in\mathbb N}$ of thr sequence $\langle X_nY_n\rangle_{n\in \mathbb N}$ has a subsequence $\langle X_{{n_k}_\ell} Y_{{n_k}_\ell}\rangle_{\ell \in \mathbb N}.$
By assumption, the subsequence $\langle X_{n_k}\rangle_{k\in \mathbb N}$ converges in probability measure on $D$ to $X.$ By Theorem $1, $ it is possible to find a subsequence $\langle X_{{n_k}_\ell}\rangle_{\ell \in \mathbb N}$ the converges almost surely on $D$ to $X.$ Similar treatment can be imposed on $\langle Y_n\rangle_{n\in\mathbb N}.$ From the property of almost sure convergence as the product $X_{{n_k}_\ell} Y_{{n_k}_\ell}\overset{\text{a.s.}}{\to}XY;$ since it is a subsequence from an arbitrary subsequence, the rest follows.
Re the ratio, let me rephrase it as $\frac{Y_n}{X_n}\mathbb I(X_n \not= 0).$ Then it is nothing but the application of Continuous Mapping Theorem (cf. this Maths.SE post) on $x\mapsto \frac{1}{x}\mathbb I_{\{x \neq 0\}}$ and what has already been established right above.
As for $\mathcal L^1$ norm, it is not even  clear if the sequences which converge to the real-valued $X, Y$ have their product $X_nY_n$ or $XY$ to be in $\mathcal L^1(\Omega). $ See this Maths.SE post for a counterexample.
For $\mathcal L^1$ convergence of sum of random variables, one can resort to the inequality (cf. $\rm [II]$)
$$ \mathbb E|(X_n -X) +(Y_n -Y) |^p\leq 2^p\left(\mathbb E|X_n- X|^p+\mathbb E|Y_n - Y|^p\right),~~p\in\mathbb R^{\geq 0}.\tag  4$$

Reference:
$\rm [I]$ Real Analysis: Theory of Measure and Integration, J.Yeh, World Scientific Publishing, $2014, $ chapter $1\S6, $ pp. $107-115,$ problems $6.9, ~6.13,~6.14.$
$\rm [II] $ Probability: A Graduate Course,  Allan Gut, Springer Science$+$Business, $2005, $ chapters $3, ~5,$  p. $127, ~247.$


text:
Q: ASP .NET Core 2.0 - JWT External Auth I am trying to get started with authentication on an ASP.NET Core 2.0 web app.
My company is using Ping Federate and I am trying to authenticate my users using the company login page and in return validating the returned token using my signing key (X509SecurityKey down here).
The login page link looks like:
https://companyname.com/authorization.oauth2?response_type=code&redirect_uri=https%3a%2f%2fJWTAuthExample%2fAccount%2fLogin&client_id=CompanyName.Web.JWTAuthExample&scope=&state=<...state...>
Out of the box, I configured the Startup.cs to be able to log in and challenge against this site.
I decorated my HomeController with a [Authorize(Policy="Mvc")] but when I access one of the pages, I just get a blank page.
Debug is not hitting the OnChallenge or OnAuthenticationFailed methods when I add it to options.Events (I think because user needs to be authenticated first).
So, what am I missing in order for a redirect to my authentication website to happen? Is it built in or do I have to do some manual configuration?
(Note: In other web apps, using asp net framework, I use a redirect in an Authorize attribute when authentication fails)
Related post: Authorize attribute does not redirect to Login page when using .NET Core 2's AddJwtBearer
- From this post, does it mean I am not using the right authentication method? I am building a web app, not an API.
namespace JWTAuthExample
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
        {
            Configuration = configuration;
            HostingEnvironment = hostingEnvironment;

            string certificatepath = Path.Combine(HostingEnvironment.ContentRootPath, $"App_Data\\key.cer");
            KEY = new X509SecurityKey(new X509Certificate2(certificatepath));
        }

        public IConfiguration Configuration { get; }
        public IHostingEnvironment HostingEnvironment { get; }
        private string AUTH_LOGINPATH { get; } = Configuration["DefaultAuth:AuthorizationEndpoint"];
        private X509SecurityKey KEY { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                {
                    options.IncludeErrorDetails = true;
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        // Ensure token expiry
                        RequireExpirationTime = true,
                        ValidateLifetime = true,
                        // Ensure token audience matches site audience value
                        ValidateAudience = false,
                        ValidAudience = AUTH_LOGINPATH,
                        // Ensure token was issued by a trusted authorization server
                        ValidateIssuer = true,
                        ValidIssuer = AUTH_LOGINPATH,
                        // Specify key used by token
                        RequireSignedTokens = true,
                        IssuerSigningKey = KEY
                    };
                });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Mvc", policy =>
                {
                    policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
                    policy.RequireAuthenticatedUser();
                });
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

A: Following Brad's suggestion,
Here is a sample of code to perform an OpenId Connect confirguration on ASP NET 2.0
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        options.Authority = Configuration["AuthoritySite"];
        options.ClientId = Configuration["ClientId"];
        options.ClientSecret = Configuration["ClientSecret"];
        options.Scope.Clear();
        // options.Scope.Add("Any:Scope");
        options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken;
        options.SaveTokens = true;

        options.GetClaimsFromUserInfoEndpoint = true;

        options.TokenValidationParameters = new TokenValidationParameters
        {
            // Compensate server drift
            ClockSkew = TimeSpan.FromHours(12),
            // Ensure key
            IssuerSigningKey = CERTIFICATE,

            // Ensure expiry
            RequireExpirationTime = true,
            ValidateLifetime = true,

            // Save token
            SaveSigninToken = true
        };

    });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Mvc", policy =>
        {
            policy.AuthenticationSchemes.Add(OpenIdConnectDefaults.AuthenticationScheme);
            policy.RequireAuthenticatedUser();
        });
    });
}

More details here: https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-2.1


text:
Q: Regex for Currency Amount with D for negative amounts or C for positive amounts I need help with RegEx.
Valid values:
-1.00 D
-2,000.00 D
-100,000.56 D
-100,000.00 D
-1,123,456.43 D

1.00 C
2,000.00 C
100,000.56 C
100,000.00 C
1,123,456.43 C

Before Decimal (Whole Numbers) can be upto 13 digits. Decimal should be always 2 digits.

-ve values will have SPACE and then D

and

+ve values will have SPACE and then C

Please help.

A: Use a look ahead to assert the overall format:
^(?=-.{,21}D|\d.{,20}C)-?\d{1,3}(,\d{3})*\.\d\d [CD]$

See live demo.

A: You can use the following regular expression to verify that strings match the pattern.
^(?=-.*D$|\d.*C$)-?(?=(?:\d,?){1,13}\.)(?:0|[1-9]\d{0,2}(?:,\d{3})*)\.\d{2} [DC]$

Demo
I tested this with the PCRE regex engine but it should work with any engine the supports lookaheads.
The regex contains two positive lookaheads. The first asserts that the string begins with a hyphen or digit; if a hyphen the last character must be D, if a digit the last character must be C. The second lookahead asserts that the string contains 1-13 digits before the decimal point.
The regex engine performs the following operations.
^                match beginning of line

(?=              begin positive lookahead
  -.*D$          match '-', 0+ chars, 'D' at end of line
  |              or
  \d.*C$         match 1 digit, 0+ chars, 'C' at end of line
)                end positive lookahead

-?               optionally match '-'

(?=              begin positive lookahead
  (?:\d,?)       match 1 digit optionally followed by ','
                 in a non-capture group
  {1,13}         execute preceding non-capture group 1-13 times
  \.             match '.'
)                end positive lookahead

(?:              begin non-capture group
  0              match '0' for amounts < '1.00'
  |              or
  [1-9]\d{0,2}   optionally match '-', then match one digit
                 other than '0', then 0-2 digits
  (?:,\d{3})     match ',' then 3 digits in non-capture group
  *              execute preceding non-capture group 0+ times
)                end non-capture group
\.\d{2} [DC]     match '.', 2 digits, 1 space 'D' or 'C'
$                match end of string

The end-of-line anchors in the first lookahead are actually not necessary (because of the end-of-line anchor at the end of the regex), but I've included them to improve readability.


text:
Q: How to generate dynamic push notification in cordova-vuejs hybrid app? I am using codova and vuejs for making hybrid app. I want to generate dynamic push notifications based on users data. How can we do that ?

A: If you are in search of a plugin that can help you with a push notification from the server, then OneSignal is one among the best.
Installation
cordova plugin add onesignal-cordova-plugin

Configuration
// Add to index.js or the first page that loads with your app.
// For Intel XDK and please add this to your app.js.

document.addEventListener('deviceready', function () {
  // Enable to debug issues.
  // window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});

  var notificationOpenedCallback = function(jsonData) {
    console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
  };

  window.plugins.OneSignal
    .startInit("YOUR_APPID")
    .handleNotificationOpened(notificationOpenedCallback)
    .endInit();
}, false);

Now, if you want something without the server, one that just works locally, the Cordova Local-Notification Plugin is the best option
Installation
cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications.git

Configuration
cordova.plugins.notification.local.schedule({
    title: 'My first notification',
    text: 'Thats pretty easy...',
    foreground: true
});


text:
Q: Install a new kernel: missing /lib/modules Hi I have a problem to install the new kernel 5.15 on my machine. To install the new kernel, I do this :

*

*make menuconfig (I tried the cp .config method too) + modified lines to have no problem while the building (CONFIG_MODULE_SIG_KEY="", CONFIG_SYSTEM_TRUSTED_KEYS="", CONFIG_SYSTEM_REVOCATION_KEYS=""). Without this last step, I have some troubles with x509 certificates

*make

*sudo make install

When I do the last step, I have this :
mcarrere@silverstone:~/Téléchargements/linux-5.15$ sudo make install VERBOSE=1
arch/x86/Makefile:142: CONFIG_X86_X32 enabled but no binutils support
sh ./arch/x86/boot/install.sh 5.15.0 \
    arch/x86/boot/bzImage System.map "/boot"
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 5.15.0 /boot/vmlinuz-5.15.0
run-parts: executing /etc/kernel/postinst.d/dkms 5.15.0 /boot/vmlinuz-5.15.0
 * dkms: running auto installation service for kernel 5.15.0                                                                                [ OK ]
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 5.15.0 /boot/vmlinuz-5.15.0
update-initramfs: Generating /boot/initrd.img-5.15.0
W: missing /lib/modules/5.15.0
W: Ensure all necessary drivers are built into the linux image!
depmod: ERROR: could not open directory /lib/modules/5.15.0: No such file or directory
depmod: FATAL: could not search modules: No such file or directory
cat: /var/tmp/mkinitramfs_LbpZGW/lib/modules/5.15.0/modules.builtin: Aucun fichier ou dossier de ce type
I: The initramfs will attempt to resume from /dev/nvme0n1p6
I: (UUID=281e04f6-0dcd-42cf-bde3-1b66a1c2f3b0)
I: Set the RESUME variable to override this.
depmod: WARNING: could not open modules.order at /var/tmp/mkinitramfs_LbpZGW/lib/modules/5.15.0: No such file or directory
depmod: WARNING: could not open modules.builtin at /var/tmp/mkinitramfs_LbpZGW/lib/modules/5.15.0: No such file or directory
run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 5.15.0 /boot/vmlinuz-5.15.0
run-parts: executing /etc/kernel/postinst.d/update-notifier 5.15.0 /boot/vmlinuz-5.15.0
run-parts: executing /etc/kernel/postinst.d/xx-update-initrd-links 5.15.0 /boot/vmlinuz-5.15.0
I: /boot/vmlinuz.old is now a symlink to vmlinuz-5.11.0-41-generic
run-parts: executing /etc/kernel/postinst.d/zz-update-grub 5.15.0 /boot/vmlinuz-5.15.0
Sourcing file `/etc/default/grub'
Sourcing file `/etc/default/grub.d/init-select.cfg'
Création du fichier de configuration GRUB…
Image Linux trouvée : /boot/vmlinuz-5.15.0
Image mémoire initiale trouvée : /boot/initrd.img-5.15.0
Image Linux trouvée : /boot/vmlinuz-5.11.0-41-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.11.0-41-generic
Image Linux trouvée : /boot/vmlinuz-5.10.52
Image mémoire initiale trouvée : /boot/initrd.img-5.10.52
Image Linux trouvée : /boot/vmlinuz-5.9.0-050900-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.9.0-050900-generic
Image Linux trouvée : /boot/vmlinuz-5.8.0-63-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.8.0-63-generic
Image Linux trouvée : /boot/vmlinuz-5.15.0
Image mémoire initiale trouvée : /boot/initrd.img-5.15.0
Image Linux trouvée : /boot/vmlinuz-5.11.0-41-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.11.0-41-generic
Image Linux trouvée : /boot/vmlinuz-5.10.52
Image mémoire initiale trouvée : /boot/initrd.img-5.10.52
Image Linux trouvée : /boot/vmlinuz-5.9.0-050900-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.9.0-050900-generic
Image Linux trouvée : /boot/vmlinuz-5.8.0-63-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.8.0-63-generic
Image Linux trouvée : /boot/vmlinuz-5.15.0
Image mémoire initiale trouvée : /boot/initrd.img-5.15.0
Image Linux trouvée : /boot/vmlinuz-5.11.0-41-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.11.0-41-generic
Image Linux trouvée : /boot/vmlinuz-5.10.52
Image mémoire initiale trouvée : /boot/initrd.img-5.10.52
Image Linux trouvée : /boot/vmlinuz-5.9.0-050900-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.9.0-050900-generic
Image Linux trouvée : /boot/vmlinuz-5.8.0-63-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.8.0-63-generic
Windows Boot Manager trouvé sur /dev/nvme0n1p1@/EFI/Microsoft/Boot/bootmgfw.efi
CentOS Linux 7 (Core) trouvé sur /dev/nvme0n1p7
Image Linux trouvée : /boot/vmlinuz-5.15.0
Image mémoire initiale trouvée : /boot/initrd.img-5.15.0
Image Linux trouvée : /boot/vmlinuz-5.11.0-41-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.11.0-41-generic
Image Linux trouvée : /boot/vmlinuz-5.10.52
Image mémoire initiale trouvée : /boot/initrd.img-5.10.52
Image Linux trouvée : /boot/vmlinuz-5.9.0-050900-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.9.0-050900-generic
Image Linux trouvée : /boot/vmlinuz-5.8.0-63-generic
Image mémoire initiale trouvée : /boot/initrd.img-5.8.0-63-generic
Windows Boot Manager trouvé sur /dev/nvme0n1p1@/EFI/Microsoft/Boot/bootmgfw.efi
CentOS Linux 7 (Core) trouvé sur /dev/nvme0n1p7
Adding boot menu entry for UEFI Firmware Settings
fait

I have no trouble while the "make".
What is the problem ? Is it usual to modify the .config for security keys ?
I need to install a kernel like this because I must modify the perf linux module and do some tests.
Thank you.
EDIT1 : So it's work now. I followed this topic and without changing my previous .config, it's work but I don't understand why it's work. An idea ? It's very curious...
ps : I did some tests on different kernels before, no need for the moment to remove them

A: So it's ok with this topic :
$ sudo make menuconfig
change some lines in the .config :
CONFIG_MODULE_SIG_KEY=""
CONFIG_SYSTEM_TRUSTED_KEYS=""
CONFIG_SYSTEM_BLACKLIST_HASH_LIST=""
CONFIG_SYSTEM_REVOCATION_KEYS=""
$ sudo make clean
$ sudo rm -rf debian
$ rm -f vmlinux-gdb.py
$ sudo make -j$(nproc) deb-pkg
$ cd ..
$ sudo dpkg -i linux-*.deb
$ awk -F\' '$1=="menuentry " || $1=="submenu " {print i++ " : " $2}; /\tmenuentry / {print "\t" i-1">"j++ " : " $2};' /boot/grub/grub.cfg
$ sudo update-grub

Maybe It's not very clean for the encryption part but it's work. If someone has a better idea...


text:
Q: Except DAX query (or other) I am building a report in Power BI, and I want to compare individuals who have an account vs. those who are actively using the account, but I can't figure out the DAX query I need, or at least am not getting the syntax right.
I have two tables - one that includes subscription data (user, applicationID, start date, end date) and one that includes usage data (user, applicationID, usage date)
I need the subset of users who have a specific applicationID but haven't used it (within a time frame set by a filter, and another filter for applicationID)
I think I need some combination of Except(evaluate(if(users with application)),(users with usage)) but I can't get the syntax right.  When I try to reference a table/column, the column name is grayed out, so the formula won't return any results.
This is a simplified model of the entire data set I'm working with, but I have one table with user subscription data and one with usage data:
Subscription data:
Subscriptiondata
Usage data:
Usagedata
The fields that joins them are:
Subscription "Sub_User_TIMSS_id" = Usage "app_user"
Subscription "mti_role_name" = Usage "app_name"
The usage table indicates each time that a specific user accesses a specific app
The end goal of this report is to identify individuals who have a subscription to an app but have not used it in a specified time period.
An example of a MySQL query that would satisfy this need is for one specific app is:
SELECT Subscription_App.Sub_User_TIMSS_id,
   Subscription_App.App_id,
   Subscription_App.Sub_Start_Date,
   Subscription_App.Sub_End_Date,
   Subscription_App.mti_role_name
FROM MTI.Subscription_App Subscription_App
WHERE (Subscription_App.mti_role_name = 'ForeignTrade')
AND     (Subscription_App.Sub_User_TIMSS_id NOT IN
            (
            SELECT app_usage.app_user
            FROM `usage`.app_usage app_usage
            WHERE (app_usage.app_name = 'ForeignTrade')
            ))

However, I can't simply use a query as my data source in Power BI because I want the user of the report to be able to specify an app and a time frame - the filter would indicate the parameters of the query as opposed to the query itself specifying the app name (in the example above, the query would represent if the user selected the app name Foreign Trade and all time in the filters).  Someone may have used the app within the last year but not within the last month - or they may have used one app but not another, so the end result needs to factor this in.
I'm not experienced enough in DAX to figure out how to accomplish this yet.


text:
Q: Initializing the array so that one can find the number of assigned values into the array What is the best way to keep track of the number of assigned elements in predefined C++ arrays?
For example, in the following code, one can easily run a loop till it encounters the first 0 in the array:
#include <iostream>
using namespace std;

#define MAX 500

int main() {
  int a[MAX] = {};
  a[0] = 1;
  a[1] = 2;
  a[2] = 3;
  // loop
}

However, if we consider the following definition:
#include <iostream>
using namespace std;

#define MAX 500

int main() {
  int a[MAX] = {};
  a[0] = 1;
  a[1] = 0;
  a[2] = 3;
  // loop
}

Seeking for the first 0 does not work since there is still a value of 3 after the first 0.
My question: How should I initialize the array so that I would have a "stable" rule of counting the number of assigned values?

A: The best way would be to use a structure built specifically to support your use case. The very good one I know of is boost.static_vector.
You can push/pop elements to/from it, you can explicitly set and query it's size, and all the while the storage is allocated statically.


text:
Q: Git: file on remote server is not being overwritten with updated version on merge I must have accidentally pushed up a file where I did not remove the merge error markers (<<<<HEAD) and it broke my site.
I checked out the problem file, found the merge conflict and fixed the code. I then went to commit the file but get the message nothing to commit (working directory clean).
Regardless, I pushed the changes up to GitHub. In GitHub I can view the file and see that the code is correct. Great!
I then went to merge the fixed code into my remote site. But nothing happens. The merge performs fine, no errors, but the site still remained broken.
Curious, I checked out the same file. The bad code is still there, on the remote repo.
Would anyone know what's happening and how I could fix it? Here's the steps I took:

*

*git checkout develop file.etc

*fix code

*git status to confirm file is modified

*git add ., git commit and git push to Github

*Check on GitHub to see that file is modifed

*git merge branch-name

*Test to see if site is working

A: OK, I think I understand what may have been going on here.
The remote repo is it's self a branch. I merged the bad file into that remote branch, but was 'checking it out' and trying to fix it on my original branch.
Since the file was fixed on my original branch, as visible up on GitHub, staging it wouldn't work - git didn't see any difference between the file I just fixed and the one already part of the branch, that's why it 'disappeared' when I added it and said there was nothing to commit.
As for why I couldn't merge in my branch in with the remote branch a 2nd time, I'm not sure.


text:
Q: Akka stream test with testkit and scalatest I am getting NullPointerException when testing my akka stream app with scalatest and don't understand why... I probably missed something in Akka Streams I am just diving into it.
I use the common structure of code for scalatest with scala 2.12.4 and sbt 1.0.3
This is my app
object CdrToMongoReactiveStream extends App {

  implicit val system = ActorSystem("cdr-data-generator")
  implicit val materializer = ActorMaterializer()
  implicit val executionContext=materializer.executionContext
  import RandomCdrJsonProtocol._

  val randomCdrThrottledSource : Source[RandomCdr,NotUsed]= Source
    .fromIterator(() => Iterator.continually(RandomCdr(msisdnLength,timeRange)))
    .throttle(throughput,1.second,1,ThrottleMode.shaping)
    .named("randomCdrThrottledSource")

  val cdrJsonParseFlow : Flow[RandomCdr,String,NotUsed]= Flow[RandomCdr]
    .map((cdr: RandomCdr) => cdr.toJson.toString())
    .named("cdrJsonParseFlow")

  val mongodbBulkSink : Sink[String,NotUsed] = Flow[String]
    .map((json: String) => Document.parse(json))
    .map((doc: Document) => new InsertOneModel[Document](doc))
    .grouped(bulkSize)
    .flatMapConcat { (docs: Seq[InsertOneModel[Document]]) ⇒
      Source.fromPublisher(collection.bulkWrite(docs.toList.asJava))
    }
    .to(Sink.ignore)

  val f = randomCdrThrottledSource.via(cdrJsonParseFlow).runWith(mongodbBulkSink)
}

And my test file
class CdrToMongoReactiveStreamSpec extends WordSpec with Matchers {

  import RandomCdrJsonProtocol._

  "randomCdrThrottledSource" should {
    "generate RandomCdr elements only" in {
      val future = CdrToMongoReactiveStream.randomCdrThrottledSource
        // line 30 in the error
        .runWith(Sink.head)(CdrToMongoReactiveStream.materializer)

      val cdr = Await.result(future,10.second)
      cdr shouldBe a [RandomCdr]
    }
  }
  "cdrJsonParseFlow" should {
    "parse RandomCdr to correct json format" in {
      val randomCdr = RandomCdr("+33612345678",1511448336402L,"+33612345678","SMS","OUT",0,0,0)
      val (pub,sub) = TestSource.probe[RandomCdr]
        .via(CdrToMongoReactiveStream.cdrJsonParseFlow)
        .toMat(TestSink.probe[String])(Keep.both)
        .run()

      sub.request(1)
      pub.sendNext(randomCdr)
      sub.expectNext() shouldBe equal(randomCdr.toJson.toString())
    }
  }
}

And the error message
java.lang.NullPointerException was thrown.
java.lang.NullPointerException
    at CdrToMongoReactiveStreamSpec.$anonfun$new$2(CdrToMongoReactiveStreamSpec.scala:30)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
    at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
    at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
    at org.scalatest.Transformer.apply(Transformer.scala:22)
    at org.scalatest.Transformer.apply(Transformer.scala:20)
    at org.scalatest.WordSpecLike$$anon$1.apply(WordSpecLike.scala:1078)
    at org.scalatest.TestSuite.withFixture(TestSuite.scala:196)
    at org.scalatest.TestSuite.withFixture$(TestSuite.scala:195)
    at org.scalatest.WordSpec.withFixture(WordSpec.scala:1881)
    at org.scalatest.WordSpecLike.invokeWithFixture$1(WordSpecLike.scala:1076)
    at org.scalatest.WordSpecLike.$anonfun$runTest$1(WordSpecLike.scala:1088)
    at org.scalatest.SuperEngine.runTestImpl(Engine.scala:289)
    at org.scalatest.WordSpecLike.runTest(WordSpecLike.scala:1088)
    at org.scalatest.WordSpecLike.runTest$(WordSpecLike.scala:1070)
    at org.scalatest.WordSpec.runTest(WordSpec.scala:1881)
    at org.scalatest.WordSpecLike.$anonfun$runTests$1(WordSpecLike.scala:1147)
    at org.scalatest.SuperEngine.$anonfun$runTestsInBranch$1(Engine.scala:396)
    at scala.collection.immutable.List.foreach(List.scala:389)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:384)
    at org.scalatest.SuperEngine.runTestsInBranch(Engine.scala:373)
    at org.scalatest.SuperEngine.$anonfun$runTestsInBranch$1(Engine.scala:410)
    at scala.collection.immutable.List.foreach(List.scala:389)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:384)
    at org.scalatest.SuperEngine.runTestsInBranch(Engine.scala:379)
    at org.scalatest.SuperEngine.runTestsImpl(Engine.scala:461)
    at org.scalatest.WordSpecLike.runTests(WordSpecLike.scala:1147)
    at org.scalatest.WordSpecLike.runTests$(WordSpecLike.scala:1146)
    at org.scalatest.WordSpec.runTests(WordSpec.scala:1881)
    at org.scalatest.Suite.run(Suite.scala:1147)
    at org.scalatest.Suite.run$(Suite.scala:1129)
    at org.scalatest.WordSpec.org$scalatest$WordSpecLike$$super$run(WordSpec.scala:1881)
    at org.scalatest.WordSpecLike.$anonfun$run$1(WordSpecLike.scala:1192)
    at org.scalatest.SuperEngine.runImpl(Engine.scala:521)
    at org.scalatest.WordSpecLike.run(WordSpecLike.scala:1192)
    at org.scalatest.WordSpecLike.run$(WordSpecLike.scala:1190)
    at org.scalatest.WordSpec.run(WordSpec.scala:1881)
    at org.scalatest.tools.SuiteRunner.run(SuiteRunner.scala:45)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13(Runner.scala:1340)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13$adapted(Runner.scala:1334)
    at scala.collection.immutable.List.foreach(List.scala:389)
    at org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:1334)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24(Runner.scala:1031)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24$adapted(Runner.scala:1010)
    at org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:1500)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:1010)
    at org.scalatest.tools.Runner$.run(Runner.scala:850)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2(ScalaTestRunner.java:138)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:28)

A: I solved the problem declaring Source, Flow and Sink outside of the main program
object CdrToMongoReactiveStream {

  def randomCdrThrottledSource(msisdnLength : Int,timeRange : Int, throughput : Int): Source[RandomCdr,NotUsed]= {
    Source
      .fromIterator(() => Iterator.continually(RandomCdr(msisdnLength,timeRange)))
      .throttle(throughput,1.second,1,ThrottleMode.shaping)
      .named("randomCdrThrottledSource")
  }

  def cdrJsonParseFlow : Flow[RandomCdr,String,NotUsed]= {
    import RandomCdrJsonProtocol._

    Flow[RandomCdr]
      .map((cdr: RandomCdr) => cdr.toJson.toString())
      .named("cdrJsonParseFlow")
  }

  def mongodbBulkSink(collection : MongoCollection[Document], bulkSize : Int) : Sink[String,NotUsed] = {

    Flow[String]
      .map((json: String) => Document.parse(json))
      .map((doc: Document) => new InsertOneModel[Document](doc))
      .grouped(bulkSize)
      .flatMapConcat { (docs: Seq[InsertOneModel[Document]]) ⇒
        Source.fromPublisher(collection.bulkWrite(docs.toList.asJava))
      }
      .to(Sink.ignore)
  }

  def main(args: Array[String]): Unit = {
    val f = randomCdrThrottledSource(msisdnLength,timeRange,throughput)
      .via(cdrJsonParseFlow).runWith(mongodbBulkSink(collection,bulkSize))

    logger.info("Generated random data")
  }
}

and the test file
class CdrToMongoReactiveStreamSpec extends WordSpec with Matchers {

  import CdrToMongoReactiveStream._
  import RandomCdrJsonProtocol._

  implicit val system = ActorSystem("cdr-data-generator")
  implicit val materializer = ActorMaterializer()

  val collection = new Fongo("mongo test server").getDB("cdrDB").getCollection("cdr")
  val randomCdr = RandomCdr("+33612345678",1511448336402L,"+33612345678","SMS","OUT",0,0,0)

  "randomCdrThrottledSource" should {
    "generate RandomCdr elements only" in {
      val future = CdrToMongoReactiveStream.randomCdrThrottledSource(8,86400000,1)
        .runWith(Sink.head)

      val cdr = Await.result(future,5.second)
      cdr shouldBe a [RandomCdr]
    }
  }
}


text:
Q: Solr stop words replaced with _ symbol I have problems with solr stopwords in my autosuggest. All stopwords was replaced by _ symbol.
For example I have text "the simple text in" in field "deal_title". When I try to search word "simple" solr show me next result "_ simple text _" but I expect "simple text".
Could someone explain me why this works in such way and how to fix it ?
Here is part of my schema.xml
<fieldType class="solr.TextField" name="text_auto">
    <analyzer type="index">
        <charFilter class="solr.HTMLStripCharFilterFactory"/>
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
        <filter class="solr.ShingleFilterFactory" maxShingleSize="3" outputUnigrams="true" outputUnigramsIfNoShingles="false" />
    </analyzer>
    <analyzer type="query">
        <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
    </analyzer>
</fieldType>

<field name="deal_title" type="text_auto" indexed="true" stored="true" required="false" multiValued="false"/>

<fieldType name="text_general" class="solr.TextField">
  <analyzer type="index">
    <tokenizer class="solr.KeywordTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="false"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.KeywordTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="false"/>
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

A: My solution to this in Solr 6.3 (where enablePositionIncrements="false" isn't possible anymore) was to:

*

*remove stopwords

*shingle with fillerToken="" (which removes the _)

*remove leading and trailing spaced

*remove duplicates
<filter class="solr.StopFilterFactory" format="snowball" words="lang/stopwords_de.txt" ignoreCase="true"/>
<filter class="solr.ShingleFilterFactory" fillerToken=""/>
<filter class="solr.PatternReplaceFilterFactory" pattern="(^ | $)" replacement=""/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>

A: To fix this you need to use<filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true" enablePositionIncrements="false" />and <luceneMatchVersion>4.3</luceneMatchVersion> in solconfig.xml


text:
Q: Invalid MEX-file due to undefined symbol I am trying to build MEX modules, but I am having runtime issues with undefined symbols. Here is the output
Invalid MEX-file '/home/glperez/issm/trunk-jpl/lib/TriMesh.mexa64':
/home/glperez/issm/trunk-jpl/lib/libISSMCore.so: undefined symbol: _ZN14ToolkitOptions14toolkitoptionsE

Error in triangle (line 40)
[elements,x,y,segments,segmentmarkers]=TriMesh(domainname,riftname,area);

Error in test101 (line 1)
md=triangle(model(),'../Exp/Square.exp',50000.);

Checking the symbols in 'libISSMCore.so' confirms the undefined symbol
$ nm ./lib/libISSMCore.so | grep 'toolkit'
U _ZN14ToolkitOptions14toolkitoptionsE

However, the symbol appears in 'TriMesh.mexa64':
$ nm ./lib/TriMesh.mexa64 | grep 'toolkit'
00000000002391b8 b _ZN14ToolkitOptions14toolkitoptionsE

As I understand it, the lowercase 'b' means that the symbol is in the uninitialized section and that it is local versus global.
Is the problem here have to do with the symbol being local, uninitialized or something else?

A:
As I understand it, the lowercase 'b' means that the symbol is in the uninitialized section and that it is local

The symbol is local, and is in zero-initialized (aka BSS) section.
Yes, the problem is that it is local, i.e. no accessible outside of the TriMesh.mexa64 library.


text:
Q: Can I have a layer in my map that gets its imagery from say google? (ArcGIS Mobile 10) I've been messing with ArcGIS Mobile and I get that it loads and caches layers from an ArcGIS Server for disconnected use. I'm wondering if it supports layers where data is loaded from a layer in realtime? I can't find any examples where I create a layer, give it a URL and have it load imagery data as I pan the map.

A: According to the documentation, the answer is yes you can use Google or Bing basemaps in ArcGIS for Windows Mobile.  You can also use ArcGIS Online free of charge if you don't have your own ArcGIS Map Server.


text:
Q: Rotate through numerous galleries with one set of thumbnails I am creating a product page in a checkout. The page has swatches that when clicked need to update the main image and corresponding thumbnails with a new set of images with the new color.  You can view page here: http://www.briansugden.com/ai/tron.html un/pw is ai/ai.
Here's the code I have:

And the javascript for the main thumbs (change views of main image) as well as the swatches (change whole gallery to a new color):
 $(function(evt) {
    $("a:has(img.thumb)").click(function() {
        var largePath = $(this).attr("href");

        $("#photoLarge").attr({ src: largePath });
        return false;

    });

    $("#productThumbs > a > img").click(function(e){
      e.preventDefault();
        $("#productThumbs > a > img").addClass("active").not(this).removeClass("active");
      });

});

$(document).ready(function () {

            $("#tronGallery_2").hide();
            $("#tronGallery_3").hide();
            $("#tronGallery_4").hide();

            var clickHandler = function (link) {
                 $(".tab").hide();
                 $("#tronGallery_" + link.data.id).show();
                 $(".active").removeClass("active");
                 $(this).attr("class","active");
           }

           $(".swatch1").bind("click", {id:"1"} ,clickHandler);
           $(".swatch2").bind("click", {id:"2"} ,clickHandler);
           $(".swatch3").bind("click", {id:"3"} ,clickHandler);
           $(".swatch4").bind("click", {id:"4"} ,clickHandler);

        })
        </script>

So the divs arent switching out correctly and the thumbs dont work once you chagne the swatch.  I think I know what the problem is but I dont know how to fix it.  I assume that once I switch out the divs by clicking a swatch its still targeting the div that was hidden instead of the one that's visible. How do I fix that.
Any help would be much appreciated!

A: First: those are some expensive shoes!
Second: you have lots of duplicate ID values. For example: photoLarge, productThumbs, thumb01, thumb02, thumb03, thumb04. Make those each unique and you will probably get better results.
Third: after the line $(this).attr("class","active"); you want to have another line to make the first thumbnail active because you removed its active class already. Your HTML marks the first thumbnail active, but that gets removed before it is shown.


text:
Q: creating a MIME email template with images to send with python / django In my web application I send emails occasionally using a reusable mailer application like this:
user - self.user
subject = ("My subject")
from = "me@mydomain.com"
message = render_to_string("welcomeEmail/welcome.eml", {
                "user" : user,
                })
send_mail(subject, message, from, [email], priority="high" )

I want to send an email with embedded images in it, so I tried making the mail in a mail client, viewing the source, and putting it into my template (welcome.eml), but I've been unable to get it to render correctly in mail clients when its sent.
Does anyone know of an easy way for me to create mime encoded mail templates with inline images that will render correctly when I send them?

A: Update
Many thanks to Saqib Ali for resurrecting this old question nearly 5 years after my reply.
The instructions I gave at the time no longer work. I suspect there have been some improvements to Django in the intervening years which mean that send_mail() enforces plain text. No matter what you put in the content, it will always be delivered as plain text.
The most recent Django documentation explains that send_mail() is really just a convenience for creating an instance of the django.core.mail.EmailMessage class, and then calling send() on that instance. EmailMessage has this note for the body parameter, which explains the results we're seeing now in 2014:

body: The body text. This should be a plain text message.
... somewhat later in the docs ...
By default, the MIME type of the body parameter in an EmailMessage is "text/plain". It is good practice to leave this alone.

Fair enough (I confess I haven't taken the time to investigate why the 2009 instructions worked - I did test them back in 2009 - or when it changed). Django does provide, and document, a django.core.mail.EmailMultiAlternatives class to make it easier for sending a plain text and HTML representation of the same message.
The case in this question is slightly different. We're not seeking to append an alternative per se, but to append related parts to one of the alternatives. Within the HTML version (and it doesn't matter if you have or omit the plain text version), we want to embed an image data part. Not an alternative view of the content, but related content that is referenced in the HTML body.
Sending an embedded image is still possible, but I don't see a straightforward way to do it using send_mail. It's time to dispense with the convenience function and to instantiate an EmailMessage directly.
Here's an update to the previous example:
from django.core.mail import EmailMessage
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Load the image you want to send as bytes
img_data = open('logo.jpg', 'rb').read()

# Create a "related" message container that will hold the HTML
# message and the image. These are "related" (not "alternative")
# because they are different, unique parts of the HTML message,
# not alternative (html vs. plain text) views of the same content.
html_part = MIMEMultipart(_subtype='related')

# Create the body with HTML. Note that the image, since it is inline, is
# referenced with the URL cid:myimage... you should take care to make
# "myimage" unique
body = MIMEText('
Hello
', _subtype='html')
html_part.attach(body)

# Now create the MIME container for the image
img = MIMEImage(img_data, 'jpeg')
img.add_header('Content-Id', '<myimage>')  # angle brackets are important
img.add_header("Content-Disposition", "inline", filename="myimage") # David Hess recommended this edit
html_part.attach(img)

# Configure and send an EmailMessage
# Note we are passing None for the body (the 2nd parameter). You could pass plain text
# to create an alternative part for this message
msg = EmailMessage('Subject Line', None, 'foo@bar.com', ['bar@foo.com'])
msg.attach(html_part) # Attach the raw MIMEBase descendant. This is a public method on EmailMessage
msg.send()

Original reply from 2009:
To send an e-mail with embedded images, use python's built-in email module to build up the MIME parts.
The following should do it:
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Load the image you want to send at bytes
img_data = open('logo.jpg', 'rb').read()

# Create a "related" message container that will hold the HTML
# message and the image
msg = MIMEMultipart(_subtype='related')

# Create the body with HTML. Note that the image, since it is inline, is
# referenced with the URL cid:myimage... you should take care to make
# "myimage" unique
body = MIMEText('
Hello
', _subtype='html')
msg.attach(body)

# Now create the MIME container for the image
img = MIMEImage(img_data, 'jpeg')
img.add_header('Content-Id', '<myimage>')  # angle brackets are important
msg.attach(img)

send_mail(subject, msg.as_string(), from, [to], priority="high")

In reality, you'll probably want to send the HTML along with a plain-text alternative. In that case, use MIMEMultipart to create the "related" mimetype container as the root. Then create another MIMEMultipart with the subtype "alternative", and attach both a MIMEText (subtype html) and a MIMEText (subtype plain) to the alternative part. Then attach the image to the related root.

A: I was having trouble with Jarret's recipe on Django 1.10 - was getting MIME and encoding errors for the various ways you can attach MIME data.
Here's a simple multipart transactional template for an email with an embedded coupon_image file object that works on django 1.10:
from django.core.mail import EmailMultiAlternatives
from email.mime.image import MIMEImage

def send_mail(coupon_image):
    params = {'foo':'bar'} # create a template context
    text_body = render_to_string('coupon_email.txt', params)
    html_body = render_to_string('coupon_email.html', params)
    img_data = coupon_image.read() #should be a file object, or ImageField
    img = MIMEImage(img_data)
    img.add_header('Content-ID', '<coupon_image>')
    img.add_header('Content-Disposition', 'inline', filename="coupon_image")

    email = EmailMultiAlternatives(
        subject="Here's your coupon!",
        body=text_body,
        from_email='noreply@example.com',
        to=['someone@example.com',]
    )

    email.attach_alternative(html_body, "text/html")
    email.mixed_subtype = 'related'
    email.attach(img)

    email.send(fail_silently=False)

A: Version using a text alternative
Jarret Hardie's answer says "You could pass plain text to create an alternative part for this message". However, I have found that doing so would lead gmail (though not outlook) to display both parts of the email, one after the other, as described here
As recommended there and elsewhere, I simply used EmailMultiAlternatives. The resulting code looks somewhat like this:
from django.core.mail import EmailMultiAlternatives
from email.mime.image import MIMEImage

# Load the image you want to send as bytes
img_data = open('logo.jpg', 'rb').read()

# Create the body with HTML. Note that the image, since it is inline, is
# referenced with the URL cid:myimage... you should take care to make
# "myimage" unique
html_content = '
Hello
'
text_content = 'Hello'

# Configure an EmailMultiAlternatives
msg = EmailMultiAlternatives('Subject Line', text_content, 'foo@bar.com', ['bar@foo.com'])
msg.attach_alternative(html_content)

# Now create the MIME container for the image
img = MIMEImage(img_data, 'jpeg')
img.add_header('Content-Id', '<myimage>')  # angle brackets are important
img.add_header("Content-Disposition", "inline", filename="myimage") # David Hess recommended this edit
msg.attach(img)

# Finally, send the whole thing.
msg.send()


text:
Q: Nginx internally call another request and return that request data I am using nginx and lua to parse my rest api (https://openresty-reference.readthedocs.io/en/latest/Lua_Nginx_API/) . I am trying to internally call another api inside my rest call which is a different server and return that response. But it is getting empty response always. Below is my config, I am requesting for /student any help is highly appreciable
location /student {
    content_by_lua '
    local str = "test"
    local res = ngx.location.capture("/detail",{method = ngx.HTTP_POST, body = str})
    ngx.say(str)
    ';
}
location /detail {
    set $target '104.28.17.1/post';
    set $pass 'Basic Y2l28=';
    lua_need_request_body on;
    content_by_lua '
    proxy_set_header          Host            $host;
    proxy_set_header          X-Real-IP       $remote_addr;
    proxy_set_header          X-Forwarded-For $proxy_add_x_forwarded_for;
    #access_by_lua '
    proxy_set_header Authorization $pass;
    proxy_set_header Content-Type 'application/x-www-form-urlencoded';
    proxy_set_header Accept '*/*';
    proxy_set_header Connection 'keep-alive';
    proxy_pass http://$target;
}

A: Try changing your location /student to
location /student {
    content_by_lua '
    local str = "test"
    local res = ngx.location.capture("/detail",{method = ngx.HTTP_POST, body = str})
    ngx.status = 200
    ngx.say(str)
    ngx.exit(ngx.HTTP_OK)
    ';
}


text:
Q: Constant Training Loss and Validation Loss I am running a RNN model with Pytorch library to do sentiment analysis on movie review, but somehow the training loss and validation loss remained constant throughout the training. I have looked up different online sources but still stuck.
Can someone please help and take a look at my code?
Some parameters are specified by the assignment:
embedding_dim = 64

n_layers = 1

n_hidden = 128

dropout = 0.5

batch_size = 32

My main code
txt_field = data.Field(tokenize=word_tokenize, lower=True, include_lengths=True, batch_first=True)
label_field = data.Field(sequential=False, use_vocab=False, batch_first=True)

train = data.TabularDataset(path=part2_filepath+"train_Copy.csv", format='csv',
                            fields=[('label', label_field), ('text', txt_field)], skip_header=True)
validation = data.TabularDataset(path=part2_filepath+"validation_Copy.csv", format='csv',
                            fields=[('label', label_field), ('text', txt_field)], skip_header=True)

txt_field.build_vocab(train, min_freq=5)
label_field.build_vocab(train, min_freq=2)

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
train_iter, valid_iter, test_iter = data.BucketIterator.splits(
    (train, validation, test),
    batch_size=32,
    sort_key=lambda x: len(x.text),
    sort_within_batch=True,
    device=device)

n_vocab = len(txt_field.vocab)
embedding_dim = 64
n_hidden = 128
n_layers = 1
dropout = 0.5

model = Text_RNN(n_vocab, embedding_dim, n_hidden, n_layers, dropout)

optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)
criterion = torch.nn.BCELoss().to(device)

N_EPOCHS = 15
best_valid_loss = float('inf')

for epoch in range(N_EPOCHS):
    train_loss, train_acc = RNN_train(model, train_iter, optimizer, criterion)
    valid_loss, valid_acc = evaluate(model, valid_iter, criterion)

My Model
class Text_RNN(nn.Module):
    def __init__(self, n_vocab, embedding_dim, n_hidden, n_layers, dropout):
        super(Text_RNN, self).__init__()
        self.n_layers = n_layers
        self.n_hidden = n_hidden
        self.emb = nn.Embedding(n_vocab, embedding_dim)
        self.rnn = nn.RNN(
            input_size=embedding_dim,
            hidden_size=n_hidden,
            num_layers=n_layers,
            dropout=dropout,
            batch_first=True
        )
        self.sigmoid = nn.Sigmoid()
        self.linear = nn.Linear(n_hidden, 2)

    def forward(self, sent, sent_len):
        sent_emb = self.emb(sent)
        outputs, hidden = self.rnn(sent_emb)
        prob = self.sigmoid(self.linear(hidden.squeeze(0)))

        return prob

The training function
def RNN_train(model, iterator, optimizer, criterion):
    epoch_loss = 0
    epoch_acc = 0
    model.train()
    for batch in iterator:
        text, text_lengths = batch.text
        predictions = model(text, text_lengths)
        batch.label = batch.label.type(torch.FloatTensor).squeeze()
        predictions = torch.max(predictions.data, 1).indices.type(torch.FloatTensor)
        loss = criterion(predictions, batch.label)
        loss.requires_grad = True
        acc = binary_accuracy(predictions, batch.label)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        epoch_loss += loss.item()
        epoch_acc += acc.item()

    return epoch_loss / len(iterator), epoch_acc / len(iterator)

The output I run on 10 testing reviews + 5 validation reviews
Epoch [1/15]:   Train Loss: 15.351 | Train Acc: 44.44%  Val. Loss: 11.052 |  Val. Acc: 60.00%
Epoch [2/15]:   Train Loss: 15.351 | Train Acc: 44.44%  Val. Loss: 11.052 |  Val. Acc: 60.00%
Epoch [3/15]:   Train Loss: 15.351 | Train Acc: 44.44%  Val. Loss: 11.052 |  Val. Acc: 60.00%
Epoch [4/15]:   Train Loss: 15.351 | Train Acc: 44.44%  Val. Loss: 11.052 |  Val. Acc: 60.00%
...

Appreciate if someone can point me to the right direction, I believe is something with the training code, since for most parts I follow this article:
https://www.analyticsvidhya.com/blog/2020/01/first-text-classification-in-pytorch/

A: In your training loop you are using the indices from the max operation, which is not differentiable, so you cannot track gradients through it. Because it is not differentiable, everything afterwards does not track the gradients either. Calling
loss.backward() would fail.
# The indices of the max operation are not differentiable
predictions = torch.max(predictions.data, 1).indices.type(torch.FloatTensor)
loss = criterion(predictions, batch.label)
# Setting requires_grad to True to make .backward() work, although incorrectly.
loss.requires_grad = True

Presumably you wanted to fix that by setting requires_grad, but that does not do what you expect, because no gradients are propagated to your model, since the only thing in your computational graph would be the loss itself, and there is nowhere to go from there.
You used the indices to get either 0 or 1, since the output of your model is essentially two classes, and you wanted the one with the higher probability. For the Binary Cross Entropy loss, you only need one class that has a value between 0 and 1 (continuous), which you get by applying the sigmoid function.
So you need change the output channels of the final linear layer to 1:
self.linear = nn.Linear(n_hidden, 1)

and in your training loop you can remove the torch.max call and also the requires_grad.
# Squeeze the model's output to get rid of the single class dimension
predictions = model(text, text_lengths).squeeze()
batch.label = batch.label.type(torch.FloatTensor).squeeze()
loss = criterion(predictions, batch.label)
acc = binary_accuracy(predictions, batch.label)
optimizer.zero_grad()
loss.backward()

Since you have only 1 class at the end, an actual prediction would be either 0 or 1 (nothing in between), to achieve that you can simply use 0.5 as the threshold, so everything below is considered a 0 and everything above is considered a 1. If you are using the binary_accuracy function of the article you were following, that is done automatically for you. They do that by rounding it with torch.round.


text:
Q: Multiple UIViews, passing methods I have two UIView contained in a UIViewController - firstView and secondView - that I initialize pragmatically. I have a UILabel in the firstView, and a UIButton in the secondView. I would like the button in the second view to change the label in the first view. In the implementation file of the second view I have the following code:
- (void) changeLabel: (UIButton *) sender{
    firstView *view = [[firstView alloc] init];
    view.label.text = @"Changed Text";
}

However I figured out that the above method just initializes a new class of firstView and does not link to the existing UIView. How can I change properties of firstView from within secondView?

A: Create properties in your view controller's header file for the views:
@property (nonatomic, retain) UIView *firstView;
@property (nonatomic, retain) UILabel *label;

When you create the view and label assign them to the properties:
self.firstView = // create your view here

self.label = // create your label here

Create a button property on your UIView object so you can access it later:
@property (nonatomic, retain) UIButton *button;

Then in your view controller file, when you create everything, access the view's button property and add a target, like this:
[firstView.button addTarget:self action:@selector(changeLabel) forControlEvents:UIControlEventTouchUpInside];

Then you can simply have the method your button calls be like this:
- (void)changeLabel {
    self.label.text = @"Changed Text.";
}


text:
Q: COleControl GetClientRect returns area with bottom as 0 I have a control derived from COleControl. When loading this control , it calls OnSize, Within OnSize I am getting ClientRect area by calling GetClientRect and moving the control to the area got from GetClientRect.
First time when initializing the GetClientRect returns sizes in right and bottom. But next time when referesh happens, GetClientRect returns the area with bottom as 0. So I couldn't able to view the control.
Is there any way to get proper Client rect area in referesh also?
Or  Any idea how this client rect size determined?


text:
Q: How to grab elements by data-attribute with JavaScript / jQuery I want to grab the data-attribute value of two li elements. However, this does not work, because I don't seem to reference the right object (el) to grab them. The el is the currentTarget that holds the event listener.
Right now I grab them like this:
const refinementData = el.dataset.identifier

I need this data-attribute value (data-identifier) for a if-condition and iteration.
In first iteration this works fine and grabs the li elements.
In 2nd iteration it does not work because el also references other dom-elements (like e.g. a span). It tries to find the data-attribute (data-identifier) on the span and returns undefined then.
I tried alternatives to el e.g. jQuery solutions like this:
const refinementData2 = $('.refinement-list[data-identifier]');

or normal JavaScript versions like these:
const refinementData2 = document.querySelector('.refinement-list');

This is the HTML / Twig file where I want to grab values from the two li items:

                        {% for refinement in concreteProduct.productOptions.refinements %}
                            {# create
 with color of refinement key #}
                            {% if refinement.key != 'V00' %}

{% endif %}
                        {% endfor %}

                        {% for tag in concreteProduct.productOptions.tags %}
                            {# create
 with tag icon #}
                            {% if tag.key != 'T00' %}

{% endif %}
                        {% endfor %}

A: I assume the reason why you cannot get the right object is because it is a list. You need to iterate.
And regarding the way you get this info with jQuery, one way is to use the data method. For data-identifier, you call .data('identifier').
$('.refinement-list').each(function(){
  console.log( $(this).data('identifier') );
});

A: Try by giving li at first. This way, you can narrow it exactly to the el.
 $('li.refinement-list[data-identifier]')

DEMO

$('li.refinement-list[data-identifier]').each(function(i, obj) {
  console.log(obj.innerHTML, $(obj).attr('data-identifier'));
})

a

b


text:
Q: AES 128 how to brute force with partial key in python I am beginner in python so I need help
I have encrypted file and partial key file ,the partial key file have 96 bit out of 128 so i need to guess
the rest of the key and decrypt the file ,the hint is the first word is "hello" in the encrypted
my questions:
how to guess the rest of key ?
how to check if the key is the right key and how much time did take?

A: Sorry that the source code in my answer is in Java but up to now I never wrote a single line in python. As you showed us nearly no self written code I assume you need a path to find a way to do it in python.
Some basics to start with - AES 128 encryption has a 128 bit or 16 bytes long key for encryption and later decryption. You told us that you already know 96 bits = 12 bytes so there are "just" 4 bytes left to guess. Each byte has a "capacity" of (integer) 256 so in maximum you would have to test 256 * 256 * 256 * 256 combinations = 4,294,967,296 combinations. Assuming that the key is of random you need half of this to try to find the real key so in real there are 2,147,483,648 combinations - a todays home computer does this within an hour or less.
Below you find my code and I setup an online compiler with the code - in this code I "restricted" the search for the last 2 bytes (so it assumes that 14 of the
16 bytes are known) because the online compiler would abort the program with a "running too long" runtime error.
The code is well commented and not optimized for speed but for readability. In the end you get an output like this one (as I'm using a random key and
initialization vector for AES in CBC mode your output will be different), the online compiler is available here: https://repl.it/@javacrypto/JavaAesCbc128BruteForce:
AES CBC String Encryption - brute force decryption
key      length: 16 data: 0cb878f9da009be3ef487f54aa8c3230
keyGuess length: 16 data: 0cb878f9da009be3ef487f54aa8c0000
*** key found ***
key      length: 16 data: 0cb878f9da009be3ef487f54aa8c3230
plaintext: hello this is just plaintext

code:
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("AES CBC String Encryption - brute force decryption");

        String plaintext = "hello this is just plaintext";
        // this plaintext beginning is known
        String plaintextKnown = "hello";
        byte[] plaintextKnownByte = plaintextKnown.getBytes(StandardCharsets.UTF_8);
        // number of known bytes of the key
        int numberKeyBytes = 14; // 14 bytes = 112 bit known bits
        // random key & iv
        SecureRandom random = new SecureRandom();
        byte[] key = new byte[16]; // 16 byte = 128 bit keylength
        random.nextBytes(key);
        byte[] iv = new byte[16];
        random.nextBytes(iv);
        System.out.println("key      length: " + key.length + " data: " + bytesToHex(key));
        // setup cbc
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);
        // get plaintext
        byte[] plaintextByte = plaintext.getBytes(StandardCharsets.UTF_8);
        byte[] ciphertextByte = cipher.doFinal(plaintextByte);

        byte[] keyGuessed = new byte[16];
        System.arraycopy(key, 0, keyGuessed, 0, numberKeyBytes ); // copy first 14 bytes = 112 bit
        System.out.println("keyGuess length: " + keyGuessed.length + " data: " + bytesToHex(keyGuessed));
        for (int a = 0; a < 256; a++) {
            for (int b = 0; b < 256; b++) {
                for (int c = 0; c < 256; c++) {
                    for (int d = 0; d < 256; d++) {
                        keyGuessed[15] = (byte) d;
                        //System.out.println("keyGuess length: " + keyGuessed.length + " data: " + bytesToHex(keyGuessed));
                        decryptAesCbc128(keyGuessed, iv, ciphertextByte, plaintextKnownByte);
                    }
                    keyGuessed[14] = (byte) c;
                }
                keyGuessed[13] = (byte) b;
            }
            keyGuessed[12] = (byte) a;
        }
    }

    private static boolean decryptAesCbc128(byte[] key, byte[] iv, byte[] ciphertext, byte[] plaintextbyteKnown) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException {
        SecretKeySpec keySpecDecode = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParameterSpecDecode = new IvParameterSpec(iv);
        Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipherDecrypt.init(Cipher.DECRYPT_MODE, keySpecDecode, ivParameterSpecDecode);
        byte[] decryptedtext = new byte[0];
        try {
            decryptedtext = cipherDecrypt.doFinal(ciphertext);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            //e.printStackTrace();
            return false;
        }
        // partial array comparison
        boolean found = ByteBuffer.wrap(decryptedtext, 0, 5).equals(ByteBuffer.wrap(plaintextbyteKnown, 0, 5));
        if (found == false) {return false;}
        System.out.println("*** key found ***");
        System.out.println("key      length: " + key.length + " data: " + bytesToHex(key));
        System.out.println("plaintext: " + new String(decryptedtext));
        System.exit(0);
        return true;
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        return result.toString();
    }
}


text:
Q: Elimination of $\forall$ in Natural Deduction I have a doubt to prove by natural deduction of this:
$\vdash\forall x \forall y \varphi (x,y) \rightarrow \forall x \varphi(x,x)$
First of all, I took $\vdash\forall x \forall y \varphi (x,y)$ as a hipothesis
And eliminate $\forall y$, to deduce: $\forall x \varphi(x,x)$.
My question is: May I change y by x in this deduction?

A: Yes, it is valid.
The tedious way is to eliminate both universals to the same arbitrary constant, then reintroduce a universal from that.
$$\begin{array}{l|l:l} \hdashline
\quad 1. & \forall x \forall y\; \varphi (x,y) & \textsf{Assume} \\ \hdashline
\qquad 2. & \forall y\;\varphi (c, y) & 1, \forall\mathsf{E}\mid^x_c \\
\qquad 3. & \varphi (c,c) & 2, \forall\mathsf{E}\mid^y_c \\ \hline
\quad 4. & \forall x\;\varphi(x,x) & 3, \forall\mathsf{I}\mid^c_x \\ \hline
5. & \big(\forall x \forall y\; \varphi (x,y)\big) \to \big(\forall x\;\varphi(x,x) \big) & 1,4, \to\mathsf{I}
\end{array}$$
However, eliminating the universal $y$ to the bound variable $x$ is a valid short cut.


text:
Q: Overriding a Method with a Parameter of Varying Type Given the following example:
class A { }

class B : A { }

class C : A { }

I'd like all inherited classes to implement a function which performs a comparison of data specific to separate instances of these classes. The problem I'm facing is that one of the parameters is the same type as the type of the class that is implementing this method. Something like:
class A
{
    public virtual void CompareSomeData(A instanceOfA) { }
}

class B : A
{
    public override void CompareSomeData(B instanceOfB)
    {
        base.CompareSomeData(instanceOfB);
    }
}

class C : A
{
    public override void CompareSomeData(C instanceOfC)
    {
        base.CompareSomeData(instanceOfC);
    }
}

Obviously you can't override methods in C# in this manner. So what is the best pattern?
public virtual void CompareSomeData(object instance, Type typeOfInstance)
{
    // Cast the object to an instance of the type here?
}

OR
public virtual void CompareSomeData(A instanceOfA, Type typeOfInstance)
{
    // Cast the object to an instance of the type here?
}

OR some other method?
The idea here is that I would like to call into these methods from a generic method with a type constraint:
private void CompareData<T>(List<T> dataOld, List<T> dataNew) where T : A
{
    foreach (T item in dataNew)
    {
        item.CompareSomeData(GetItemToCompare(dataOld));
    }
}

Edit:
The problem I still see with both my suggestions and Marc's answer is that these really aren't type safe. There's no way for me to guarantee that an object passed to B is really B without a check in the method (if (instanceOfA is B) { ... }). I don't know if there's any way around this, but I might just have to work with it and throw an ArgumentException or something.

A: You cannot change the signature when overriding, but you can overload the method while overriding in parallel, for example:
class A {
    public virtual void CompareSomeData(A instanceOfA) { }
}

class B : A {
    public void CompareSomeData(B instanceOfB) {
        // ...
    }
    public override void CompareSomeData(A instanceOfA) {
        // ...
    }
}

Note that it would be common here for one of these two methods to call into the other (with the logic in one place only) - but which should call which is implementation-specific.
Note also that if you are only changing the return type, you need to do it a different way:
class A {
    public bool CompareSomeData(A instanceOfA) {
        return CompareSomeDataImpl(instanceOfA);
    }

    protected virtual bool CompareSomeDataImpl(A instanceOfA)
    { return true; }
}

class B : A {
    public new string CompareSomeData(A instanceOfA) {
        // ...
    }
    protected override bool CompareSomeDataImpl(A instanceOfA) {
        // ...
    }
}

A: It's ugly, but one way to ensure type safety without casting or requiring classes to know about the classes which inherit from them would be:
interface IDataComparer<T>
{
    void CompareSomeData(T instance);
}

class A : IDataComparer<A>
{
    public virtual void CompareSomeData(A instanceOfA) { }
}

class B : A, IDataComparer<B>
{
    public override void CompareSomeData(A instanceofA)
    {
        throw new ArgumentException("...");
    }

    public virtual void CompareSomeData(B instanceOfB)
    {
        base.CompareSomeData(instanceOfB);
    }
}

class C : A, IDataComparer<C>
{

    public override void CompareSomeData(A instanceofA)
    {
        throw new ArgumentException("...");
    }

    public virtual void CompareSomeData(C instanceOfC)
    {
        base.CompareSomeData(instanceOfC);
    }
}

Then in your CompareData<T> method, you would use the constraint T : IDataComparer<T>

A: Quick Disclaimer (Rant):
I'm not very fond of method overloading (same identifier, different parameter's type or different parameter's qty.). And, if it get's mix with method overriding (virtual methods), things get's more complicated.
Propposed Solution:
Inverse the process. Instead of overloading or overriding the class that handles the parameter, overload or override the class that is a parameter.
public abstract class ParameterDataClass
{
  public abstract bool CompareTo(StreamClass Stream);
} // class ParameterDataClass

public /* concrete */ class DataComparerClass
{
  internal /* nonvirtual */ void InternalComparison(string Data) { ... }

  public /* nonvirtual */ bool CompareThis(ParameterDataClass Data)
  {
    bool Result = false;

    if (Data != null)
    {
       Result = Data.CompareTo(this);
    }
  } // bool CompareThis(...)
} // class StreamClass

public /* concrete */ class CustomerClass: StreamDataClass
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public DateTime BirthDate { get; set; }

  public override bool CompareTo(StreamClass Stream)
  {
    bool Result = false;

    if (Stream!= null)
    {
      string Temp = "{" +
        FirstName.ToString() + "," +
        LastName.ToString() + "," +
        BirthDate.ToString() + "}"
      Result = Data.CompareTo(Temp);
    }
  } // bool CompareTo(...)

  return Result;
} // class CustomerClass

public /* concrete */ class AreaClass: StreamDataClass
{
  public int Top { get; set; }
  public int Left { get; set; }
  public int Width { get; set; }
  public int Height { get; set; }

  public override bool CompareTo(StreamClass Stream)
  {
    bool Result = false;

    if (Stream!= null)
    {
      string Temp = "{" +
        Top.ToString() + "," +
        Left.ToString() + "," +
        Width.ToString() + "," +
        Height.ToString() + "}"
      Result = Data.CompareTo(Temp);
    }
  } // bool CompareTo(...)

  return Result;
} // class AreaClass

public /* concrete */ class IntegerClass: StreamDataClass
{
  public int RealVaLue { get; set; }

  public override bool CompareTo(StreamClass Stream)
  {
    bool Result = false;

    if (Stream!= null)
    {
      Result = Data.CompareTo(RealValue.ToString());
    }
  } // bool CompareTo(...)

  return Result;
} // class IntegerClass

I don't remember the name of this technique, "Visitor Pattern", "Dispatch", whatever.
Hope it helps.
P.S. Do not forget to give an open tuna can for the kitty


text:
Q: Can windows 7 and 8 common dialogs be hooked I am trying to replace all Windows Common (Open/Save) filedialog calls with my own custom dialog. From what I read so far, I could do this with a hook on the calls either by writing my own or by using libraries like detours or easyhook. But someone told me recently that such an approach is only possible pre-Vista, because of the change in sessions architecture and it is impossible to do such a switch in Win 7/8. Now, I am not a guy who likes the word 'impossible' :) So if you have any advice on the matter, any at all, please do tell and I will appreciate your kindness.
For what I what to do, my application will be run by the user, it will reside in the tray, and when the user calls for Open/Save dialog from any application, it should replace the default common dialog with a custom dialog.

A: The newer style Common Item dialogs are implemented as standard COM objects, so you could just implement your own DLL that exposes the same COM interfaces (IFileOpenDialog, IFileSaveDialog, etc) and then override the default registrations in the Registry with your own.  That way, every app that uses the dialogs will load your DLL instead of Microsoft's.


text:
Q: Lambda destination not being triggered on Lambda error I have a Cloudformation stack which connects two Lambdas together via a Lambda destination config and an SQS queue.
The idea is that ErrorsFunction is fired when there is an error in HelloAddFunction.
This stack deploys fine, and HelloAddFunction works fine when I invoke it with some integer values.
I can see an error in HelloAddFunction when I invoke it with non- integer values, but no corresponding error seems to be received by ErrorsFunction.
The binding of ErrorsFunction to ErrorsQueue  seems to be working - if I push a message onto ErrorsQueue via the console, it's received by ErrorsFunction.
So it feels like the Lambda destination config is somehow not working.
What am I missing here ?
TIA
AWSTemplateFormatVersion: '2010-09-09'
Outputs: {}
Parameters:
  AppName:
    Type: String
  MemorySizeSmall:
    Default: 512
    Type: Number
  RuntimeVersion:
    Default: '3.8'
    Type: String
  TimeoutShort:
    Default: 5
    Type: Number
Resources:
  HelloAddEventConfig:
    Properties:
      DestinationConfig:
        OnFailure:
          Destination:
            Fn::GetAtt:
            - ErrorsQueue
            - Arn
      FunctionName:
        Ref: HelloAddFunction
      MaximumRetryAttempts: 0
      Qualifier: $LATEST
    Type: AWS::Lambda::EventInvokeConfig
  HelloAddFunction:
    Properties:
      Code:
        ZipFile: |
          def handler(event, context):
            x, y = int(event["x"]), int(event["y"])
            return x+y
      Handler: index.handler
      MemorySize:
        Ref: MemorySizeSmall
      Role:
        Fn::GetAtt:
        - HelloAddRole
        - Arn
      Runtime:
        Fn::Sub: python${RuntimeVersion}
      Timeout:
        Ref: TimeoutShort
    Type: AWS::Lambda::Function
  HelloAddRole:
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Action: sts:AssumeRole
          Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
        Version: '2012-10-17'
      Policies:
      - PolicyDocument:
          Statement:
          - Action: logs:*
            Effect: Allow
            Resource: '*'
          - Action: sqs:*
            Effect: Allow
            Resource: '*'
          Version: '2012-10-17'
        PolicyName:
          Fn::Sub: hello-add-role-policy-${AWS::StackName}
    Type: AWS::IAM::Role
  ErrorsFunction:
    Properties:
      Code:
        ZipFile: |
          def handler(event, context):
            print (event)
      Handler: index.handler
      MemorySize:
        Ref: MemorySizeSmall
      Role:
        Fn::GetAtt:
        - ErrorsRole
        - Arn
      Runtime:
        Fn::Sub: python${RuntimeVersion}
      Timeout:
        Ref: TimeoutShort
    Type: AWS::Lambda::Function
  ErrorsQueue:
    Properties: {}
    Type: AWS::SQS::Queue
  ErrorsQueueBinding:
    Properties:
      EventSourceArn:
        Fn::GetAtt:
        - ErrorsQueue
        - Arn
      FunctionName:
        Ref: ErrorsFunction
    Type: AWS::Lambda::EventSourceMapping
  ErrorsRole:
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Action: sts:AssumeRole
          Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
        Version: '2012-10-17'
      Policies:
      - PolicyDocument:
          Statement:
          - Action: logs:*
            Effect: Allow
            Resource: '*'
          - Action: sqs:*
            Effect: Allow
            Resource: '*'
          Version: '2012-10-17'
        PolicyName:
          Fn::Sub: errors-role-policy-${AWS::StackName}
    Type: AWS::IAM::Role

A: Your template is fine, but lambda destinations are for asynchronous invocations of your function only. So you have to make such an invocation, which can be done using AWS CLI (--invocation-type Event). AWS Console is synchronous only.
aws lambda invoke --function-name <HelloAddFunctionnaem> --invocation-type Event --payload '{"x": 3, "y": "SSS"}' /dev/stdout


text:
Q: Days Until Christmas Application Java Value Will Not Round Up I'm teaching myself Java and I am working on this application that will count the days until Christmas. The HOUR_OF_DAY, MONTH, and SECOND values of the GregorianCalendar and Date objects for today and Christmas are all set to zero. By debugging I can see the variable for the difference in days in milliseconds and it gives me a time of 1641599724 milliseconds which comes out to be 18.99999 days but it wont round up to 19 no matter what I try!
I have tried Math.ceil method to try and round up but I can't get it to equal 19.
FIRST: DataUtils class stores/modifies input from the user
package chapter13datesstrings;

import java.util.*;

public class DateUtils {

static final int MILLS_IN_DAY = 24 * 60 * 60 * 1000;

public static Date getCurrentDate(){
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.set(Calendar.HOUR_OF_DAY, 0);
    currentDate.set(Calendar.MINUTE, 0);
    currentDate.set(Calendar.SECOND, 0);
    return currentDate.getTime();
}

public static Date createDate(int year, int month, int day){
    GregorianCalendar date = new GregorianCalendar(year, month, day);
    return date.getTime();
}

public static Date stripTime(Date date){
    GregorianCalendar noTimeDate = new GregorianCalendar();
    noTimeDate.setTime(date);
    noTimeDate.set(Calendar.HOUR, 0);
    noTimeDate.set(Calendar.MINUTE,0);
    noTimeDate.set(Calendar.SECOND, 0);
    return noTimeDate.getTime();
}

public static double daysDiff(Date date1, Date date2){

    date1 = stripTime(date1);
    date2 = stripTime(date2);

   long longDate1 = date1.getTime();
   long longDate2 = date2.getTime();

   long longDiff = longDate2 - longDate1;

   return (int) (Math.ceil(longDiff / MILLS_IN_DAY));
}

}

SECOND: DateUtilExample class provides input to the DataUtils class
package chapter13datesstrings;

import java.util.*;
import java.text.*;

public class DateUtilExample {

public void thisIsCode(){

GregorianCalendar currentGC = new GregorianCalendar();
int currentYear = currentGC.get(Calendar.YEAR); //sets current year

Date currentDate = DateUtils.getCurrentDate(); //create current date object
Date christmas = DateUtils.createDate(currentYear, Calendar.DECEMBER, 25); //set christmas date
int daysToChristmas = DateUtils.daysDiff(currentDate, christmas); // days until christmas

DateFormat date = DateFormat.getDateInstance(Calendar.LONG);
String formattedToday = date.format(currentDate);

/**** Output Items *****/
System.out.println("Today is " + formattedToday);
System.out.println("Number of Days 'Till Xmas: " + daysToChristmas + " days");
}

}

MAIN METHOD CLASS
package chapter13datesstrings;

import java.util.Date;
import java.text.DateFormat;

public class Chapter13DatesStrings {

public static void theDates(){
    DateUtilExample dateUtilExample = new DateUtilExample();
    dateUtilExample.thisIsCode();
}

public static void main(String[] args) {
 theDates();
}

}

A: When you divide two integers in Java, the result is rounded down ("truncated") automatically.
The expression longDiff / MILLS_IN_DAY isn't equal to 18.99999, it is equal to 18.  Java essentially calculates 18.99999 and then throws everything after the decimal point away, before you can do anything with it.  Rounding up with ceil won't help at that point, because you just end up calculating ceil(18) which is just 18.
One solution to this is to cast the numbers to double before you divide them.  double's are floating point values, so dividing them does not round the result down.  To use doubles, replace
longDiff / MILLS_IN_DAY

with
((double)longDiff) / ((double)MILLS_IN_DAY)

Another solution, which may be more computationally efficient but a little bit less elegant is to simply add 1 to the result.  This isn't strictly equivalent, because when you are within a millisecond of midnight the result will be a day more than you expected, but this is essentially unnoticeable.  To take this approach, you would replace the line:
return (int) (Math.ceil(longDiff / MILLS_IN_DAY));

with
return longDiff / MILLS_IN_DAY + 1;

A: Alternatively to what SelectricSimian said,
this is something that can be done in a couple of lines using the Calendar API provided by java.
To simply get the day difference between the current time and a given day, you can use:
public static void main(String[] args) {
    System.out.println(getDaysUntil(Calendar.DECEMBER, 25) + " day(s).");
    // If the date is December 25th, this will output "365 day(s)"
    // If the date is December 24th, this will output "1 day(s)"
}

public static int getDaysUntil(int month, int day) {
    /**
     * First get a properly formatted calendar representing right now. This
     * should include leap years and local. With this calendar, we get the
     * day of the year.
     */
    Calendar calendar = Calendar.getInstance();
    int today = calendar.get(Calendar.DAY_OF_YEAR);

    /**
     * Now change the day and month of the current calendar to the given day
     * and month.
     */
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, day);
    int desiredDay = calendar.get(Calendar.DAY_OF_YEAR);

    /**
     * Then we just get the difference between now and then.
     */
    int difference = desiredDay - today;

    /**
     * If the desiredDay has passed already, or it's currently the
     * desiredDay, we need to recalculate the difference.
     */
    if (difference <= 0) {
        /**
         * We start by getting the days until the end of the year.
         */
        calendar.set(Calendar.MONTH, 11);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        int daysUntilEnd = calendar.get(Calendar.DAY_OF_YEAR) - today;

        /**
         * Then, move the calendar forward a year and get the day of year
         * for the desired day again. We recalculate the number of days just
         * in case next year is a leap year.
         */
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        desiredDay = calendar.get(Calendar.DAY_OF_YEAR);

        /**
         * Finally, just add daysUntilEnd and desiredDay to get the updated
         * difference.
         */
        difference = daysUntilEnd + desiredDay;
    }

    return difference;
}