text:
Q: Containerised Azure function (v4, dotnet-isolated) breaks when trying to use environment variables as config source This follows on from a previous question. I'm trying to build an Azure function to run as a Linux container image in an isolated process using .NET 6 and v4 of the functions runtime.
I have followed the Microsoft guide to get a working, running sample function with HTTP trigger. I have then begun the process of adding my code to the app and immediately become blocked. This is the Main method of my Program:
public static void Main()
{
    var host = new HostBuilder()
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureAppConfiguration((context, builder) =>
        {
            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            builder.AddEnvironmentVariables();
        })
        .ConfigureServices((context, collection) => ConfigureServices(collection, context.Configuration))
        .Build();

    host.Run();
}

What I've discovered is that the function works fine until I add the line builder.AddEnvironmentVariables();. With this change only, the function suddenly craps out on startup with the exception:

System.InvalidOperationException at Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcFunctionInvocationDispatcherLoadBalancer.GetLanguageWorkerChannel

There's a message hidden in there saying "Did not find any initialized language workers" which I understand is Azure Function language for "something bad happened during startup but I'm not going to tell you what or why".
In my particular use case I'm depending on the function being able to use environment variables as a config source because my pipeline will be passing these to the ARM template as site config. So my question is, how is this possible in isolated mode?

A: Well it turns out that environment variables are added automatically by the call to ConfigureFunctionsWorkerDefaults. You can see this here in WorkerHostBuilderExtensions. I have no idea why attempting to add environment variables as a config source in the traditional dotnet core way causes the whole thing to blow up, but at least I'm unblocked. Hope this helps someone else.
It's woth also pointing out that this will affect the order in which you use the ConfigureAppConfiguration and ConfigureFunctionsWorkerDefaults extensions. Since the latter adds console input and environment variables as config sources, if you also use an appsettings.json on disk it's likely you'll want environment variables to override its config so ConfigureFunctionsWorkerDefaults would need to be called after ConfigureAppConfiguration. Therefore my Program looks like this:
public class Program
{
    public static async Task Main()
    {
        var host = new HostBuilder()
            .ConfigureAppConfiguration((context, configurationBuilder) =>
            {
                configurationBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

                if (context.HostingEnvironment.IsDevelopment())
                {
                    configurationBuilder.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true);
                }
                else
                {
                    configurationBuilder.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
                }
            })
            .ConfigureFunctionsWorkerDefaults()
            .ConfigureServices((context, collection) => ConfigureServices(collection, context.Configuration))
            .Build();

        await host.RunAsync();
    }

    private static void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        services
            .AddLogging()
            .AddDomainLayer(configuration)
            .AddHttpLayer(configuration)
            .AddKeyVaultLayer(configuration);
    }
}


text:
Q: Should I use std::endl after every cout statement? So I am a complete beginner in C++. I am following the book C++ primer. The author always uses std::endl after every std::cout statement to flush the buffer. My quesion is should I always use std::endl?
#include<iostream>
int main()
{
    int sum=0,val=1;
    while(val<=10)
    {
        sum+=val;
        ++val;
    }
    std::cout<<"Sum of the 1 to 10 is: "<<sum<<std::endl;
    return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simplest way to fill out a PDF file in Java. ( creating invoices ) I am trying to find a good method for creating customer invoices in Java.  I have been looking into Jasper Reports but it seems a bit heavy for what I need and I am working through some troubles with it now.
I am just looking for a simple way to edit fields and tables in a pdf file.  Alternatively, a way to create a PDF in java with a logo and a table of different charges for a particular customer.
Thanks!

A: "Alternatively, a way to create a PDF in java with a logo and a table of different charges for a particular customer." - Use itext. It is a stable and time tested library.
There is another library - flying saucer which uses itext internally but works really well with xml, html or xhtml. This meets almost all needs and takes good care of styles and formatting. You can even export an html document to pdf.
https://github.com/flyingsaucerproject/flyingsaucer


text:
Q: Recursively Read Files Spark wholeTextFiles I have a directory in an azure data lake that has the following path:
'adl://home/../psgdata/clusters/iptiqadata-prod-cluster-eus2-01/psgdata/mib'
Within this directory there are a number of other directories (50) that have the format 20190404.
The directory 'adl://home/../psgdata/clusters/iptiqadata-prod-cluster-eus2-01/psgdata/mib/20180404' contains 100 or so xml files which I am working with.
I can create an rdd for each of the sub-folders which works fine, but ideally I want to pass only the top path, and have spark recursively find the files. I have read other SO posts and tried using a wildcard thus:
pathWild = 'adl://home/../psgdata/clusters/iptiqadata-prod-cluster-eus2-01/psgdata/mib/*'
rdd = sc.wholeTextFiles(pathWild)
rdd.count()

But it just freezes and does nothing at all, seems to completely destroy the kernel. I am working in Jupyter on Spark 2.x. New to spark. Thanks!

A: Try this:
pathWild = 'adl://home/../psgdata/clusters/iptiqadata-prod-cluster-eus2-01/psgdata/mib/*/*'


text:
Q: ipad web app not adjustd for portrait mode, uiwebview, I've a web application for iphone/ipad. When I view it in mobile safari it appears good both in landscape and portrait mode. But when I open it in my own ipad web app (under uiwebview), it appears good in landscape mode, but contents are cut-off in portrait mode.
How to fix it. Am i supposed to fix it on server side, or in ipad application?
Regards

A: If it works in Mobile Safari and not in your wrapper app using UIWebView, it is possible that the problem comes from the application, and that your webview is not properly resized when the device rotates to landscape.
Try setting the webview's autoresizingMask as follow in your view setup code :
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

or, if you defined your webview in Interface Builder, use the "size inspector" to set the appropriate autoresizing mask (every red line must be selected in the resizing diagram).


text:
Q: Chrome ignoring Window network DNS settings I had found the answer at Why is Chromium bypassing /etc/hosts and dnsmasq? but it's outdated and instructions on its answers aren't working anymore.
I have a local BIND DNS server, where I have lots of domains blocked. It works on everything, except Chrome.
I understand Chrome has its own caches, claiming to be meant to speed up page loads, but clearly these caches bypassing the DNS server settings doesn't aim at speed, but in bypassing ads blocks.
Settings > Advanced > Privacy > Preload pages for faster browsing and searching has always been disabled here. chrome://net-internals/#dns > chear host cache also didn't work.


text:
Q: Google Cloud DNS giving 404 on top level domain I'm using Google Cloud DNS and Google App Engine Standard to configure an application.
Currently, I configured the DNS like this
mydomain.com.   A   300
216.239.32.21
216.239.34.21
216.239.36.21
216.239.38.21

mydomain.com.   AAAA    300
2001:4860:4802:32::15
2001:4860:4802:34::15
2001:4860:4802:36::15
2001:4860:4802:38::15

mydomain.com.   MX  216000
1 aspmx.l.google.com.
5 alt1.aspmx.l.google.com.
5 alt2.aspmx.l.google.com.
10 alt3.aspmx.l.google.com.
10 alt4.aspmx.l.google.com.

mydomain.com.   NS  21600
ns-cloud-c1.googledomains.com.
ns-cloud-c2.googledomains.com.
ns-cloud-c3.googledomains.com.
ns-cloud-c4.googledomains.com.

mydomain.com.   SOA 21600
ns-cloud-c1.googledomains.com. cloud-dns-hostmaster.google.com. 1 21600 3600 259200 300

@.mydomain.com. A   300
216.239.32.21
216.239.34.21
216.239.36.21
216.239.38.21

api.mydomain.com.   CNAME   300
ghs.googlehosted.com.

stage.mydomain.com. CNAME   300
ghs.googlehosted.com.

api.stage.mydomain.com. CNAME   300
ghs.googlehosted.com.

www.stage.mydomain.com. CNAME   300
ghs.googlehosted.com.

www.mydomain.com.   CNAME   300
ghs.googlehosted.com.

So that I configured an stage environment using these domains and it is working so far.

*

*api.stage.mydomain.com

*stage.mydomain.com / www.stage.mydomain.com

I recently added the configuration for production with these domains

*

*api.mydomain.com

*mydomain.com / www.mydomain.com

And it is working so far except that mydomain.com is returning 404 http status from Google:
404. That's an error.

The requested URL was not found on this server. That's all we know.

Does anyone has encountered this problem before? How can it be solved so that mydomain.com starts working?


text:
Q: Connection lost when connect R to MySQL using collect I would like to use dplyr and RMySQL to work with my large data. There is no issues with dplyr code. The problem (I think) is about exporting data out of MySQL to R. My connection is dropped every time even I am using n=Inf in collect. Theoretically, my data should have more than 50K rows, but I can only get around 15K back. Any suggestions are appreciated.
Approach 1
library(dplyr)
library(RMySQL)

# Connect to a database and select a table
my_db <- src_mysql(dbname='aermod_1', host = "localhost", user = "root", password = "")
my_tbl <- tbl(my_db, "db_table")
out_summary_station_raw <- select(my_tbl, -c(X, Y, AVERAGE_CONC))
out_station_mean_local <- collect(out_summary_station_raw)

Approach 2: using Pool
library(pool)
library(RMySQL)
library(dplyr)

pool <- dbPool(
  drv = RMySQL::MySQL(),
  dbname = "aermod_1",
  host = "localhost",
  username = "root",
  password = ""
)

out_summary_station_raw <- src_pool(pool) %>% tbl("aermod_final") %>% select(-c(X, Y, AVERAGE_CONC))

out_station_mean_local <- collect(out_summary_station_raw, n = Inf)

Warning message (both approaches):
Warning messages:
1: In dbFetch(res, n) : error while fetching rows
2: Only first 15,549 results retrieved. Use n = Inf to retrieve all.

Update:
Checked log and it looks fine from the server side. For my example, the slow-log said Query_time: 79.348351  Lock_time: 0.000000 Rows_sent: 15552  Rows_examined: 16449696, but collect just could not retrieve the full data. I Am able to replicate the same move using MySQL Bench.

A: As discussed here
https://github.com/tidyverse/dplyr/issues/1968,
https://github.com/tidyverse/dplyr/blob/addb214812f2f45f189ad2061c96ea7920e4db7f/NEWS.md  and https://github.com/tidyverse/dplyr/commit/addb214812f2f45f189ad2061c96ea7920e4db7fthis package issue seems to be addresed.
What  version of the dplyr package  are you using?

A: After the most recent RMySQL update, I noticed that I could not collect() data from large views, and I reported it as an issue. Your problem might be related.
One thing to try is to roll back to the last version.
devtools::install_version("RMySQL", version = "0.10.9",
                          repos = "http://cran.us.r-project.org")


text:
Q: Google Maps API not working correctly under safari If I do something like
map = new GMap2(document.getElementById(mapCanvas));
directions = new GDirections(map);
directions.load("SOME DIRECTIONS HERE");

Under firefox on LInux it works great!
Under safari it displays the map but not the directions.
What gives?

A: Figured it out.
The Google Maps API will not let you use GDirections without a valid API Key. Also you can't use an ip, so you have to use DNS.


text:
Q: Vertica: split string to array and group over to get set of unique values? I have a column on Vertica which stores numbers as a string of values concatenated by commas, for example: 12,15,17, for example:
ID  |  values
----------------------
A   | 1,3,5
A   | 2,3,5,6
B   | 1,2,3

I'd like to get this as my end result:
ID  |  values
----------------------
A   | 1,2,3,5,6
B   | 1,2,3

meaning, for each ID a s et of all different values. How do I do this?
(Using Vertica 8.1.1)

A: Found it:
Assuming you know what is the max number of values per entry (let's assume 6 in this example):
with m as (
  select 1 as i union all
  select 2 as i union all
  select 3 as i union all
  select 4 as i union all
  select 5 as i union all
  select 6 as i),
splitted_data as (
  select distinct ID, split_part('values',',',i) as value
  from main_table cross join m)
select ID, rtrim(agg_concatenate(value||','),',') as values
from splitted_data


text:
Q: Problems to detect arrays in JSON files using YAJL trees in C I try to parse a JSON file using yajl 2.0.4 (using yajl_tree.h) but I have some problems to detect whether the found value is an array or not (even if I use YAJL_IS_ARRAY, it seems that the type field is not set.
Here is my JSON file :
{
    "equipment": [
        {
            "name": "mynode",
            "type": "node",
            "attribute": [
                {
                    "name": "cpu_available",
                    "value": "8"
                },
                {
                    "name": "memory_available",
                    "value": "24"
                }
            ]
        }
    ]
}

Here is my code :
const char *path[] = { "equipment", (const char *) 0 };
yajl_val v = yajl_tree_get( node, path, yajl_t_array );
if ( v && YAJL_IS_ARRAY( v ) ) {
    for ( i = 0; i < v->u.array.len; i++ ) {
        yajl_val obj = v->u.array.values[i];
        if( obj && YAJL_IS_ARRAY(obj)) {
            for ( j = 0; j < obj->u.object.len; j++ ) {
                yajl_val obj2 = obj->u.array.values[ j ];
                if(obj2 && YAJL_IS_ARRAY(obj2)) {
                    for ( k = 0; k < obj2->u.array.len; k++ ) {
                        yajl_val obj3 = obj->u.array.values[ k ];
                        const char * key3 = obj3->u.object.keys[ k ];
                        yajl_val val3 = obj3->u.object.values[ k ];
                            printf( "      %s : %s \n", key3, val3->u.string );
                    }
                }
                else {
                    const char * key2 = obj->u.object.keys[ j ];
                    yajl_val val2 = obj->u.object.values[ j ];
                        printf( "    %s : %s \n", key2, val2->u.string );
                }
            }
        }
        else {
            const char * key = obj->u.object.keys[ i ];
            yajl_val val = obj->u.object.values[ i ];
                printf( "  %s : %s ", key, val->u.string );
        }
    }
}

When I use this code I never enter the YAJL_IS_ARRAY even if the value is an array, for example attribute. So I was wondering if YAJL_IS_ARRAY is not correct to get an array, what must be used ?  Moreover, is it normal that the type of my objects (obj, obj2...) have no correct types ? What mistake did I do ?
Thanks in advance for your help. :)

A: Your JSON isn't an array. It's a dictionary with a key "equipment", and the value of "equipment" is an array. In this case, an array containing a single dictionary.


text:
Q: On netlogo, what command do I use to make a turtle stop if the patch it wants to move to is a certain color I'm making a maze on netlogo and I want to do it so that once it tries to walk into the violet lines, it'll stay on its own patch instead of moving forward.  What command would that be? I tried bk 1 to reverse the fd 1 but it doesn't work all the time

A: You can undo your step like this:
ask turtles [
  fd 1
  if pcolor = violet [fd -1]
]

Or you can check ahead of time as Marzy answered. Basically it's the difference of asking for forgiveness vs permission :-)

A: I hope this example answer your questions:
turtles-own [target]
to setup
  clear-all
  reset-ticks
  ask n-of 100 patches [
    set pcolor red
    ]
  create-turtles 1
  [ move-to one-of patches with [pcolor != red]
    set heading 90
    set target one-of patches with [pcolor != red]
    ask target
    [
      set pcolor green
      ]
    ]
end

to go

  ask turtles
  [ifelse pcolor != green
  [
    ifelse [pcolor] of patch-ahead 1 != red
    [
      Your-Move-Function
    ]
    [
      Your-Bounce-Function
    ]
    leave-a-trail

  ]
  [stop
  print ticks
  ]
  ]
  tick
end

to Your-Move-Function
  let t target
  face min-one-of all-possible-moves [distance t]
  fd 1
end

to Your-Bounce-Function
  let t target
  face min-one-of all-possible-moves [distance t]
  end

to-report all-possible-moves
  report patches in-radius 1 with [pcolor != red and distance myself  <= 1 and distance myself  > 0 and plabel = "" ]
end

to leave-a-trail
  ask patch-here [set plabel ticks]
end

This is how it works:

Random patches are colored Red to show walls or obstacles, one turtle is created in a random location with a random target which is colored green:
I have used a variable to store all available patches which turtle can step on , but since I have considered a target for the turtle, turtle chooses the one patch which is closest to the target, and since I have noticed in some cases it might go in circle I have asked the turtle to leave tick number which is its move number as a plabel, you can use a variable for that for specifying if that path was already selected or not.


text:
Q: make objects and fields dynamically in javascript instead of using getParameterByName('Field', PostData) (PostData == $('form').serialize();)
I would like to write PostData.Field, how can i do that with javascript?

A: You could write your own extension to return an object like you want, here's what that looks like:
jQuery.fn.MakeIntoFields = function() {
  var arr = this.serializeArray();
  var props = {};
  $.each(arr, function(i, f) {
    props[f.name] = f.value;
  });
  return props;
};

You'd call it by doing this:
var PostData = $("form").MakeIntoFields();

Then you could access the values with dot notation like you want:
PostData.fieldNameHere
//or...
PostData["fieldNameHere"]

You can see this working against a demo <form> here

A: Do you mean something like this?
PostData = {
  field: $('input[name=Field]').val(),
  otherData: 'customdata'
};


text:
Q: How to log in in jfrog container registry? I start the container registry:
docker run --name artifactory -d -p 8081:8081 -p 8082:8082 docker.bintray.io/jfrog/artifactory-jcr:latest

I was able to login using the UI and create a repository etc.
Now I want to login using the CLI:
docker login localhost:8082
Username: admin
Password:
Error response from daemon: Get http://localhost:8082/v2/: received unexpected HTTP status: 503 Service Unavailable

What am I doing wrong? I got the same error when I use my local 192.168.x.x address (and after adding it to my insecure registries).

A: I tried it too and had to search for a while.
Using the API I saw: "message" : "status code: 503, reason phrase: In order to use Artifactory you must accept the EULA first"
I didn't find how to sign it using the UI but it worked this way:
$ curl -XPOST -vu admin:password http://localhost:8082/artifactory/ui/jcr/eula/accept

After that I was able to login:
$ curl -XPOST -vu admin:password http://localhost:8082/artifactory/ui/jcr/eula/accept
8:35
docker login localhost:8081/docker/test
Username: admin
Password:
Login Succeeded

A: First, let us test if the docker client can reach the JCR by running the below curl,

curl -u http://localhost:8082/artifactory/api/docker/docker/v2/token

Moreover, it looks like the docker client isn't taking localhost as the docker container's IP but the server's host, to check this, add the following line in /etc/hosts file,

127.0.0.1 myartifactory

then access it using myartifactory:8082 thru the UI and if it is accessible then use the docker login as "docker login myartifactory:8082"

A: Because each repo can have different authentication or authorization, you need to login to a specific repo.
Let's say you created a docker repo "myrepo", you can login as follows
docker login localhost:8082/myrepo


text:
Q: select2 AJAX'd to a model, configuration So, I just discovered select2.  Awesome.  Now I'm trying to figure out how to use it, server side with ajax / json.  All of the examples I see, everywhere, show using select2 with JSONP to retrieve data from an external source.  I feel like this should be even easier if calling from a local model, no?  I'll get right to the nitty gritty.  json returns a value, but the searchbox doesn't autocomplete, it stays blank.
view html:
<%= form_tag request_pal_path, remote: true do %>
  <%= hidden_field_tag :email, nil, class: 'ui-corner-all' %>
  <%= submit_tag "Send request", class: 'button' %>
<% end %>

and calling some js on it:
$(document).ready(function() {
  $("#find_user #email").select2({
    width: '400px',
    placeholder: "Find user...",
    minimumInputLength: 1,
    multiple: false,
    id: function(obj) {
      return obj.id; // use slug field for id
    },
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
      url: "/users",
      dataType: 'json',
      data: function (term, page) {
        return {
          q: term, // search term
          page_limit: 10
        };
      },
      results: function (data, page) { // parse the results into the format expected by Select2.
        // since we are using custom formatting functions we do not need to alter remote JSON data
        return {results: data};
      }
    },
    formatResult: FormatResult,
    formatSelection: FormatSelection,
    escapeMarkup: function (m) { return m; }
  });

})

function FormatResult(user) {
  return '<div>' + user.name + '</div>';
}

function FormatSelection(user) {
  return user.name;
}

which goes to the controller, user index action:
def index
  @find = User.where('name LIKE ?', "%#{params[:q]}%")
  @users = @find.where('id NOT IN (?)', current_user.id).order('random()').page(params[:page]).per(100)
  @title = "Potential pals"
  respond_to do |format|
    format.html
    format.js {
      @find = @find
      @users = @users
    }
    format.json { @find }
  end
end

and I made a .json file for it to respond to (not sure if this is even necessary):
<% @find.each do |user| %>
  <%= user.name %>
<% end %>

So, the json is working, to an extent.  If I look in the developer console, it shows a response coming from http://localhost:3000/users.json?q=tay, or whereever, and it returns a single value, for Taylor (in that instance).  But when I search inside of the select2 search box, it just spins and spins, with no results.  No console errors, so that's nice, ha.  Thoughts?  Thanks!

A: The select2 plugin expects JSON data in the following format:
[ { "text": "Taylor", "id": 1 }, { "text" : "Tailor", "id": 2 }, ...]

So you need to replace name with text in your user model when converting to JSON:
def as_json(*args)
    super.tap { |hash| hash["text"] = hash.delete "name" }
end

and then in the index method:
def index
  @find = User.where('name LIKE ?', "%#{params[:q]}%")
  @users = @find.where('id NOT IN (?)', current_user.id).order('random()').page(params[:page]).per(100)
  @title = "Potential pals"
  respond_to do |format|
    format.html
    format.js {
      @find = @find
      @users = @users
    }
    format.json { render json: @find, :only => [:text, :id] }  # might be :name here ?
  end
end

and you don't need the view for JSON.

A: I guess the problem is in your .json file, since select2 needs json array or json object. Try to remove it and respond with format.json { render json: @find.to_json }. Other code seems ok to me.


text:
Q: References to roslyn compiled from file from another project I am trying to build an assembly dynamically, using roslyn, and to later be loaded from the
ASP.NET CORE 'AddApplicationParts' extension method, at the startup phase of my web app.
I am loading a .cs file externally from another project, where it works great.
Here is the code, i got everything to work, but i cannot seem to figure out how to load 'references' from the external project, i tried the so called 'add references' from metadatafile but no luck.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Reflection;
using System.Collections.Immutable;

namespace WebApplication1
{

    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .Build();

            Pr2.Main2();

            host.Run();
        }
    }

    public class Pr2
    {
        public static void Main2()
        {
            string code = File.ReadAllText(@"c:\users\victor\documents\visual studio 2017\Projects\WebApplication2\WebApplication2\Controllers\HomeController.cs");
            SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(code);

            CSharpCompilation compilation = CreateCompilation(tree);
            SemanticModel model = compilation.GetSemanticModel(tree);

            ShowLocalDeclarations(tree, model);
            ShowDiagnostics(compilation);
            ExecuteCode(compilation);

        }

        private static void ShowLocalDeclarations(SyntaxTree tree, SemanticModel model)
        {
            IEnumerable<LocalDeclarationStatementSyntax> locals = tree.GetRoot()
                             .DescendantNodes()
                             .OfType<LocalDeclarationStatementSyntax>();

            foreach (var node in locals)
            {
                Microsoft.CodeAnalysis.TypeInfo type = model.GetTypeInfo(node.Declaration.Type);
                Console.WriteLine("{0} {1}", type.Type, node.Declaration);
            }
        }

        private static Assembly ExecuteCode(CSharpCompilation compilation)
        {
            Assembly roRet;
            using (var stream = new MemoryStream())
            {
                compilation.Emit(stream);

                roRet = Assembly.Load(stream.GetBuffer());
            }

            return roRet;
        }

        private static void ShowDiagnostics(CSharpCompilation compilation)
        {
            ImmutableArray<Diagnostic> diagnostics = compilation.GetDiagnostics();
            foreach (var diagnostic in diagnostics)
            {
                // OVER HERE WE SEE THE ERRORS.
                Console.WriteLine(diagnostic.ToString());
            }
        }

        private static CSharpCompilation CreateCompilation(SyntaxTree tree)
        {
            CSharpCompilationOptions options = new CSharpCompilationOptions(
                                            OutputKind.DynamicallyLinkedLibrary);

            PortableExecutableReference reference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

            CSharpCompilation compilation =
                CSharpCompilation.Create("test")
                                 .WithOptions(options)
                                 .AddSyntaxTrees(tree)
                                 .AddReferences(reference);
            return compilation;
        }
    }
}

The external file is in another asp.net core project, started fresh from vs2017 core templates, using the 4.6.2 framework. !!
using Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Controllers
{
    public class TestController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}

A: The issue is that you're referencing only mscorlib when compiling the file, but you need to reference all assemblies the file depends on. You could try to do this one assembly at a time, but I think a better option is to take advantage of the fact that you have a second csproj, which contains all the information you need. You just need to get the information from there somehow.
To do that, you can use MSBuild. Reference the Microsoft.Build and Microsoft.Build.Tasks.Core packages and then use this code (adapted from this answer):
private static IEnumerable<string> GetReferences(string projectFileName)
{
    var projectInstance = new ProjectInstance(projectFileName);
    var result = BuildManager.DefaultBuildManager.Build(
        new BuildParameters(),
        new BuildRequestData(projectInstance, new[]
        {
            "ResolveProjectReferences",
            "ResolveAssemblyReferences"
        }));

    IEnumerable<string> GetResultItems(string targetName)
    {
        var buildResult = result.ResultsByTarget[targetName];
        var buildResultItems = buildResult.Items;

        return buildResultItems.Select(item => item.ItemSpec);
    }

    return GetResultItems("ResolveProjectReferences")
        .Concat(GetResultItems("ResolveAssemblyReferences"));
}

// in Main2
var references = GetReferences(@"C:\code\tmp\roslyn references\WebApplication2\WebApplication2.csproj");

CSharpCompilation compilation = CreateCompilation(tree, references);

// in CreateCompilation
CSharpCompilation compilation =
    CSharpCompilation.Create("test")
        .WithOptions(options)
        .AddSyntaxTrees(tree)
        .AddReferences(references.Select(path => MetadataReference.CreateFromFile(path)));


text:
Q: Intersection of unipotent radicals of adjacent Borel subgroups This is a question in the context of Kottwitz' paper 'On the Hodge-Newton decomposition of split groups.'
Let $F$ be a finite extension of $\mathbb{Q}_p$ with DVR $\mathcal{O}_F$ and let $G$ be a reductive group defined over $\mathcal{O}_F$. Further let $T$ be a split maximal torus and let $B_1$ and $B_2$ be two adjacent Borel subgroups containing $T$. So we have a root $\alpha$ which is positive for $B_1$ and negative for $B_2$. Denote by $U_1$ and $U_2$ the unipotent radicals of the above Borels and by $U_\beta$ the root subgroup corresponding to any root $\beta$.
Then the claim ist that $U_1=(U_1\cap U_2)\rtimes U_\alpha$.
It is clear to me that $(U_1\cap U_2)$ and $U_\alpha$ generate $U_1$, as $U_1\cap U_2$ contains all root subgroups of $U_1$ except $U_\alpha$. But I don't see why $U_1\cap U_2$ is a normal subgroup of $U_1$.
One of my ideas was to show that $U_\alpha$ normalizes every other root subgroup or at least permutes them. But I can't find any reference on the interaction of different root subgroups.
Do you have any ideas?


text:
Q: Create a Download link with user input placed in the middle of link I wish to generate a download link button with user input replacing certain text in the link it's self.
http://linkhere/folder/foder/folder/InvoiceEnquiry.action?getPDF=&invoiceNumber=(User input result placed here)&criteria.invoiceType=INVOICE
Is this possible. I can use html code to get to the userinput but not to place the final part of the link after it prior to clicking the download button.
    HTML Codes online
Form Builder

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

    $('#button').click(function(e) {
        var inputvalue = $("#input").val();
        window.location.replace("First part of link"+inputvalue");

    });
});
</script>
</head>
<body>

       <input type="text" value="002" id="input">
       <button type="button" id="button">Click Me!</button>
</body>
</html>

Generated full download link with the users input and the extension of the link placed afterwards to have a complete download link

A: First off, you don't need JQuery for this. Vanilla JS would work fine. Just wrap the redirect in a function and call the function with the HTML "onclick" attribute on the button element. Then you can get rid of the JQuery script, unless something else needs it.
Secondly the replace() method takes two arguments. You're giving it one concatenated string (the + operator used in this way is for combining strings).
window.location.replace("(User input result placed here)", inputvalue");
That will work if (User input result placed here) doesn't change.


text:
Q: Possible to make partition key added on server side Azure Table Storage I noticed that Windows Azure Diagnostics uses a UTC ticks primary key as a method of making it easy to access entries by time ranges. I would like to implement a similar system for my table.
However a major issue is that the systems that will be doing the uploading will not necessarily have their time synced to the millisecond (not to mention ping time differences) so setting the Partition key locally and then uploading doesn't work well (I am having all kinds of race condition issues). Ideally I would like to guarantee that any time a table entry is made its partition key is certain to be greater than or equal to any partition key already in the table (since that's how time works).
The only way that I can think to ensure this guarantee is by having the "timestamp" partition key set server side. Is there some way to have this happen, such as via a server side script?
Note: I realize that a timestamp is added already for when an entry is made, but tables are not indexed by this timestamp.

A: I would recommend using twitter / snowflake solution for that purpose. I had very similar requirement and that approach worked perfectly for me.
I used Flake ID Generator. It is .net implementation based on twitter / snowflake.
The generator can be independently deployed to different Azure instances (or work as a independent service) - I was generating ids independently on each Azure service instance. Generated 64-bit ids are directly sortable and always unique (even if come from the different instances at the same time). You also have access to its source code so you can also add customizations if needed.
I hope that will help.


text:
Q: AR Configured AVD cannot run AR apps According to the Android Docs I should be able to run ARCore applications on the emulator. I've followed the instructions in the above link, but receive This device does not support AR.
Name: Pixel_2_API_28
CPU/ABI: Google APIs Intel Atom (x86)
Path: /Users/ashley/.android/avd/Pixel_2_API_28.avd
Target: google_apis [Google APIs] (API level 28)
Skin: pixel_2
SD Card: 512 MB
fastboot.chosenSnapshotFile:
runtime.network.speed: full
hw.accelerometer: yes
hw.device.name: pixel_2
hw.lcd.width: 1080
hw.initialOrientation: Portrait
image.androidVersion.api: 28
tag.id: google_apis
hw.mainKeys: no
hw.camera.front: emulated
avd.ini.displayname: Pixel 2 API 28
hw.gpu.mode: auto
hw.ramSize: 1536
PlayStore.enabled: false
fastboot.forceColdBoot: no
hw.cpu.ncore: 4
hw.keyboard: yes
hw.sensors.proximity: yes
hw.dPad: no
hw.lcd.height: 1920
vm.heapSize: 256
skin.dynamic: yes
hw.device.manufacturer: Google
hw.gps: yes
hw.audioInput: yes
image.sysdir.1: system-images/android-28/google_apis/x86/
showDeviceFrame: yes
hw.camera.back: virtualscene
AvdId: Pixel_2_API_28
hw.lcd.density: 420
hw.arc: false
hw.device.hash2: MD5:55acbc835978f326788ed66a5cd4c9a7
fastboot.forceChosenSnapshotBoot: no
fastboot.forceFastBoot: yes
hw.trackBall: no
hw.battery: yes
hw.sdCard: yes
tag.display: Google APIs
runtime.network.latency: none
disk.dataPartition.size: 800M
hw.sensors.orientation: yes
avd.ini.encoding: UTF-8
hw.gpu.enabled: yes

I'm developing on a 2018 13" MacBook Pro with Mojave as the OS. I don't know whether that has any bearing on the problem. How do I get ARCore to work in the virtual device?


text:
Q: Phantom SWT Button Images? I'm working on an old SWT (specifically, it's RCP) project and it has a virtual keyboard.  I added functionality to optionally have an image instead of a character.  When the button configuration is toggled from image back to button, it sometimes shows one of the other defined images AND the character.  I created a pop-up that reveals whether or not button.getImage() is null and when this phantom image is there, it is actually null, so the button seems to be constructed correctly, but is there some sort of dispose or redraw that I should be performing when switching back and forth between image and character?  Is there something else I'm doing wrong?
For control purposes, I created two buttons elsewhere in the application for testing and found that it still occurs:
testButton = new Button(buttonBar, SWT.PUSH);
testButton.setText("Test Button");
testButton.setEnabled(true);
testButton.addListener(SWT.MouseDown, new Listener() {
    public void handleEvent(Event event) {
        if (testButton.getImage() == null) {
            Image originalImage = new Image(Display.getDefault(), "EM-51.png");
            Image resizedImage = ImageUtils.resize(originalImage, 12, 12);
            testButton.setImage(resizedImage);
            originalImage.dispose();
            testButton.setText("");
        } else {
            testButton.setImage(null);
            testButton.setText("Test Button");
        }
    }
});
testButton1 = new Button(buttonBar, SWT.PUSH);
testButton1.setText("Test Button 1");
testButton1.setEnabled(true);
testButton1.addListener(SWT.MouseDown, new Listener() {
    public void handleEvent(Event event) {
        if (testButton1.getImage() == null) {
            Image originalImage = new Image(Display.getDefault(), "EM-52.png");
            Image resizedImage = ImageUtils.resize(originalImage, 12, 12);
            testButton1.setImage(resizedImage);
            originalImage.dispose();
            testButton1.setText("");
        } else {
            testButton1.setImage(null);
            testButton1.setText("Test Button 1");
        }
    }
});

This is in Win7, Java 8_131, Eclipse Neon.
Here's an example of what I see.  The phantom image is behind the text in the right button.

A: I got your problem Chris. What you are doing is that you are creating image each time you click on button.
Solution:

*

*Create Image somewhere else, may be in constructor and reuse the
same image. your code should not create image object at runtime,
because creating image object is a heavy operation.

Code snippet: https://github.com/skumbha/testrepo/blob/master/TestDialog2.java
Optional:

*Use testButton1.addSelectionListener(new SelectionAdapter() {}); instead of mouse down listener for buttons.( you will see lots of examples over net)

*Use Jface Image registry to create image.

*Looks like you are using JfaceDialog's "buttonbar", instead you can override createButtonsForButtonBar() method to create button in "buttonbar" and override buttonPressed()  method to add listeners for those buttons.

Code snippet: https://github.com/skumbha/testrepo/blob/master/TestDialog.java
You will get plenty of examples over net for each step.

A: No matter what I did, nothing would fix the phantom buttons.  I eventually gave up and was going to come back and worry about it later and it magically fixed itself a few weeks later.  I am guessing that it was a bug related to the graphics driver and how SWT was using it.  Java was updated and the drivers were updated during that period and no more phantoms.
Not the best way to resolve a problem, but I'll take it
¯\_(ツ)_/¯


text:
Q: QT UI-Design custom load Bar I would like to create a custom Widget (Loading Bar) Which has the shape of a half Donut, what is the way of creating custom Widgets? In css i would animate the position of an inked bar and use the donut as an alpha mask.
Any tips doing that in Qt?


text:
Q: backup command issue from linux server using ssh I am mewbie for ssh and mysql commanding.
I have a issue with taking backup from one linux server to another linux server using passwordless authentication. I already generated the key for passwordless authentication and upload it to another server.
I have used this command
[user1@server1 ~]$ mysqldump -u dbuser -p"dbpwd" --opt  dbname | gzip -c | ssh  -o StrictHostKeyChecking=no -o UserKnownHostsFile=/...../known_hosts -l deploy -i  /...../id_rsa -v  user2@server2  "/bin/cat > user2@server2:/......./test.sql.gz" 2>&1

Now when I run the command in SSH, I got the below error
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
Credentials cache file '/tmp/krb5cc_20082' not found

debug1: Unspecified GSS failure.  Minor code may provide more information
Credentials cache file '/tmp/krb5cc_20082' not found

debug1: Unspecified GSS failure.  Minor code may provide more information

debug1: Unspecified GSS failure.  Minor code may provide more information

debug1: Next authentication method: publickey
debug1: Offering public key: /home/indus33/.ssh/id_rsa

I have googled a lot but no solution helped me.
If anyone have query about this frequenkly ask me.
please help me to solve this issue.
updated
I run the command
[user@server1 ~]$ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/..../known_hosts -l deploy -i /..../id_rsa -v user2@server2
error
OpenSSH_5.3p1, OpenSSL 1.0.0-fips 29 Mar 2010
debug1: Reading configuration data /.../ssh_config
debug1: Applying options for *
debug1: Connecting to server2IP [server2IP] port 22.
debug1: Connection established.
debug1: identity file /......./id_rsa type 1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3
debug1: match: OpenSSH_5.3 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.3
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'server2IP' is known and matches the RSA host key.
debug1: Found key in /......./known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
Credentials cache file '/tmp/krb5cc_20082' not found

debug1: Unspecified GSS failure.  Minor code may provide more information
Credentials cache file '/tmp/krb5cc_20082' not found

debug1: Unspecified GSS failure.  Minor code may provide more information

debug1: Unspecified GSS failure.  Minor code may provide more information

debug1: Next authentication method: publickey
debug1: Offering public key: /....../id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
Last login: Mon Sep 30 03:25:52 2013 from server1
user2@server2 [~]#

hope the issue will be clear for all.....

A: The best way to first create a authorized_keys at server2
 touch /root/.ssh/authorized_keys
 chmod 600 /root/.ssh/authorized_keys

Then copy content of id_rsa.pub to the server to
[user1@server1 ~]$ cat ~/.ssh/id_rsa.pub | ssh user2@server2 "cat >> ~/.ssh/authorized_keys"

Then issue the below mysqldump command on server1
[user1@server1 ~]$ mysqldump -u dbuser -p"dbpwd" --opt  dbname | gzip -c | ssh user2@server2 "/bin/cat > /your_path/test.sql.gz" 2>&


text:
Q: Reading a CSV file and doing an action i have a csv file that gets populated with 3 lines a day. As the day starts it has none, then 1, 2, and 3. I want my code to go through the lines and do an action based if there is something written to the line or not regardless of whats there. The issue im having is that it will read line 1 & 3 and execute just fine, but not line 2.
CSV NAME - User1.csv
CSV EXAMPLE:
Line 1
Line 2
Line 3

My Code:
import csv
import itertools
while 1:
    z = 'User1.csv'
    RUN1 = False
    RUN2 = False
    with open(z, 'r') as f:
        Line = csv.reader(f)
        for Line in itertools.islice(f, 1, 2):
            print('newline2')
            RUN1 = True
        if RUN1 == False:
            for Line in itertools.islice(f, 0, 1):
                print('newline1')
                RUN2 = True
            if RUN2 == False:
                print('newline0')
    break

I will also accept complete rewrites to the code if you could give a brief explanation as to why you wrote it this way so i can better learn python.
SOLVED! Thanks to a_guest comment.
Working code is:
import csv
import itertools
while 1:
    z = 'User1.csv'
    RUN1 = False
    RUN2 = False
    with open(z, 'r') as f:
        Line = csv.reader(f)
        for Line in itertools.islice(f, 1, 2):
            print('newline2')
            RUN1 = True
        if RUN1 == False:
            with open(z, 'r') as f:
                for Line in itertools.islice(f, 0, 1):
                    print('newline1')
                    RUN2 = True
                if RUN2 == False:
                    print('newline0')
    break

As a_guest said you have to reset the file pointer which i did with adding again with open(z, 'r') as f: and that has fixed it. Feel free to keep posting to this question with other methods to help others with very similar problems.


text:
Q: Clunky calculation of differences between an incrementing set of numbers, is there a more beautiful way? The following code works just fine. But it seems so verbose, surely there is a more elegant way to calculate this?
The idea is that I have a list of 100 incrementing timestamps, I want to look at those timestamps and calculate the mean time between each time-stamp.
The code below functions, but I'm sure it's really inefficient to be reversing lists like this.
Any suggestions?
#!/usr/bin/python

nums = [1,4,6,10]
print nums
nums_orig = list(nums)

nums_orig.pop()
nums.reverse()
nums.pop()
nums.reverse()

print nums
print nums_orig

total = 0

for idx, val in enumerate(nums):
  difference = val - nums_orig[idx]
  total += difference
  print idx, val - nums_orig[idx]

print "Mean difference is %d" % (total / len(nums))

A: If you have numpy:
>>> import numpy as np
>>> np.diff([1,4,6,10]).mean()
3.0

A: What you are looking for is
>>> nums = [1,4,6,10]
>>> [x-y for x,y in zip(nums[1:],nums)]
[3, 2, 4]
>>> delta=[x-y for x,y in zip(nums[1:],nums)]
>>> float(sum(delta))/len(delta)
3.0

Solution with using Starmap
>>> from itertools import starmap
>>> from operator import sub
>>> sum(starmap(sub,zip(nums[1:],nums)))/float(len(nums)-1)
3.0

A:
The idea is that I have a list of 100 incrementing timestamps, I want to look at those timestamps and calculate the mean time between each time-stamp.

Since they are increasing, the sum of the differences is simply the difference between the first and last. The number of differences, meanwhile, is simply 1 less than the number of values.
So no looping is needed. Just:
(nums[-1] - nums[0])/(len(nums) - 1)


text:
Q: prove that $\operatorname{lcm}(n,m) = nm/\gcd(n,m)$ I'm trying to prove that $\operatorname{lcm}(n,m) = nm/\gcd(n,m)$
I showed that both $n,m$ divides $nm/\gcd(n,m)$
but I can't prove that it is the smallest number.
Any help will be appreciated.

A: Hint: For any $a,b$ real numbers: $\min(a,b)+\max(a,b)=a+b$.
Now, if we have $a=a_1^{p_1} a_2^{p_2}\ldots$ and similarly with $b$, if you use the equation I just mentioned for all $p_i$, you will get, that $\gcd(a,b)\cdot\operatorname{lcm}(a,b)=ab$.

A: Hint $\,\ n,m\mid j \!\iff\! nm\mid nj,mj\!$ $\overset{\ \rm\color{darkorange}U}\iff\! nm\mid (nj,mj) \overset{\ \rm \color{#0a0}D_{\phantom |}}= (n,m)j\!$ $\iff\! nm/(n,m)\mid j$
where above we have applied $\,\rm \color{darkorange}U = $ GCD Universal Property and $\,\rm\color{#0a0} D =$ GCD Distributive Law.
Remark $ $ If we bring to the fore implicit $\rm\color{#0a0}{cofactor\  reflection}$ symmetry we obtain a simpler proof: $ $ it is easy to show  $\,d\,\color{#0a0}\mapsto\, mn/d\,$ bijects common divisors of $\,m,n\,$ with common multiples $\le mn.$ Being order-$\rm\color{#c00}{reversing}$, it maps the $\rm\color{#c00}{Greatest}$ common divisor to the $\rm\color{#c00}{Least}$ common multiple, i.e. $\,{\rm\color{#c00}{G}CD}(m,n)\,\color{#0a0}\mapsto\, mn/{\rm GCD}(m,n) = {\rm \color{#c00}{L }CM}(m,n).\,$
See here and here more on this $\:\!\rm\color{#0a0}{involution\ (reflection)}$ symmetry at the heart of gcd, lcm duality.

A: Here is one way without using the Fundmental theorem of arithmetic just using the definitions
The definition of lcm(a,b) is as follows:
t is the lowest common multiple of a and b if it satisfies the following:
i)a | t and b | t
ii)If a | c and b | c, then t | c.
Similiarly for the gcd(a,b).
Here is my proof:
Case I: gcd(a,b) $\neq$ 1
Suppose gcd(a,b) = d.
Then $ab = dq_1b = dbq_1  = d*(dq_1q_2)$
Claim: $lcm(a,b) = dq_1q_2$
$a = dq_1$ | $dq_1q_2$
$b = dq_2$ | $dq_2q_1$.
Supppose lcm(a,b) = c.
Hence c $\leq$ $dq_1q_2$ .
To get the other inequality we have $dq_1$ | a and $dq_2$ | b. Hence $dq_1$ $\leq$ a $\leq$ c $\leq$ $dq_1q_2$  similiarly for $dq_2$.
Suppose that c is strictly less than $dq_1q_2$, so we have $dq_1q_2$ < $cq_2$ and $dq_1q_2$ < $cq_1$.
So $dq_1q_2$ < c < $cq_2$ < $dq_2^2q_1$ and $dq_1q_2$ < c < $cq_2$ < $dq_1^2q_2$, but $dq_1^2q_2$ > $dq_1q_2$ so c < $dq_1q_2$ and
c > $dq_1q_2$ contradiction. Hence c = d$q_1q_2$
Notice that the case where gcd(a,b) = 1 we can just set $q_1 = a$ and $q_2$ = b, and the proof will be the same.

A: Let's just do this directly. Let $g = \gcd(m,n)$. We need to prove that
$\operatorname{lcm}(m,n) = \dfrac{mn}{g}$.

STEP $0$. (Preliminary stuff.)
DEFINITION $1$. $L = \operatorname{lcm}(m,n)$ if and only if
 1. L is a multiple of m and of n.
 2. If C is a multiple of m and of n, then C is a multiple of L.

LEMMA $2$. If $\gcd(a,b) = 1$ and $a \mid bc$, then $a \mid c$.
PROOF. If $\gcd(a,b) = 1$, then there exists integers $A$ and $B$ such that
$aA + bB = 1$. It follows that $acA + bcB = c$. Since $a | acA$ and $a \mid bcB$, then $a \mid c$.

STEP $1$. $\dfrac{mn}{g}$ is a common multiple of $m$ and of $n$.
This is true because $\dfrac m g$ and $\dfrac n g$ are integers and
$\dfrac{mn}{g} = \dfrac{m}{g}n = m \dfrac{n}{g}$.

STEP $2$. If $G$ is a common multiple of $m$ and of $n$, then $G$
is a multiple of  $\dfrac{mn}{g}$.
Suppose $G = mM = nN$ for some integers $M$ and $N$. Then
$\dfrac G g = \dfrac m g M = \dfrac n g N$.
Since $\gcd\left( \dfrac m g, \dfrac n g \right) = 1$, and
$\dfrac m g M = \dfrac n g N$, then, by LEMMA $2$, $\dfrac m g \mid N$, say
$N = \dfrac m g N'$ for some integer $N'$.
So $\dfrac{G}{g} = \dfrac{n}{g} N = \dfrac{m}{g} \dfrac{n}{g} N'$. It follows that $G = \dfrac{mn}{g} N'$ and so $G$ is a multiple of $\dfrac{mn}{g}$.

From STEP $1$, STEP $2$, and DEFINITION $0$, we can conclude that
$\operatorname{lcm}(m,n) = \dfrac{mn}{\gcd(m,n)}$.


text:
Q: Min length for text area in my form I need to set a min length and a max length for my text area box on my website. I know for max i can do it in html, but min you cannot. Could someone help me with this? I can do if, else statements but that would be after the form is submitted. I want it to tell the user the length is too short before he/she even submits it. I think jquery would be the best but really unsure.
Code listed below.
        <!DOCTYPE HTML>

<link type="text/css" rel="stylesheet" href="index.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

<link rel="stylesheet" href="/resources/demos/style.css" />

 Daily Dorm News
 The best place to get your latest Dorm news

<form action="posting_wall.php" method="get">

Username:<input type="text" name="name" pattern="[A-Za-z0-9]{3,15}" title="Letters and numbers only, length 3 to 15" required autofocus>

E-mail: <input type="email" name="email" maxlength="20" required>

Post:

<textarea rows="15" cols="50" name='message' required></textarea>

Date this event took place: <input type="text" name='date' id="datepicker" required>

<input type="reset" value="Reset">
<input type="submit">

</form>

A: Set min-length
pattern=".{5,}"  --> 5 characters minimum

set both min-length and max-length
pattern=".{5,100}"  --> 5 characters minimum and 100 maximum .

Example
<input type="text" name="test" pattern=".{20,100}" required >

to support Html5 in every browser use html5shiv

Updated after OP's comment

$('#myform').submit(function(e){
    if($('#message').val().length < 3){
       e.preventdefault();
    }
});

A: Note that your HTML misses . That said, the "pattern" attribute seems to work :
<input type="text" required="required" pattern="^[A-Za-z0-9]{3,15}$" />

Here is another way of doing this  using Javascript. Just put this code into the  section, right after $("#datepicker").datepicker(); :
$('form').submit(function (e) {
    var nameValue = $('[name="name"]').val();
    if (!/^[A-Za-z0-9]{3,15}$/.test(nameValue)) {
        alert('failure');
        e.preventDefault(); // prevents from submitting
    }
});

Here is a demo combining both solutions : http://jsfiddle.net/wared/KbxM8/.
See also : http://api.jquery.com/submit/

I've tried something according to your comments :
$('form').submit(function (e) {
    var value;

    // "message" pattern : from 3 to 15 alphanumerical chars

    value = $('[name="message"]').val();
    if (!/^[A-Za-z0-9]{3,15}$/.test(value.replace(/\n/g, ''))) {
        alert('Wrong value for "message".');
        e.preventDefault();
        return;
    }

    // "name" pattern : at least 1 digit

    value = $('[name="name"]').val();
    if (!/\d+/.test(value)) {
        alert('Wrong value for "name".');
        e.preventDefault();
        return;
    }
});


text:
Q: wso2 is custom adaptive function not able to set claim I am using wso2 IS 5.10, for adding custom claim which needs to be added by fetching from db I am using custom adaptive function. But the below code is not working.
package org.wso2.custom.auth.functions;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticatedUser;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticationContext;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import org.wso2.custom.auth.functions.internal.CustomAuthFuncComponent;
import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.*;

public class SetForceAuthFunctionImpl implements SetForceAuthFunction {

    private static final Log LOGGER = LogFactory.getLog(SetForceAuthFunctionImpl.class);

    @Override
    public JsAuthenticatedUser setForceAuth(JsAuthenticationContext context, boolean forceAuth) {

        AuthenticatedUser lastAuthenticatedUser = context.getContext().getLastAuthenticatedUser();

        LOGGER.info("lastAuthenticatedUser****:::::::::::"+lastAuthenticatedUser);
        String userName = lastAuthenticatedUser.getUserName();
        LOGGER.info("userName2****:::::::::::"+userName);

        String tenantDomain = MultitenantUtils.getTenantDomain(userName);
        String fullyQualifiedUserName=("USERS"+"/"+userName+"@"+tenantDomain);
        Map<org.wso2.carbon.identity.application.common.model.ClaimMapping, String> claims = new HashMap<org.wso2.carbon.identity.application.common.model.ClaimMapping, String>();
        claims.put(org.wso2.carbon.identity.application.common.model.ClaimMapping.build("test123", "test123", null, true), org.apache.commons.lang3.StringUtils.join("*******************",",,,"));

        AuthenticatedUser authenticatedUserObj = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(MultitenantUtils.getTenantAwareUsername
                (fullyQualifiedUserName));
        authenticatedUserObj.setAuthenticatedSubjectIdentifier(MultitenantUtils.getTenantAwareUsername
                (fullyQualifiedUserName));
        authenticatedUserObj.setUserAttributes(claims);
        authenticatedUserObj.setUserName(MultitenantUtils.getTenantAwareUsername
                (fullyQualifiedUserName));

        return new JsAuthenticatedUser(authenticatedUserObj);
    }
}

package org.wso2.custom.auth.functions.internal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.wso2.carbon.identity.application.authentication.framework.JsFunctionRegistry;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.custom.auth.functions.GenerateHashFunction;
import org.wso2.custom.auth.functions.GenerateHashFunctionImpl;
import org.wso2.custom.auth.functions.GetClaimsForUsernameFunction;
import org.wso2.custom.auth.functions.GetClaimsForUsernameFunctionImpl;
import org.wso2.custom.auth.functions.GetUsernameFromContextFunction;
import org.wso2.custom.auth.functions.GetUsernameFromContextFunctionImpl;
import org.wso2.custom.auth.functions.SetForceAuthFunction;
import org.wso2.custom.auth.functions.SetForceAuthFunctionImpl;

@Component(
        name = "custom.auth.functions.component",
        immediate = true
)
public class CustomAuthFuncComponent {

    private static final Log LOG = LogFactory.getLog(CustomAuthFuncComponent.class);
    private static JsFunctionRegistry jsFunctionRegistry;

    @Activate
    protected void activate(ComponentContext ctxt) {

        SetForceAuthFunction setForceAuthFunctionImpl = new SetForceAuthFunctionImpl();
        jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "setForceAuth",
                setForceAuthFunctionImpl);

        GetUsernameFromContextFunction getUsernameFromContextFunctionImpl = new GetUsernameFromContextFunctionImpl();
        jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getUsernameFromContext",
                getUsernameFromContextFunctionImpl);

        GetClaimsForUsernameFunction getClaimsForUsernameFunctionImpl = new GetClaimsForUsernameFunctionImpl();
        jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getClaimsForUsername",
                getClaimsForUsernameFunctionImpl);

        GenerateHashFunction generateHashFunctionImpl = new GenerateHashFunctionImpl();
        jsFunctionRegistry.register(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "generateHash",
                generateHashFunctionImpl);
    }

    @Deactivate
    protected void deactivate(ComponentContext ctxt) {

        if (jsFunctionRegistry != null) {
            jsFunctionRegistry.deRegister(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "setForceAuth");
            jsFunctionRegistry.deRegister(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getUsernameFromContext");
            jsFunctionRegistry.deRegister(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "getClaimsForUsername");
            jsFunctionRegistry.deRegister(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER, "generateHash");
        }
    }

    @Reference(
            name = "user.realmservice.default",
            service = RealmService.class,
            cardinality = ReferenceCardinality.MANDATORY,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "unsetRealmService"
    )
    protected void setRealmService(RealmService realmService) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("RealmService is set in the custom conditional authentication user functions bundle");
        }
        CustomAuthFuncHolder.getInstance().setRealmService(realmService);
    }

    protected void unsetRealmService(RealmService realmService) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("RealmService is unset in the custom conditional authentication user functions bundle");
        }
        CustomAuthFuncHolder.getInstance().setRealmService(null);
    }

    @Reference(
            name = "registry.service",
            service = RegistryService.class,
            cardinality = ReferenceCardinality.MANDATORY,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "unsetRegistryService"
    )
    protected void setRegistryService(RegistryService registryService) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("RegistryService is set in the custom conditional authentication user functions bundle");
        }
        CustomAuthFuncHolder.getInstance().setRegistryService(registryService);
    }

    protected void unsetRegistryService(RegistryService registryService) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("RegistryService is unset in the custom conditional authentication user functions bundle");
        }
        CustomAuthFuncHolder.getInstance().setRegistryService(null);
    }

    @Reference(
            service = JsFunctionRegistry.class,
            cardinality = ReferenceCardinality.MANDATORY,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "unsetJsFunctionRegistry"
    )
    public void setJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) {

        this.jsFunctionRegistry = jsFunctionRegistry;
    }

    public void unsetJsFunctionRegistry(JsFunctionRegistry jsFunctionRegistry) {

        this.jsFunctionRegistry = null;
    }
}

But when I am using setForceAuth(context, true); in adaptive authentication function to add custom claims its not working but working in custom authenticator.
Adaptive authentication script:
function onLoginRequest(context) {
    doLogin(context);
}

function doLogin(context) {
  executeStep(1,{
        onSuccess: function (context) {
        },
        onFail: function(context){
           executeStep(4,{
                onSuccess: function (context) {
                    var subject = context.currentKnownSubject;
                    setForceAuth(context, true);

            },
                onFail: function(context){
                }
            });

        }
    });
}

A: The issue is that
setForceAuth(context, true);
executes the below code block
return new JsAuthenticatedUser(authenticatedUserObj);
There is no point in your code (authencation script or the java function) where the newly created JsAuthenticatedUser is set to the context.
What you need to do is to change the script like this
onSuccess: function (context) { context.currentKnownSubject = setForceAuth(context, true);}
or
the java function as below
`@Override
public JsAuthenticatedUser setForceAuth(JsAuthenticationContext context, boolean forceAuth) {
    AuthenticatedUser lastAuthenticatedUser = context.getContext().getLastAuthenticatedUser();

    LOGGER.info("lastAuthenticatedUser****:::::::::::"+lastAuthenticatedUser);
    String userName = lastAuthenticatedUser.getUserName();
    LOGGER.info("userName2****:::::::::::"+userName);

    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    String fullyQualifiedUserName=("USERS"+"/"+userName+"@"+tenantDomain);
    Map<org.wso2.carbon.identity.application.common.model.ClaimMapping, String> claims = new HashMap<org.wso2.carbon.identity.application.common.model.ClaimMapping, String>();
    claims.put(org.wso2.carbon.identity.application.common.model.ClaimMapping.build("test123", "test123", null, true), org.apache.commons.lang3.StringUtils.join("*******************",",,,"));

    AuthenticatedUser authenticatedUserObj = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(MultitenantUtils.getTenantAwareUsername
            (fullyQualifiedUserName));
    authenticatedUserObj.setAuthenticatedSubjectIdentifier(MultitenantUtils.getTenantAwareUsername
            (fullyQualifiedUserName));
    authenticatedUserObj.setUserAttributes(claims);
    authenticatedUserObj.setUserName(MultitenantUtils.getTenantAwareUsername
            (fullyQualifiedUserName));

    context.getContext().setSubject(authenticatedUserObj);
}

Still it is not advisable to have a tenant aware user name on authentication scripts. Rather can you think of not using

setForceAuth()

function and use the provided user.localClaims[] instead?


text:
Q: Estimating the # of Principal components based on variance explained I am running PCA on a dataset with dimensions 1460(n) * 307(p). Upon running PCA, I obtain the below plot of variance explained and the number of components. I am trying to estimate the number of PCs to select for my training dataset.
Based on the plot below, It appears that around 75% of the variance is explained/captured by 50 PCs. So, selecting 50 PCs is a reasonable estimate.
How would you interpret the below plot and estimate # of PCs to select?
Thanks!


text:
Q: Remove character from string Given two strings string1 and string2, remove those characters from first string(string1) which are present in second string(string2). Both the strings are different and contain only lowercase characters.
NOTE: Size of  first string is always greater than the size of  second string( |string1| > |string2|).
class Solution {
  public:
    string removeChars(string string1, string string2) {
        // code here
        int i;
           int arr[26]={0},curr=0;
           for(i=0; i<string2.size(); i++){
               if((string2[i]-'a')!=-1){
                   arr[string1[i]-'a']=-1;
               }
           }
           for(i=0; i<string1.size(); i++){
               if(arr[string1[i]-'a']!=-1){
                   string1[curr]=string1[i];
                   curr++;
               }
               string1[curr]='\0';

           }

       return string1;
    }
};

For Input: computer cat
Your Output:
puterer
Expected Output:
ompuer


text:
Q: File Access denied in .NET I am  writing an application in c# which saves data to xml. When i reopen the application it says

Access to the path 'C:\ProgramData\Test\abc.xml' is denied.

Can any one pls help me to sort out this problem.
Is there any way to find why access is denied.

A: You're probably getting this error because you're running Vista or Win7 and you have UAC turned on.
C:\ProgramData requires admin priveledges to write to (but not read from).
I just found this out the hard way because I've been working on a program that was working fine on XP that used System.Environment.SpecialFolder.CommonApplicationData which in Vista refers to the above location and requires elevated privs to write to that directory.

A: It would be helpful to identify the exact cause if you present the code you are working with. Without that, my guess is that your application leaves handles to the Filestream open.
You should always dispose of unmanaged references using the dispose pattern (or using the using construct).

A: This is a common problem I've found with XML writer's in the past. If the Filestream being used isn't closed properly then the file will stay locked. I say this is a problem, mainly because I've noticed that for some reason the lock persists even after the application has been closed, but I've only seen it happen when I use an XML writer in this fashion (don't know why yet).
Basically, just use the "using" keyword to ensure that your writer is closed properly. The code should look something like this:
using(XmlWriter _myXmlWriter = XmlWriter.Create(outputStream, xmlWriterSettings))
{
     //Build XML here
}

A: use Unlocker to know which program is locking that file, and refactor the code if it is your application, you should close file after reading or writing


text:
Q: Styling forms generated with different plugins Premise: I'm doing an Internship right now, so I am not a pro.
Hey Developers, I need your help.
I inherited a work from another guy in which I have to re-style 3 contact forms.
Problem is: two forms are generated in Wordpress with Contact form 7, and the last one is done using Woocommerce.
What's the best way to proceed to make all three forms consistent?
Do I override the styles of the theme with my own styles?
Any better solution?
Thanks in advance.

A: The answer to this is to identify the common fields.
In most cases you can add styling to the input and input[type="X"] fields.
This will mean not only will these forms be consistent but everything else that a form will be consistent.
E.g.
input {
    background: #f1f1f1;
    padding: 5px;
}

input[type="submit"] {
    border-radius: 20px;
    background: #333;
    color: white;
}

This will style all the inputs and then also target the input with the type submit.
In most cases these stylings will be ignored due to weight of the styling so it may be necessary to nest these inside classes and divs. Or just use !important to overide them.
E.g
//Overiding with !important
input {
    background: #f1f1f1 !important;
    padding: 5px !important;
}

//Nesting to give extra value
html body .container form input[type="submit"] {
    border-radius: 20px;
    background: #333;
    color: white;
}

More information on weights given to classes/id's/elements here.
More information on input types here.


text:
Q: Saving temporary form information in global Javascript variables Is there any reason why I shouldn't do something like the following (to avoid using a hidden field to store the temporary information)? I'm using jQuery syntax for brevity but it's a general JavaScript question.
function editComments() {
    window.currentComments = $('#commentsTextBox').val();
    $('#commentsTextBox').removeAttr("readonly");
}

function cancelEditComments() {
    $('#commentsTextBox').val(window.currentComments);
    $('#commentsTextBox').attr("readonly", "readonly");
}

I know that globals are generally considered bad practice, but is there really any problem with doing the above?
Please don't answer/comment with "globals variables are evil" unless you can give a reason/explanation.

A: There's no real problem with this except that global variables are evil. ;)
However, if you are using jQuery anyway, in my opinion, a much nicer way is to store it in the element using data():
function editComments() {
    $('#commentsTextBox').data("oldValue", $('#commentsTextBox').val());
    $('#commentsTextBox').removeAttr("readonly", "readonly");
}

function cancelEditComments() {
var oldValue = $('#commentsTextBox').data("oldValue");
$('#commentsTextBox').val(oldValue );
$('#commentsTextBox').attr("readonly", "readonly");
}

As long as you keep it inside the script, and nothing else gets done with the element, that should work fine.

A: The problem with globals in javascript (on top of that of any other languages). Is that there is no mechanism to resolve name clashes (or rather, the mechanism is to just assume that it's the same variable).  If you use a global variable called currentComments and also include some other module with a currentComments global variable then one of them is going to lose, and you may get unpredictable results.
It would be better to use one that is scoped to your module, thus:
(function(){
    var currentComments;

    function editComments() {
        currentComments = $('#commentsTextBox').val();
        $('#commentsTextBox').removeAttr("readonly", "readonly");
    }

    function cancelEditComments() {
        $('#commentsTextBox').val(currentComments);
        $('#commentsTextBox').attr("readonly", "readonly");
    }
}());

A: There's no real reason not to do it, if you ignore the "global variables are bad" argument.
One thing you need to be aware of is you can't .delete properties from the window object in IE, it causes an exception to be thrown. In your case, since it's just a string, it probably doesn't matter.
This fails on IE:
window.foo = 'bar';
delete window.foo;


text:
Q: Android - Using AlarmManager or Timer on Service when fairly heavy task hight frequence periodic I'm newbie on android and really thank you for your attention.
My case is an app that have to check the gps every 10s (or 30s, not fixed yet) and compare to data saved on local db, after that, it maybe send gps to server and get response, save data to local db.
I think it's a fairly heavy job and excute hight frequence.
So could anyone tell me should choose service with timer or using alarmManager?
Thank you very much and have a nice day.


text:
Q: Use ASP.NET Core logging without using WebHost We have .NET Core applications that could benefit from ASP.NET Core logging (and service provider) but they're not using any WebHost or WebHostBuilder.
I'd like to peek inside extensions/methods like ConfigureLogging or UseStartup to get some inspiration on how to set-up my root configuration/service provider.
I thought ASP.NET Core was open-source, but somehow I lack the talent to find those sources. Where can I learn more about how all this is set up, and how I could use them in any console app, not just apps using WebHostBuilder?

A: The various components from ASP.NET Core are all usable separately. So you can absolutely use things like Microsoft.Extensions.Logging, or even other things like DependencyInjection, Configuration or Options separately without having to actually use ASP.NET Core or its WebHost.
I could point you to various locations in the sources now (e.g. the WebHostBuilder, the WebHost, or the default builder), but getting logging up and running in your own application is actually pretty simple, so you don't need to browse through all that.
Instead, just add a reference to Microsoft.Extensions.Logging and your favorite logging providers, e.g. Microsoft.Extensions.Logging.Console, and then set up a logger factory and create a logger:
var loggerFactory = new LoggerFactory();
loggerFactory.AddConsole();

var logger = loggerFactory.CreateLogger("categoryName");
logger.LogInformation("Whee!");

That is all you need to get logging working. Of course, you now need to create your own loggers and pass it to where you need it, but you have full control over it.
If you like, you can also add dependency injection to the mix by adding a reference to Microsoft.Extensions.DependencyInjection and creating a service collection:
var services = new ServiceCollection();

// add logging
services.AddLogging(loggerBuilder =>
{
    loggerBuilder.AddConsole();
});

// add your services
services.AddTransient<MyService>();

// create the service provider
var serviceProvider = services.BuildServiceProvider();

// request your service and do something
var service = serviceProvider.GetService<MyService>();
service.DoSomething();

public class MyService
{
    private readonly ILogger<MyService> _logger;
    public MyService(ILogger<MyService> logger)
    {
        _logger = logger;
    }

    public void DoSomething()
    {
        _logger.LogInformation("Did something!");
    }
}

And suddenly you have working dependency injection with logging in just a few lines. So you can set up your own environment for console applications, and then built upon those techniques for your application—without relying on actual ASP.NET Core stuff.

A: It is worth mentioning that since .NET Core 2.1, you can now use a HostBuilder for such projects. Works very well.


text:
Q: How get value of parameters in stacktrace I can get information about a parameter by StackTrace using something like this:
catch (Exception ex)
{
    var st = new StackTrace(ex);

    System.Reflection.ParameterInfo pi = st.GetFrame(0).GetMethod().GetParameters().First();
}

I want know how i get the value of parameter. Example:
If my method in stack trace was like:
void MyMethod(object value)

And the call was like:
MyMethod(10);

I want to get the value 10.
How i do that?

A: Not with C# except if you are creating a highly CLR (patch) version dependant solution. But what does work is to attach Windbg to your process, load sos.dll switch to your thread and type
!ClrStack -p

to show the managed call stack and the method parameters for most methods. This is even under the debugger not foolproof because due to inlining and JIT optimizations the stack layout is very flexible. Besides this some parameters might not even show up in the stack memory because they are passed via registers (which is even more common under the x64 platform).
To answer your first question. No it is not possible with the approach you are trying. A working solution would be possible but not at all portable. A managed debugger can partially retrieve your arguments but there is no 100% working solution (even under the debugger).

A: There are two ways.  The more powerful is the COM API for .NET Debugging.  For example, arguments and local variables of function in the call stack are both accessible from ICorDebugILFrame.  But this must be run from a separate process that is attached to your process as the debugger.
For in-process introspection, there's the Profiler API, which also can find information about function arguments.  Look at the information about "shadow stacks".


text:
Q: How to detect SSL pinning is being done in the app? I have already gone through this
How to detect SSL pinning on Android

A: If you setup SSL interception with tools like mitmproxy or Burp and then import the proxy CA of this interception proxy into the android certificate store as trusted then you should be able to intercept the connection, i.e. get the plain text. If instead the application fails and maybe throws out some error about failing SSL verification than this application is probably doing SSL pinning.


text:
Q: Остановка setInterval из прототипа Есть конструкция в ходе которой у объекта есть переменная interval и через методы в прототипе этой переменной задаётся setInterval и при нажатии на кнопку этот setInterval должен тормозиться, но этого почему-то не происходит.

class Timer{
  constructor(date){
    this.interval;
  }
  startCount() {
    this.interval = setInterval(()=> console.log('work'), 100);
  }
  stopCount() {
    clearInterval(this.interval);
  }
}

let timer = new Timer();
timer.startCount();

document.querySelector('button').onclick = timer.stopCount;
<button> stop </button>

A: Попробуйте так:

class Timer {
   constructor(date){
    this.interval;
  }
  startCount() {
    this.interval = setInterval(()=> console.log('work'), 300);
  }
  stopCount() {
    clearInterval(this.interval);
  }
}

var timer = new Timer();

document.querySelector('a').onclick = function(){
  timer.startCount();
}

document.querySelector('button').onclick = function(){
  timer.stopCount();
}
<a href="#"> start </a>
<button> stop </button>


text:
Q: Google Calendar API. Patching sharedExtendedProperty for events I have created event in my Google calendar. Most interesting part is:
{
// some event data;
 "extendedProperties": {
  "shared": {
   "cases_1": "1",
   "cases_2": "2"
  }
 }
}

Right now I need to PATCH existing event. In extendedProperties I do not need "cases_1":"1" any more. So I use developers endpoint to patch it. The PATCH request body is:
{
 "extendedProperties": {
  "shared": {
   "cases_2": "2"
  }
 }
}

In response I see my both shared fields. How must my request body look like to remove from extendedProperties shared cases_1 field?

A: Try adding the line below to your request:
{
 "extendedProperties": {
  "shared": {
   "cases_1": null,
   "cases_2": "2"
  }
 }
}

It was shown in this documentation:

Any properties not included in an update request will be deleted, but
   a better approach is to make a patch request to set the value to null

Hope this helps.


text: Q: How to add a dynamic listview layout inside a parent list view? I am new to android in my android layout i got listview inside a listview both the listviews should be repeat dynamically.here i have to acheive the curriculum fragment layout.In curriculum CREATION:making your idea center title is the parent list view and the bellow CREATION: audio and workbook is the sub listview.how can i achieve it.


text:
Q: Given the plaintext, ciphertext, and IV. Can I find a reused key? Hey all
I'm stuck on a part of an assignment for one of my programming classes.
I believe the solution is pretty straightforward, but for whatever reason I cannot grasp it.
The goal of the assignment is to modify the ciphertext so that the dollar amount is strictly increased. The classes encrypt and decrypt are given and cannot be edited, code is added to attack. Attack acts as a middleman and retrieves the output from encrypt before decrypt is called. Note that the key is retrieved from a reused file, ergo the same key is used for each encrypt and decrypt. Also we can assume we know the layout of the message.
My initial reaction was that because we know that the key is the same and because we have the plaintext, ciphertext, and IV in attack, there must be a simple solution to modifying the ciphertext. I've tried computing a new tag after modifying the ciphertext, but the ciphertext is dependent on previous input (IV) so that doesn't work. Am I right to assume there is a relatively simple solution?
Note: Not necessarily looking for a fully coded answer, just want some guidance in the approach to this problem. TA office hours was a mess with everything online :(
Thanks!

#### EXAMPLE KEY #####
2D7F8E92A8E7109258C879F878E12387
######################

class encrypt

import sys
import os
import Crypto.Cipher.AES
import hashlib

f = open(sys.argv[1], 'r')
key = f.readline()
key = bytes.fromhex(key[:32])
f.close()

message = \
"""AMOUNT: $  10.00
Originating Acc Holder: Doe
Orgininating Acc #82123-098370

I authorized the above amount to be transferred to the account #38108-443280
held by a student at the National Bank of the Cayman Islands.
"""

iv = os.urandom(16)
cipher = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, IV=iv)
ciphertext = cipher.encrypt(message.encode()).hex()
tag = hashlib.sha256(message.encode()).hexdigest()
print(iv.hex() + ciphertext + tag)

class decrypt

import sys
import Crypto.Cipher.AES
import hashlib

f = open(sys.argv[1], 'r')
key = f.readline()
key = bytes.fromhex(key[:32])
f.close()

ciphertextWithTag = bytes.fromhex(sys.argv[2]) # bytes.fromhex($CT)

if len(ciphertextWithTag) < 16+16+32:
  print("Ciphertext is too short!")
  sys.exit(0)

iv = ciphertextWithTag[:16]
ciphertext = ciphertextWithTag[:len(ciphertextWithTag)-32]  # with iv
tag = ciphertextWithTag[len(ciphertextWithTag)-32:]
cipher = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, IV=iv)
plaintext = cipher.decrypt(ciphertext[16:]) # here [16:] has spare apart iv

if tag.hex() != hashlib.sha256(plaintext).hexdigest():
   print("Invalid tag!")
else:
   print("Verified message")
   print(plaintext.decode())

class attack

import sys

ciphertextWithTag = bytes.fromhex(sys.argv[1])

if len(ciphertextWithTag) < 16+16+32:
  print("Ciphertext is too short!")
  sys.exit(0)

iv = ciphertextWithTag[:16]
ciphertext = ciphertextWithTag[:len(ciphertextWithTag)-32]
tag = ciphertextWithTag[len(ciphertextWithTag)-32:]

# TODO: Modify the input so the transfer amount is more lucrative to the recipient

# TODO: Print the new encrypted message
# you can change the print content if necessary
print(ciphertext.hex() + tag.hex())

A: Look at the very first block decrypted using CBC mode
   PlainText = Decrypt(CipherText, Key) ^ IV.

You know the PlainText you know the IV, and you have a new text FakeText that you want to create.  It should be pretty clear how to change IV to a new IV' so that you end up with FakeText instead of a PlainText.  You don't care what the results of the decryption are, just that it's some constant.
Beyond that, it's your homework.


text:
Q: How to dynamically assign name and href for anchor tag in xsl I have a requirement where the xml might have one or more services (name might be different), and I am having a content which should have all of these available services from the xml  something like below

CMS

DIS

but above I have hardcoded the a tag content and href since I know these are the values, but in real time I would not be knowing these names, so how to set href and anchor tag contents based on xml values?
So far I got the below for-each statement, which gets me all the service names from the xml
<xsl:variable name="number">
  <xsl:number/>
</xsl:variable>

<xsl:for-each select="csmclient/product/domainmetadata/domainmetadata_service">

<xsl:value-of select="@name"/><xsl:value-of select="position()"/>

</xsl:for-each>

.
.
.

<xsl:for-each select="domainmetadata/domainmetadata_service">

Service Name: <xsl:value-of select="@name"/>

    .
    .
    .
</xsl:for-each>

but it does not seem to work, it gives me all my services but the link does not work. Any other ideas?
Note: I took help from this question link which had a similar requirement.

A: There is a xslt function generate-id() which gives and unique textual identifier for any node in the xml.
http://www.w3.org/TR/xslt#function-generate-id

A: Use something like below, should work
<xsl:for-each select="csmclient/product/domainmetadata/domainmetadata_service">

<xsl:value-of select="@name"/>

</xsl:for-each>

<xsl:for-each select="domainmetadata/domainmetadata_service">

Service Name: <xsl:value-of select="@name"/>

</xsl:for-each>

A:

<xsl:value-of select="@name"/><xsl:value-of select="position()"/>

but it does not seem to work ...

What you are trying to write is this (not discussing at all if this uniquely identifies the node):


text:
Q: Python- how to return an index depending if there is an appearance in a list So i have functions which output a random 5 digits (dice variable) i then have another variable which has a count that displays a number depending on how many of that certain number were in 'dice' e.g.
dice= [1, 3, 1, 4, 6] so then totals= [2, 0, 1, 1, 0, 1] (because there is two 1's etc.)... my issue is that i need to make it that, If appearance is found in totals, the die's score associated with that value is returned. If not, -1 is returned.
def countSame(appearances, totals):
    for appearances in totals:
        if appearances == True:
            return totals
        else:
            return -1

i cant seem to get my head around how to return the score (sorry im new)

A: What you want is a Counter:
>>> from collections import Counter
>>> dice = [1, 3, 1, 4, 6]
>>> counts = Counter(dice)
>>> counts
Counter({1: 2, 3: 1, 4: 1, 6: 1})
>>> totals = [counts.get(i, 0) for i in xrange(1, 7)]
>>> totals
[2, 0, 1, 1, 0, 1]


text:
Q: Python KeyboardInterrupt not stopping loop Python 3.10 in macOS terminal
I kick off this simple script in macOS terminal, which runs infinitely (so please be warned when running it):
import itertools
for i in itertools.count(start=1):
    try:
        p = pow(2,i)
        print(p)
    except KeyboardInterrupt:
        print("Loop terminated")
        raise

Yet clicking on the keyboard does not terminate the loop.
What am I missing?

A: Thanks to everyone for the clarification.  The problem is I was under the assumption that KeyboardInterrupt would respond to any key pressed.  It actually only responds to Ctrl-C.  Everything works as expected when using Ctrl-C.


text:
Q: ActiveModelSerializer - serialize array object I have problems with ActiveModelSerializer.
Model test.rb:
class Test < ActiveModel::Serializer
  attr_accessor :id, :userName, :lista, :test2

  def initialize params = {}
    @lista = Array.new
    @test2 = Array.new
    params.each { |key, value| send "#{key}=", value }
  end
end

Model test2.rb:
class Test2 < ActiveModel::Serializer
  attr_accessor :id, :userName

  def initialize params = {}
    params.each { |key, value| send "#{key}=", value }
  end
end

test_serializer.rb:
class TestSerializer < ActiveModel::Serializer
  attributes :id, :userName, :lista
  attributes :test2

  public

  def test2
    Test2Serializer.new(object.test2).as_json
  end
end

test2_serializer.rb:
class Test2Serializer < ActiveModel::Serializer
  attributes :id, :userName
end

I get an error:
NoMethodError (undefined methodread_attribute_for_serialization' for #Array:0x00007f1bb52da460):

After debuggin the code I found out that the Exception is from this line:
object.read_attribute_for_serialization(attr)

In variable object is an array. I think it should be object. So I tried to change
Test2Serializer.new(object.test2).as_json

oto
json: object.test2, each_serializer: Test2Serializer

or:
object.test2, each_serializer: Test2Serializer

That didn't work. Can anyone help me?


text:
Q: C - Signal handlers and Kill() not working to communicate through 2 processes As an assignment I got at my university to send arguments to Server, then server needs to calculate and send the result back to the Client.
I need to make 2 .c files(client and server).
Then, compile them using gcc command(gcc client.c -o client.out) and run the server first, let it run in the background(CTRL+Z), get it's PID('ps' command) and then run the client with those arguments:

The code is written in C, and my workspace is Linux terminal using Putty.
The problem is that when I use the "kill" command in my client file(I called it "c.c") in order to send a signal to a specific process that I have it's PID(which is the server) , The handler of the server doesn't wake up and start working and of course because of that, it won't send a "kill" command back to the client with result.
Jokes aside, I literally sat 24 hours(I'm mean.. for real lol), and since it's 5am I really need to get some rest I'm starting to get delusional and I have less then 24 hours to submit the assignment :( .
Below I shared my code, I hope it's understandable, I tried to do my best guys.
Client.c:
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#define GODEL 100

char* reqArgs[5];

void sigterm_handler(int dummy)
{
    char msg[150];
    int clientPID, toClientFD, res, signalCharsR;
    pid_t pid;
    clientPID = getpid();

    char* toClientFileName = (char*)malloc(strlen("to_client_") + strlen(reqArgs[4]) + strlen(".txt") + 1);
    strcat(toClientFileName, "to_client_");
    strcat(toClientFileName, reqArgs[4]);
    strcat(toClientFileName, ".txt");

    // Open the result file(to_client_XXXXX) from Server
    toClientFD = open(toClientFileName, O_RDONLY, 0777);
    if(toClientFD == -1)
    {
        sprintf(msg, "Could not Open file: to_client_%d.txt\n", clientPID);
        write(2, msg, strlen(msg));
        exit(-1);
    }

    // Read the result from the results file(to_client_XXXXX)
    signalCharsR = read(toClientFD, msg, strlen(toClientFileName));
    if(signalCharsR == -1)
    {
        sprintf(msg, "Could not Read result from file: to_client_%d.txt\n", clientPID);
        write(2, msg, strlen(msg));
        exit(-1);
    }

    write(1, msg, sizeof(msg));

    signal(SIGTERM, sigterm_handler);

    exit(0);
}

int main(int argc, char* argv[])
{
    char msg[150];
    int logFD, reqFD, charsR = 0;
    pid_t pid;

    if(argc != 5)
    {
        strcpy(msg, "Wrong number of arguments\n");
        write(2, msg, strlen(msg));
        exit(-1);
    }

    signal(SIGTERM, sigterm_handler);

    for(int i = 0; i<argc; i++)
        reqArgs[i] = argv[i];

    // Open request.txt, Creates it if doesn't exist
    reqFD = open("request.txt", O_CREAT | O_RDONLY | O_WRONLY | O_APPEND, 0777);
    if(reqFD == -1)
    {
        strcpy(msg, "Could not Create and Open file: request.txt\n");
        write(2, msg, strlen(msg));
        exit(-1);
    }

    // Open cLog.txt file
    logFD = open("cLog.txt", O_CREAT | O_RDONLY | O_WRONLY | O_APPEND, 0777);
    if(logFD == -1)
    {
        strcpy(msg, "Could not Create and Open file: request.txt\n");
        write(2, msg, strlen(msg));
        exit(-1);
    }
    close(1);
    dup(logFD);
    close(logFD);

    // Writing into request.txt
    for(int i = 2; i<argc; i++)
    {
        charsR = write(reqFD, argv[i], strlen(argv[i]));
        if(charsR == -1)
        {
            strcpy(msg, "Could not write to file: request.txt\n");
            write(2, msg, strlen(msg));
            exit(-1);
        }
        write(reqFD, "\n", 1);
    }
    char mypid[5];
    sprintf(mypid, "%d", pid);
    write(reqFD, mypid, sizeof(mypid));
    close(reqFD);

    signal(SIGTERM, sigterm_handler);

    // Sending KILL to the Server
    if(kill(atoi(argv[1]), SIGTERM) == -1){
        write(2, "Could not send signal\n", strlen("Could not send
        signal\n"));
    }

    // Sleeping until Server sends back a result
    while(1){
        sleep(1);
    }

    exit(1);
}

Server:
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>

int calculator(int x, int y, int op)
{
    switch(op)
    {
        case 1:
            return x+y;
            break;
        case 2:
            return x-y;
            break;
        case 3:
            return x*y;
            break;
        case 4:
            if(y == 0)
                return -1;
            return x/y;
            break;
        default:
            return -1;
    }
    return -1;
}

void sigterm_handler(int dummy)
{
    char msg[150];
    pid_t pid;

    // Forking
    pid = fork();
    if(pid < 0)
    {
        //printf("EX2_FROM_ERROR\n");
        strcpy(msg, "Could not Fork\n");
        write(2, msg, strlen(msg));
        printf("Could not Fork\n");
        exit(-1);
    }
    else
    {
        // Son
        if(pid == 0)
        {
            int logFD, fd, bytesRead, x, y, op, res;
            char ch;
            char* reqArgs[4];

             // Open request.txt file
            fd = open("request.txt", O_RDONLY, 0777);
            if(fd == -1)
            {
                strcpy(msg, "Could not open file: request.txt\n");
                write(2, msg, strlen(msg));
                exit(-1);
            }

            //  Reading lines from request.txt file;
            for(int i = 0; i < 4; i++) {
                int j = 0;
                bytesRead = read(fd, &ch, 1);

                    while(ch != '\n' && bytesRead != 0) {
                    reqArgs[i][j] = ch;
                    bytesRead = read(fd, &ch, 1);
                    j++;
                }
                reqArgs[i][j] = '\0'; // put null at the end
            }
            close(fd);  // Close request.txt File

            // Initialize the data into variables
            x = atoi(reqArgs[0]);
            op = atoi(reqArgs[1]);
            y = atoi(reqArgs[2]);
            printf("%d+%d+%d=", x, op, y);

            // Creating result file to send to the client
            char* toClientFileName = (char*)malloc(strlen("to_client_") + strlen(reqArgs[3]) + strlen(".txt") + 1);
            strcat(toClientFileName, "to_client_");
            strcat(toClientFileName, reqArgs[3]);
            strcat(toClientFileName, ".txt");

            fd = open(toClientFileName, O_CREAT | O_RDWR | O_APPEND, 0777);
            if(fd == -1)
            {
                sprintf(msg, "Could not Create and Open file: %s\n", toClientFileName);
                write(2, msg, strlen(msg));
                //printf("Could not Create and Open file: %s\n", toClientFileName);
                exit(-1);
            }

            // Calling the calc() function
            res = calculator(x, y, op);
            if(res =! -1)
                write(fd, &res, sizeof(res));
            else
                write(fd, "Calculate went wrong\n", strlen("Calculate went wrong")+1);

            close(fd);
            signal(SIGTERM, sigterm_handler);

            char test[5];
            sprintf(test, "%d", atoi(reqArgs[3]));
            // Sending KILL back to the Client
            if(kill(atoi(test), SIGTERM) == -1){
                 write(2, "Could not send signal\n", strlen("Could not send
                 signal\n"));
            }
        }
        // Father
        else
        {

        }
    }
    signal(SIGTERM, sigterm_handler);
}

int main(int argc, char* argv[])
{
    signal(SIGTERM, sigterm_handler);

    while(1){
        sleep(10);
    }

    exit(1);
}

A: ctrl-z merely stops the forground process. It does not send it to the background. You need to resume the process as background process using bg $n where n is the job number shown in brackets after you stopped the server, [1] as seen in your terminal screenshot:
bg $1