text:
Q: Connecting to .aspx site from c# application I'm trying to build c# application, which notify me when there is an "update" in site.
The site login form contains 3 textboxes, and it's login.aspx.
My question is, how can I "send" the 3 details to the site and connect(authenticate) from the application I want to build in c#, and if it's possible, how can I do it?
I looked for any guide or something to read about this but haven't found.

A: you need to use the WebClient class. More info on this class can be found at http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx
And a nice example at http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-4

A: First you need post a form using c#
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            Console.WriteLine ("Content length is {0}", response.ContentLength);
            Console.WriteLine ("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format.
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            Console.WriteLine ("Response stream received.");
            Console.WriteLine (readStream.ReadToEnd ());
            response.Close ();
            readStream.Close ();

then try to save cookie, its required to store aspnet_session_id into client for future requests
private class CookieAwareWebClient : WebClient
{
    public CookieAwareWebClient()
        : this(new CookieContainer())
    { }
    public CookieAwareWebClient(CookieContainer c)
    {
        this.CookieContainer = c;
    }
    public CookieContainer CookieContainer { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = this.CookieContainer;
        }
        return request;
    }
}

ensure you send the and restore aspnet_session_id on each request.
And bingo!!
I recommend you to read this.


text:
Q: Passing JSON payload over the command line I am trying to pass JSON Payload vai command line to node.js to execute the code. Its seems, Command line does not treat JSON Object as single string.
Here is the code: I have tried both Encoded and decoded JSON object but still no luck. How Can I decode JSON back to original in node js program.
var account_id= "109443356002";
var change_request= "chg0123456";

//Request Body Output: {"account_id":"109443356002","change_request":"chg0123456"}

//Decoded Outout: "{\"account_id\":\"109443356002\",\"change_request\":\"chg0123456\"}"

var command = C:\Users\kp250041\desktop\myfiles decoded

var requestBody = {};
requestBody.change_request = change_request+'';
requestBody.customer_id = customer_id+;

requestBody1 = JSON.stringify(new global.JSON().encode(requestBody));
var decoded = new global.JSON().decode(requestBody1);

A: Provided you pass actual valid JSON to the command line and quote it correctly, you can parse the value with the JSON.parse:

The JSON.parse() method parses a JSON string, constructing the
  JavaScript value or object described by the string. An optional
  reviver function can be provided to perform a transformation on the
  resulting object before it is returned.

Example:
data = JSON.parse(process.argv[2] || '{}')
console.log(data)

Then call it:
node test.js '{"account_id":"109443356002","change_request":"chg0123456"}'

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can unmanaged C++ use a resx file? Using Visual Studio, I can add a .resx resources file to the unmanaged Visual C++ project. But how can I use it?
It compiles fine, but no resource headers are generated that can be included in source. For the classical RC files, there are headers with resource IDs.
I want to use resx files to have a shared resources, like strings and icons, between managed and unmanaged libraries. The idea was to include the same resx file in both projects.

A: You can't.  The tooling is missing to translate them from their .resx format to binary .resource files and embed them in the managed assembly manifest.  Necessarily so, native C++ projects don't create an assembly.
Use a .rc file instead.  Well supported by the C++ IDE, if you don't have one yet then use Project + Add New Item, Resource node, "Resource File (.rc)" template.  Double-click the added item to open the resource editor.  Load resources at runtime with winapi functions, like LoadString, LoadIcon, etc.  If you need to share them with managed code then that code will need to pinvoke those same functions.  You might consider duplicating them to avoid that.  It doesn't otherwise make a lot of sense to require sharing.


text:
Q: Как раскодировать xml в кодировке 1251 Выдает ошибку:

System.Xml.XmlException: "System does not support 'windows-1251' encoding.

Как раскодировать?
string URLXml = "http://сайт.ru/file.xml";

XmlReaderSettings settings = new XmlReaderSettings();
XmlReader reader = XmlReader.Create(URLXml);

while (reader.Read())
{}

A: В отличие от обычного .NET Framework, в котором изначально поддерживается большое количество кодировок, в .NET Core по умолчанию доступны лишь несколько базовых.
Вся информация описана в документации: CodePagesEncodingProvider.

*

*Добавьте в проект ссылку на сборку System.Text.Encoding.CodePages.dll.

*Получите объект CodePagesEncodingProvider из статического свойства CodePagesEncodingProvider.Instance.

*Передайте объект CodePagesEncodingProvider методу Encoding.RegisterProvider.
Фактически, в код нужно добавить одну строку:
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

A: Encoding encoding = Encoding.GetEncoding("windows-1251");

A: Вы можете попробовать LINQ to XML API.

c#

void Main()
{
    const string Url = @"http://сайт.ru/file.xml";

    XDocument doc = XDocument.Load(Url);
}


text:
Q: Using Linq to convert KeyValue pairs into Newtonsoft.Json.Linq.JObject I am trying to use C# LINQ to build a JObject.  I know that I can use a loop, such as,
var jobj = new JObject();
foreach (var field in fieldList)
{
    jobj[field.Name] = new JValue(field.Value);
}

Is it possible to replace the loop with LINQ?  I tried this,
var data = fieldList.Select(field => new KeyValuePair<string, JValue>(field.Name, new JValue(field.Value)));
var jobj = new JObject(data);

but it fails with this error:
Could not determine JSON object type for type System.Collections.Generic.KeyValuePair`2[
     System.String,Newtonsoft.Json.Linq.JValue].

A: Well, I don't know if it's any prettier, but you could use Aggregate:
fieldList.Aggregate(new JObject(), (obj, next) => {obj[next.Name] = new JValue(next.Value);  return obj;})

It would be nice if JObject had a chainable API, but it doesn't seem to.

A: Here
jobj[field.Name] = new JValue(field.Value);

you actually are calling the following JObject indexer:
public JToken this[string propertyName] { get; set; }

i.e. you are setting the JObject property.
So the LINQ equivalent will be like this:
var data = fieldList.Select(field => new JProperty(field.Name, field.Value));
var jobj = new JObject(data);


text:
Q: How do I provide a default value to EF Model when Stored Procedure does not return specified column We are using DB First Entity Framework in which We have a stored procedure which would return all the columns but one for a table. When I try to map that stored procedure to return the entity type it crashes saying
"The data reader is incompatible with the specified 'ReservingModel.t_MyTable'. A member of the type, 'MyTableID', does not have a corresponding column in the data reader with the same name."

I know I can create a complex type to match what sp is returning, or I can return a default value from sp itself, but what I here want to know is, is there anyway by which I can ask ef to set '0' into MyTableId if it was not returned by stored procedure ?

A: http://msdn.microsoft.com/en-US/data/jj691402
Quote from Article:
Note:EF does not take any mapping into account when it creates entities using the Translate method. It will simply match column names in the result set with property names on your classes.
You must either mark the property as [NotMapped], or return the Column with a default value via the stored procedure.
Select
ColA, ColB, ColC ,
[MyColumnName] = convert(bit , 0) /* this would mimic a false (dotnet) , aka, bit in sql-server */
from
dbo.MyTable

Make sure you have the correct datatype in the convert statement.


text:
Q: tf-agent, QNetwork => DqnAgent w/ tfa.optimizers.CyclicalLearningRate Is there an easy native way to implement tfa.optimizers.CyclicalLearningRate w/ QNetwork on DqnAgent?
Trying to avoid writing my own DqnAgent.
I guess the better question might be, what is a proper way to implement callbacks on DqnAgent?

A: From the tutorial you linked, the part where they set the optimizer is
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate)

train_step_counter = tf.Variable(0)

agent = dqn_agent.DqnAgent(
    train_env.time_step_spec(),
    train_env.action_spec(),
    q_network=q_net,
    optimizer=optimizer,
    td_errors_loss_fn=common.element_wise_squared_loss,
    train_step_counter=train_step_counter)

agent.initialize()

So you can replace optimizer with whatever optimizer you would rather use. Based on the documentation something like
optimizer = tf.keras.optimizers.Adam(learning_rate=tfa.optimizers.CyclicalLearningRate)

should work, barring any potential compatibility issues coming from that they are using the tf 1.0 adam in the tutorial.


text:
Q: Books about sql security Can anybody advice me some goods books for sql protection from hackers? Where it will clearly explain how hackers work and how to secure SQL.

A: For SQL server security this would be good.
the main security issue with SQL is SQL injection
Also look at these resources -
Google Code University - Web Security. - The second video is specific to cross-site scripting and SQL injection attacks
Foundations Security Every Programmer Experts Should Know
W3 School on web security

A: You can find useful stuff here:
Database Hacker's Handbook
SQL Injection Attack and Defense
SQL Server Security
Implementing Database Security and Auditing
The Rational Guide To SQL Server 2005 Security
SQL Server Security Distilled
Writing Secure Code
And of course the SQL databases benchmarks here, MySQL, SQLServer, Oracle, DB2 and even Sybase.


text:
Q: Using Carrierwave on a Devise Model I'm trying to use carrierwave to add profile images to a user model that's handled by devise.
I've used carrierwave before with no problems but this time, when I go to start the rails server, I get the error:
/var/lib/gems/1.9.1/gems/carrierwave-0.10.0/lib/carrierwave/mount.rb:46:in `uploader_option': undefined method `validate_integrity' for :ImageUploader:Symbol (NoMethodError)

There's very little information about this out there but I did read that you could ignore some errors using :ignore_integrity_errors. After trying a few times (and getting a lot of syntax errors) I finally settled on passing that in like so:
mount_uploader :profile_image, :ImageUploader, :options => {:ignore__integrity_errors => true}

I still think my syntax is incorrect because the NoMethodError persists. Any help at all on this matter would be much appreciated!
EDIT
I reverted to the commit before I started working with carrierwave, started my server, and tried again. In my browser I'm now getting the error:
uninitialized constant CarrierWave

on this line
class ImageUploader < CarrierWave::Uploader::Base

and this error apparently happens when the routes are loaded. I'm really confused about this, I have the gem in my Gemfile and I ran bundle install.

A: There are a couple of things going on here. First, the reason you're seeing the uninitialized constant CarrierWave error is probably just a consequence of not having restarted the server or something silly like that. If you've properly included it in the Gemfile and bundled, you should be fine.
To your original issue, though, there are three problems. The first is that you're passing a symbol as the uploader, and you need to pass the class. So you should pass ImageUploader, not :ImageUploader. The second issue is that you must pass the options hash directly to the uploader, not inside a parent hash with an options key. The third problem is that you've included an additional underscore in the ignore_integrity_errors symbol. So you should be using this:
mount_uploader :profile_image, :ImageUploader, ignore_integrity_errors: true

A: It would help to know what version to rails you are using. I've had this issue before but a server restart helped out.
Also, it looks like others had this issue. Maybe try doing what some of the users did here: https://github.com/carrierwaveuploader/carrierwave/issues/399


text:
Q: Dimension of an invariant subspace Let $V$ be a vector space of dimension $k$ and $n$ a positive integer. Let $a: V^n \to V$ be the map sending $(v_1,\ldots,v_n)$ to $v_1 + \cdots + v_n$. The symmetric group $S_n$ acts on $V^n$ by permuting the factors and the subspace $K := ker(a)$ is stable under this action.
What is the dimension of the vector spaces $( K^{\otimes l} )^{S_n}$, $(\wedge^lK)^{S_n}$, and $(Sym^lK)^{S_n}$ in terms of $k$, $n$, and $l$?  Is there any reference which does systematically this kind of computations?

A: UPDATE: this answer responded to an earlier version of the question, see comments below.
Any element of $V^{\oplus n}$ (this includes elements of $K$) that is invariant under $S_n$ is of the form $(v, v, \ldots, v)$. Now for such an element to lie in $K$ we must have $v + v + \ldots + v = 0$ ($n$ terms). If the characteristic of the ground field over which you have your vectorspace $V$ is zero (i.e. if the ground field are the complex numbers) this can only happen when $v = 0$ and so $K^{S_n} = \{0\}$.
If the characteristic of the ground field is $p$ then $v + v + \ldots + v = 0$ is possible when $p|n$. However, in that case it is not only possible but also inevitable. It follows  that for fields of characteristic $p$ the answer is:
$K^{S_n} = \{0\}$ if $p \not|  n$ and
$K^{S_n} = (V^{\oplus n})^{S_n} = \{(v, \ldots, v) : v \in V \}$ if $p|n$.


text:
Q: When does the pipeline take 2 decode stages when there is a RAW dependency in 2 successive instructions Consider a RISC pipeline having 5 stages, Find how many cycles are required for the instruction given below, assume operand forwarding, branch prediction is used in which the branch is not taken, ACS is the branch instruction and the five stages are Instruction fetch, Decode, Execute, Memory and Write back.
I1: ACS R0, R1,X

I2: LOAD R2, 0(R3)

I3: SUB R4 R2, R2
I4: X: ADD R5, R1, R2
I5: LOAD R1, 0(R5)

I6: SUB R1, R1, R4
I7: ADD R1, R1, R5

A. 11
B. 12
C. 13
D. 14

Solution:

In the solution, I coludn't understand why have they neglected 2 DECODE cycles in I6 and I7 although they have a RAW dependency?
Source of the question:
Question 41 of https://practice.geeksforgeeks.org/contest-quiz/sudo-gate-2020-mock-iii

A: I think the answer gives the right total (13 cycles) but put the stall in the wrong instruction.
I5 doesn't need to stall; I4 (ADD R5, R1, R2) produces R5 in time to forward it to the next instruction's EX for address calculation (LOAD R1, 0(R5)).  (Your 5-stage classic RISC pipeline has bypass forwarding).
But I6 reads the result of a load instruction, and loads produce their result a cycle later than the ALU in EX.  So like I3, I6 needs to stall, not I5.
(I7 depends on I6, but I6 is an ALU instruction so it can forward without stalling.)
They stalls in the D stage because the ID stage can't fetch registers that the I2 / I5 load hasn't produced yet.

Separately from that, your diagram shows I4 (and what should be I7) not even being fetched when the previous instruction stalls.  That doesn't make sense to me.  At the start of that cycle, the pipeline doesn't even know that it needs to stall because it hasn't yet decoded I3 (and I6) and detected that it reads a not-ready register so an interlock is needed.
Fetch doesn't wait until after decoding the previous instruction to see if it stalled or not; that would defeat the entire purpose of pipelining.  It should look like
I3     IF   D   D  EX  MEM   WB
I4         IF  IF   D   EX  MEM  WB

BTW, load latency is the reason that classic MIPS has a load-delay slot (unpredictable behaviour if you try to use a register in the next instruction after loading into it).  Later MIPS added interlocks to stall if you do that, instead of making it an error, so you can keep static code-size smaller (no NOP filler) in cases where you can't find any other instruction to put in that slot.  (And some even later MIPS did out-of-order exec which can hide latency.)


text:
Q: Windows store certification - error with SQLite I am unable to pass Windows app Certification test because of these 2 errors:
Package compliance test
FAILED
   MyApp takes a dependency on Microsoft Visual C++ Runtime Package (Microsoft.VCLibs.120.00) framework but is missing the framework dependency declaration in the manifest.

Supported API test
FAILED
API RoReportUnhandledError in api-ms-win-core-winrt-error-l1-1-1.dll is not supported for this application type. SQLiteWinRT.dll calls this API.
API ??0AccessDeniedException@Platform@@Q$AAA@P$AAVString@1@@Z in vccorlib120_app.dll is not supported for this application type. SQLiteWinRT.dll calls this API.
API ??0COMException@Platform@@Q$AAA@HP$AAVString@1@@Z in vccorlib120_app.dll is not supported for this application type. SQLiteWinRT.dll calls this API.
.....
API malloc in msvcr120_app.dll is not supported for this application type. SQLiteWinRT.dll calls this API.
API memcpy in msvcr120_app.dll is not supported for this application type. SQLiteWinRT.dll calls this API.

Type of the app: Windows Metro
Platform: Windows 8
There I add SQLite project as a reference to my my project.

Anybody experience same situation ?

A: You need to use the Windows Store specific library.  See here.


text:
Q: How to enable Google Ads Data Hub Account? Your account may not be associated with an active Ads Data Hub customer I'm trying to activate Google Ads Hub Account. We have Google Cloud account and my user has full control over the account. Does anybody know how to activate Ads Data Hub account ? :)
When I'm trying to access the interface of Ads Data Hub: https://adsdatahub.google.com/ I'm getting an error message "You do not have access to this application. Your account may not be associated with an active Ads Data Hub customer."
Link to support doesn't work: https://support.google.com/ads-data-hub/contact/adh_support
I found this article: https://developers.google.com/ads-data-hub/guides/account-setup which has a "Note: This guide assumes that you are the owner of both the Ads Data Hub account" so I probably already need to have some access to the Ads Data Hub in order to proceed... And when I'm trying to find Ads Data Hub API in list of Services/APIs it is not there neither...
Thanks.


text:
Q: Function not returning object for .then to work with - but able to console.log the object, and am explicitly returning it please can someone help shed some light as to why this .then is not taking the return value of the function call before it? This was working before I deployed to heroku, and I have a feeling its to do with eager loading, but I don't really know.
Basically the problem is: handleSubmit on registration calls on signup function, which is meant to return a user object, but .then isn't fed a return value from the signup function and errors: cannot read propery .then of undefined. So my handeSubmit is failing for trying to register to the app.
The signup method itself functions correctly (user is added to backend [Rails], JWT is provided and set in local storage in browser, and user object is rendered as JSON from API and succesfully console logged).
The handleSubmit looks like this:
      e.preventDefault();
      API.signup({ username, password })
         .then(user => {
            console.log(user);
            props.setUser(user);
            history.push("/home");
         })
         .catch(errors => {
            setErrors(errors[errors]);
            console.error(errors);
         });
   };

The signup function looks like this:
const signup = userDetails => {
  fetch(SIGNUP_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json"
    },
    body: JSON.stringify({ user: userDetails })
  })
  .then(jsonify)
  .then(data => {
    localStorage.setItem("token", data.token);
    console.log(data.user)
    return data.user
  })
};

Interestingly my login function, which is identical to signup (even identical handleSubmit) aside from hitting a different endpoint on my API, works absolutely fine.
It's not a CORS issue I'm pretty sure otherwise login wouldn't work either. Thanks for any advice on how to debug this. I can provide back and frontend code on request.

A: Your singup function doesn't return anything hence why you get the error either use return keyword before fetch or remove {}around your function


text:
Q: Azure API call - az apim update - update customProperties I am using following az api call command az apim show -n Namexxx -g RGxxx. As an output I am getting below:
{
"additionalLocations": null,
"apiVersionConstraint": {
"minApiVersion": null
},
"certificates": null,
"createdAtUtc": "2021-10-15T08:49:38.486813+00:00",
"customProperties": {
"Microsoft.WindowsAzure.ApiManagement.Gateway.Protocols.Server.Http2": "false",
"Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Backend.Protocols.Ssl30": "false",
"Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Backend.Protocols.Tls10": "false",
"Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Backend.Protocols.Tls11": "false",
"Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.TripleDes168": "true",
"Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Protocols.Ssl30": "false",
"Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Protocols.Tls10": "false",
"Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Protocols.Tls11": "false"
},

I need to modify one of the customProperties. I tried to use command: az apim update -n xxNamexx -g xxRGxx --set customProperties.Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.TripleDes168=false but I am getting an error like below:
Couldn't find 'Microsoft' in 'customProperties.Microsoft.WindowsAzure.ApiManagement.Gateway.Security'. Available options: ['Microsoft.WindowsAzure.ApiManagement.Gateway.Protocols.Server.Http2'

In MS API dos didn't find any useful information --> AZ apim API

A: @tester81
Command group 'apim' is experimental and under development.I tested the functionality at my end and I was encountering the same issue in a WinPowershell.
I did find an different behavior at the Ubuntu Terminal.
If you are not making use of Win Powershell/cmd for invoking the az commandlet, you could probably try the below script at your end in your linux terminal.
customPropertiesUpdated=$(az apim show -n <APIM NAME> -g <APIM RESOURCE GROUP> --query customProperties | jq '."Microsoft.WindowsAzure.ApiManagement.Gateway.Security.Ciphers.TripleDes168" = "True"')
az apim update -n <APIM NAME> -g <APIM RESOURCE GROUP> --set customProperties="$customPropertiesUpdated"

The above script helped in changing the state. However, a relative script in    Win Powershell / Commad prompt / Cloud shell did not.
The Alternative or the recommended approach would be to make use of the REST API - until it is out of the experimental stage.
Please do see properties.customProperties - Api Management Service - Create Or Update - REST API (Azure API Management) | Microsoft Docs


text:
Q: Inferior performance of Tensorflow compared to sklearn I'm comparing the performance of Tensorflow with sklearn on two datasets:

*

*A toy dataset in sklearn

*MNIST dataset

Here is my code (Python):
from __future__ import print_function

    # Import MNIST data
    from tensorflow.examples.tutorials.mnist import input_data
    mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

    import tensorflow as tf

    from sklearn.datasets import load_digits
    import numpy as np

    # digits = load_digits()
    # data = digits.data
    # labels = digits.target

    # convert to binary labels
    # y = np.zeros((labels.shape[0],10))
    # y[np.arange(labels.shape[0]),labels] = 1

    x_train = mnist.train.images
    y_train = mnist.train.labels
    x_test = mnist.test.images
    y_test = mnist.test.labels
    n_train = mnist.train.images.shape[0]

    # import pdb;pdb.set_trace()

    # Parameters
    learning_rate = 1e-3
    lambda_val = 1e-5
    training_epochs = 30
    batch_size = 200
    display_step = 1

    # Network Parameters
    n_hidden_1 = 300 # 1st layer number of neurons
    n_input = x_train.shape[1] # MNIST data input (img shape: 28*28)
    n_classes = 10 # MNIST total classes (0-9 digits)

    # tf Graph input
    X = tf.placeholder("float", [None, n_input])
    Y = tf.placeholder("float", [None, n_classes])

    # Store layers weight & bias
    weights = {
        'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
        'out': tf.Variable(tf.random_normal([n_hidden_1, n_classes]))
    }
    biases = {
        'b1': tf.Variable(tf.random_normal([n_hidden_1])),
        'out': tf.Variable(tf.random_normal([n_classes]))
    }

    # Create model
    def multilayer_perceptron(x):
        # Hidden fully connected layer with 256 neurons
        layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
        # Activation
        layer_1_relu = tf.nn.relu(layer_1)
        # Output fully connected layer with a neuron for each class
        out_layer = tf.matmul(layer_1_relu, weights['out']) + biases['out']
        return out_layer

    # Construct model
    logits = multilayer_perceptron(X)

    # Define loss and optimizer
    loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y)) + lambda_val*tf.nn.l2_loss(weights['h1']) + lambda_val*tf.nn.l2_loss(weights['out'])
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
    train_op = optimizer.minimize(loss_op)

    # Test model
    pred = tf.nn.softmax(logits)  # Apply softmax to logits
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1))
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    # Initializing the variables
    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)

        # Training cycle
        for epoch in range(training_epochs):
            avg_cost = 0.
            total_batch = int(n_train/batch_size)
            # Loop over all batches
            ptr = 0
            for i in range(total_batch):
                next_ptr = ptr + batch_size
                if next_ptr > len(x_train):
                    next_ptr = len(x_train)
                batch_x, batch_y = x_train[ptr:next_ptr],y_train[ptr:next_ptr]
                ptr += batch_size
                # Run optimization op (backprop) and cost op (to get loss value)
                _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
                                                                Y: batch_y})
                # Compute average loss
                avg_cost += c / total_batch
            # Display logs per epoch step
            if epoch % display_step == 0:
                print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost))
        print("Optimization Finished!")
        print("Accuracy on training set: ", accuracy.eval({X:x_train,Y:y_train}))
        print("Accuracy on testing set:", accuracy.eval({X: x_test, Y: y_test}))

    print("Experimenting sklearn...")
    # now experiment with sklearn
    from sklearn.datasets import load_digits
    import numpy as np
    from sklearn.neural_network import MLPClassifier
    import time

    # use MLP
    t_start = time.time()
    print('fitting MLP...')
    clf = MLPClassifier(solver='adam', alpha=1e-5, hidden_layer_sizes=(300,),max_iter=training_epochs)
    clf.fit(x_train,y_train)
    print('fitted MLP in {:.2f} seconds'.format(time.time() - t_start))
    print('predicting...')
    labels_predicted = clf.predict(x_test)
    print('accuracy: {:.2f} %'.format(np.mean(np.argmax(y_test,axis=1) == np.argmax(labels_predicted,axis=1)) * 100))

The code is adapted from a github repository. For this testing, I'm using a traditional neural network (MLP) with only one hidden layer of size 300.
Following is the result for the both datasets:

*

*sklearn digits: ~83% (tensorflow), ~90% (sklearn)

*MNIST: ~94% (tensorflow), ~97% (sklearn)

I'm using the same model for both libraries. All the parameters (number of hidden layers, number of hidden units, learning_rate, l2 regularization constant, number of training epochs, batch size) and optimization algorithms are the same (Adam optimizer, beta parameters for Adam optimizer, no momentum, etc).
I wonder if sklearn has done a magic implementation over tensorflow? Can anyone help answer?
Thank you very much.


text:
Q: images not showing on like box every day we post a photo album on our facebook page. They always used to show up in our like box embedded on our website until a couple of days ago. Now there is just a hyperlink to the album and nothing else. If we go back a month on our like box, we start to see photos again. What is causing this? does anyone know?

A: Use following meta tag to add image with like button:
<meta property="og:image" content="imageurl"/>


text:
Q: CSS on my site is working as programmed on android but works differently on IOS. What do I do to fix this?
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Find New Music</title>

Music Miner

      Find new songs, new genres and new artists with the click of a button

    <button onclick="randsong()" type="button" id="finder" class="start-items">
      Find An Artist
    </button>

    <form id="link" action="" target="_blank">
      <input type="submit" id="link-bt" value="" style="display: none" />
    </form>

and the CSS
@import url("https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap");
body {
  background-color: black;
  font-family: "Bebas Neue", cursive;
  color: #00ffff;
  text-align: center;
  align-content: center;
  margin: 0;
}
h1 {
  font-size: 8vw;
  margin-bottom: 0;
  margin-top: 2vh;
}
p {
  margin-top: 0;
  margin-bottom: 1.75vw;
  margin-left: 25vw;
  width: 50vw;
  font-size: 2vw;
}
a {
  font-size: 2vw;
  color: #66ff00;
  text-decoration: none;
}
button {
  border: none;
  height: 7vw;
  width: 13vw;
  padding: 2vw, 2vw;
  background-color: #00ffff;
  border-radius: 12px;
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  font-size: 2vw;
  font-family: "Bebas Neue", cursive;
  transition-duration: 0.5s all;
  margin-bottom: 3vw;
  margin-top: 0;
}
button:active {
  transform: scale(0.98);
  box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24);
}
#intro {
  margin-bottom: 3vw;
  font-style: italic;
}

#main {
  margin-left: 63.5vw;
}

#fcf-button,
#link-bt{
  padding: 0.5vw;
  width: 12vw;
  height: 4.5vw;
  padding: 1vw;
  margin-top: 1vw;
  margin-left: 0;
}
#link-bt{
    margin-left: 44.5%;
    background-color: #1fdf64;
    font-size: 1.5vw;
    border-radius: 12px;

}
#link-bt:active{
  transform: scale(0.98);
  box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24);

}

@media screen and (max-width: 650px) {
  #nav-heading {
    font-size: 4vw;
  }
  a,
  p {
    font-size: 4vw;
  }
  #main {
    margin-left: 40vw;
  }
  button,
  #link-bt {
      height: 8vw;
      width: 16vw;
      font-size: 3vw;
    }

    #link-bt {
      font-size: 2vw;
      color: black;
    }

}

This is how it is on android
Android Home Page
Android Artist Page
And this is how it is on IOS.
IOS Home Page
IOS Artist Page
What Should I do to fix this. Do I change something in the code or do I have to do something else. Also sorry for the messy CSS I'm not much of a web developer. I've also omitted some Javascript from the main HTML file s because I thought it doesn't make much of a difference.


text:
Q: send curl without waiting for response php I am currently working on a script and i need to make some curl posts. The problem is that the script will need to perform a lot of these requests which i am afraid will affect the performance and response time.Please note that i only need to make the curl post and i don't need the answer.
Here is the code I am using :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_USERAGENT, 'api');
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_close($ch);

Am I using the right code ? Will this code only post the request and closes and don't wait for any response ?
Thanks guys for your help in advance.

A: You can use this function, this works well! :)
function systemCurl($url, $post_array, $headers=null, $check_ssl=true) {
  if(!is_null($headers)){
    foreach($headers as $key => $val){
      $head .= " -H '".$key.":". $val."' ";
    }
  }
  $cmd = "curl -X POST ".$head;
  $cmd.= " -d '" . json_encode($post_array) . "' '" . $url . "'";
  if(!$check_ssl){
    $cmd.= "'  --insecure";
  }
  $cmd .= " > /dev/null 2>&1 &";
  exec($cmd, $output, $exit);
  return $exit == 0;
}

A: If you can use shell_exec function, then you can use this:

exec('curl http://example.com/example > /dev/null 2>&1 &');

A: i would recommend you to use jquery  ajax so you dont need to care about processing time
$.ajax("yourFile.php");

where yourFile.php contains your cUrl php script with data


text:
Q: Performance issues with KVM versus Virtualbox I'm trying to use KVM on Ubuntu (5.8.0-59-generic #66~20.04.1-Ubuntu) and finding some serious performance issues. In order to quantify the problem, I tried a fresh install of Windows 7, both under KVM and Oracle Virtualbox. The latter was considerably faster. Overall, performance on the Virtualbox VM is pretty good (obviously not as good as native, but still respectable enough), but with KVM was terrible (screen refresh was slow, mouse pointer stuttered, IO was up to 20x slower etc). Settings on both installations were "out of the box" (I used virt-manager to set up the VM under KVM) (so I didn't use virtio with KVM, or Guest Additions with Virtualbox).
So my question is: is this just a case of KVM being "a bit rubbish" (as has been suggested), or is this a problem with my setup? Is it worth doing a bit more work to try and get it working properly, or am I wasting my time? I know that KVM is good for passthrough hardware support... is this why it's popular?
Thanks!

A: KVM is massively better than VirtualBox. Windows takes a lot of hand holding to get the best performance when virtualizing, and KVM probably doesn't care about pandering to it by default.
Make sure your timers are appropriately configured:
https://altechnative.net/virtualized-windows-10-idle-cpu-consumption/
Regarding I/O, make sure you enable writeback caching. Pinning vCPUs to physical cores will also help.
For graphical performance, KVM doesn't support 3D acceleration (VirtualBox sort of almost does to a usable extent), but for 2D it is pretty decent if you install the paravirtualized QXL driver and use Spice instead of VNC protocol for accessing it.


text:
Q: Creating a Virtual Host for Apache MAMP I'm trying to create a virtual host on my MAMP setup so I can access http://api.localhost for a PHP API I'm trying to build with Slim. Here's the code I've appended to my httpd.conf file:
Name VirtualHost 127.0.0.1
<VirtualHost 127.0.0.1>
    DocumentRoot "/Applications/MAMP/htdocs/slim"
    ServerName api.localhost
</VirtualHost>

When I restart the server and try to start it up again with this new configuration, it simply won't load. I commented out the new code and it loads fine. Any ideas?

A: try to use this line
<VirtualHost *:80>

instead of yours
and I think you can remove the first line too...


text:
Q: Game crashes when I try to use the features of a b2Body -- why? My app crashes when I try to use the features of b2Body from within my NSObject class.
Here is the interface of my class:
#import <Foundation/Foundation.h>

#import "Box2D.h"
#import "GLES-Render.h"
#import "cocos2d.h"
#import "HelloWorldScene.h"

@interface Magnet : NSObject {
    b2Body* body;
}
@property (readwrite,assign) b2Body* body;
@end

And here is how I declare it in HelloWorldScene.h:
#import "cocos2d.h"
#import "Box2D.h"
#import "GLES-Render.h"
#import <UIKit/UIKit.h>
#import "Magnet.h"

@class Magnet;

@interface HelloWorld : CCLayer {
    b2World* world;
    GLESDebugDraw *m_debugDraw;
    Magnet *magnet;
}

And here is how I access the b2Body in magnet, in HelloWorldScene.mm:
b2BodyDef bodyDef2;
bodyDef2.type = b2_staticBody;

bodyDef2.position.Set(300/PTM_RATIO, 150/PTM_RATIO);
bodyDef2.userData = sprite2;
magnet.body = world->CreateBody(&bodyDef2);

// Define another box shape for our dynamic body.
//b2PolygonShape dynamicBox;
b2CircleShape dynamicBox2;

//dynamicBox.SetAsBox(1.0f, 1.0f);//These are mid points for our 1m box
dynamicBox2.m_radius = 0.49;
// Define the dynamic body fixture.
b2FixtureDef fixtureDef2;

fixtureDef2.shape = &dynamicBox2;
fixtureDef2.density = 1.3f;
fixtureDef2.friction = 1.0f;

magnet.body->CreateFixture(&fixtureDef2);

Is there any problem with my code?
I'm receiving a SIGABRT in the Box2D source files, in the CreateFixture() function. What should I do?
Sorry about the mess, here is the backtrace:
    (gdb) bt
    #0  0x0002f35c in b2Body::CreateFixture (this=0x0, def=0xbfffd360) at b2Body.cpp:141
    #1  0x00004f7e in -[HelloWorld loadLevel:] (self=0x5544770, _cmd=0xfbc7c, level=1) at HelloWorldScene.mm:255
    #2  0x0000573d in -[HelloWorld init] (self=0x5544770, _cmd=0x4ffd774) at HelloWorldScene.mm:140
    #3  0x0009d7b1 in +[CCNode node] (self=0x147100, _cmd=0xfc558) at CCNode.m:231
    #4  0x0000377d in +[HelloWorld scene] (self=0x147100, _cmd=0xfb61c) at HelloWorldScene.mm:39
    #5  0x000036d7 in -[MagnetSpillAppDelegate applicationDidFinishLaunching:] (self=0x680b9f0, _cmd=0xca40a3, application=0x5511370) at MagnetSpillAppDelegate.mm:96
    #6  0x008b1ce2 in -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] ()
    #7  0x008b3d88 in -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] ()
    #8  0x008be617 in -[UIApplication handleEvent:withNewEvent:] ()
    #9  0x008b6abf in -[UIApplication sendEvent:] ()
    #10 0x008bbf2e in _UIApplicationHandleEvent ()
    #11 0x029ca992 in PurpleEventCallback ()
    #12 0x0147d944 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ ()
    #13 0x013ddcf7 in __CFRunLoopDoSource1 ()
    #14 0x013daf83 in __CFRunLoopRun ()
    #15 0x013da840 in CFRunLoopRunSpecific ()
    #16 0x013da761 in CFRunLoopRunInMode ()
    #17 0x008b37d2 in -[UIApplication _run] ()
    #18 0x008bfc93 in UIApplicationMain ()
    #19 0x00002cc4 in main (argc=1, argv=0xbffff058) at main.m:13

A: Without the crash, it is hard to say specifically what is going wrong.
However, that code is rife with potential for crashes.

*

*you are using structures that are on the stack, not allocated.  If the scope of that code goes away before you are done with those structures, it'll lead to crashes and undefined behavior.

*you aren't initializing all the fields in those structures; the remaining values will be in an undefined state.   Since it is impossible to differentiate an uninitialized float32 from an initialized float32, that is bound to eventually lead to problems.

*you are setting up structures on the stack that have references to other structures on the stack;  another form of the first point, but should be called out because it makes it doubly easy to leak pointers to the stack.

Line 141 of b2Body::CreateFixture() is an assert:
    b2Assert(m_world->IsLocked() == false);

Is your world locked?  Looks like it shouldn't be.


text:
Q: multiple row fetched with max number sql I have two tables with the following records:
Clients:
cid | cname | ccountry
-----------------------
  1 | John  | Australia
  2 | Mark  | USA
  3 | Liz   | England

Orders:
oid | cid | oquantity
---------------------
  1 |   1 |       100
  2 |   1 |       100
  3 |   2 |        50
  4 |   2 |       150
  5 |   3 |        50
  6 |   3 |       100

I need to find out the Client name(s) who has maximum quantity of orders. I run the following query and got the correct result.
select cname, ccountry
  from Clients
 where cid in
         (select cid
            from Orders
        group by cid
          having sum(oquantity) = (select max(amount) from
                                       (select sum(oquantity) amount
                                          from Orders
                                        group by cid)t1))

2 row(s) returned

'John', 'Australia'
'Mark', 'USA'

But I just need to know, whether it can be done by more simple way. It has become complicated once total quantity is also required to be returned.

A: SELECT c.cname, c.ccountry, SUM(oquantity) AS total_qtty
FROM Clients c
INNER JOIN Orders o ON (o.cid = c.cid)
GROUP BY c.id
ORDER BY total_qtty DESC
LIMIT 2

A: I have reduced your 2 Subqueries.
SELECT
  clients.cid,
  cname,
  ccountry
FROM Orders,
  Clients
WHERE orders.cid = clients.cid
GROUP BY clients.cid
HAVING SUM(orders.oquantity) = (SELECT
                                  SUM(oquantity) AS amount
                                FROM Orders
                                GROUP BY cid
                                ORDER BY amount DESC
                                LIMIT 1 )

A: Try :
select cname, ccountry, sum(oquantity)
FROM Clients c
INNER JOIN Orders o ON (o.cid = c.cid)
where c.cid in
(
  select cid from Orders group by cid
   having sum(oquantity) = (
     select max(amount) from (
        select sum(oquantity) amount from Orders group by cid)t1))
GROUP BY c.cid


text:
Q: CSS, how to change the background after a certain time and keep it like that When i run this the color will change after 5 seconds but after the 5 seconds it goes back to White, however i want it to stay #1b1b1b
.bg {
  -webkit-animation: change-color 5s; /* Safari 4+ */
  -moz-animation:    change-color 5s; /* Fx 5+ */
  -o-animation:      change-color 5s; /* Opera 12+ */
  animation:         change-color 5s; /* IE 10+ */
}

And
@-webkit-keyframes change-color {
 from {
        background: White;
 }
 to {
        background: #1b1b1b;
 }
}
(I also use -moz-animation etc)

A: Just add forwards to you animation declaration:

.bg {
  height: 400px;
  width: 400px;
  -webkit-animation: change-color 5s forwards;
  /* Safari 4+ */
  -moz-animation: change-color 5s forwards;
  /* Fx 5+ */
  -o-animation: change-color 5s forwards;
  /* Opera 12+ */
  animation: change-color 5s forwards;
  /* IE 10+ */
}

@-webkit-keyframes change-color {
  from {
    background: white;
  }
  to {
    background: #1b1b1b;
  }
}

Please notice that background: White is invalid but background: white is.

A: Use a simple transition.
body {
    background: red;
    transition: background 5s linear;
}

.recolor {
    background: black;
}

Adding the class recolor to the body will change the color from red to black.


text:
Q: Extract specific text in between 2 strings Assume we have text such as the following.
Title: (some text)
My Title [abc]

Content: (some test)
My long content paragraph. With multiple sentences. [abc]

Short Content: (some text)
Short content [abc]

Using Javascript and RegEx, is it possible to extract the text so that it would be as follows.
Title: My Title
Content: My long content paragraph. With multiple sentences.
Short Content: Short content

Basically ignoring new lines and text in the () and [] brackets?
I've tried to use Regex but I can't get it to do exactly as I'd like. I'm also getting the issue that when I match Content: i'm getting a match for both Content: & Short Content: however i'd want to only match the occurrence where it is an exact match.
EDIT:
I'm new to RegEx. So far to extract the titles such as Title:, Content: and so on I have
/[A-Za-z]+:|[A-Za-z]+ [A-Za-z]+:|[A-Za-z]+ [A-Za-z]+ [A-Za-z]+:|[A-Za-z]+ [A-Za-z]+ [0-9]+:/g

And then I loop through and use this
[TITLENAME]:.*\n.*

I'm struggling to get past this. My next step would be to loop through the text that is matched above and then remove the bracket stuff. I'm sure there is a better way to do this!

A: You could use String.replace( /(\(|\)|\[|\])/g , '')
If you take a string and use the replace method with these two arguments it will return a string with the ()[] characters removed. I have escaped them all with \ since they are special characters in regex. It might be a little over zealous.
Also g makes the regular expression global so it will remove all instances

A: If the text within parenthesis (e.g. 'abc') is fixed and have a special meaning you can also go with: '/(\(some text\)\n|\(some test\)\n|(\[abc\]))|(^$\n)/gm'.
This way you would allow parenthesis in the real text that you want to preserve, e.g. some text (this I want to preserve) and other text.
Please note the multiline m flag.
https://regex101.com/r/cS3pRR/1


text:
Q: Check password of large 7zip file quickly I have a large 7zip file which I forgot the password to.
I can narrow down the password possibilities to a word list with about 2000 passwords.
Only problem is, that it takes ages for each password to be checked, since its such a large file.
Is there a way to speed up the process, or is a 7zip file encrypted as "one"?
I am a complete noob in this field, thats why I am asking.

A: Use the commandline interface of 7z to test the archive. As a parameter you can pass a password. You can wrap this in a scripting for-loop that loops over your candidate passwords.

*

*Commandline options of 7z

*You can use the exitcode to check if you got the right password.

The 7z command is thus: 7z t archive.zip -p <password>
In pseudocode:
FOR password IN passwordlist:
    exitcode = 7z t archive.zip -p password
    IF exitcode == 0:
        PRINT Found password: password


text:
Q: Custom Settings values not being queried I have a custom settings which has the following columns:
Department || Sub Department || Employee || Serial Number
My code is :
for(CustomSettings__c cst: CustomSettings__c.getAll().values()) {

So the list should get fetched arranged in ascending order according to serial number.
Currently there are 10 records and I need to add 4 more . If I'm adding any extra , it's not coming up in my final output. Total records getting fetched is still 10 .
But if I change the serial number of a new record to say 5 , that is getting fetched and the old record , whose serial number is now beyond 10 , is not getting fetched.
In Developer console , all custom settings are getting fetched.
Please suggest.

A: Please check whether the field type of Serial_Number__c field is it Number with length of 1 digit by any chance?
This looks like a strange issue. Also try once by directly using SOQL also. Like below,
List<Custom_Setting__c> customList = [select field1__c, field2__c from Custom_Setting__c];

If still not working, I think you might have to raise a ticket with salesforce support team.


text:
Q: MD5 of javascript content in WSO2 ESB API I have to deal with javascript content in API resource in WSO2 ESB. Specifically, I want to get the md5 hash from message which it is a javascript.
When I use messageType = application/javascript I get a binary, no JS message.
Can I do this? If I use binary to get md5, Will it work?

A: Finally, I solved this question as given below:
At first, I changed in axis2.xml the messageBuldir and messageFormater property to "text/javascript" pointing to "org.apache.axis2.format.PlainTextBuilder" and "org.apache.axis2.format.PlainTextFormatter".
At second I got the message in API with next expression: "s11:Body/child::[fn:position()=1] | s12:Body/child::[fn:position()=1]". With that, I can save the js message in a property.
Finally, I wrote a class mediator to calculate MD5 of property with JS.


text:
Q: How to swap two windows of the same app in taskbar In Windows 10, if you want to swap two windows in the taskbar, you just drag and swap the two windows. But if the two windows are from the same app, for example if they are both Chrome windows - you can't swap windows that way, as all the windows would move together.
So how do you swap two windows of the same app? I think it's still somehow possible - as a couple of times in Chrome I accidentally swapped two windows, without any clue as to how. Perhaps there's some key you have to press down while attempting the "drag-swapping"?
This specific question about swapping two windows of the same app has not been asked in SuperUser before, I believe.


text:
Q: Adding custom attributes in HTML I want to make an image which, when clicked, displays some additional information about the image, such as the title. Below is some code I have tried, which seems to work. However, this was just after deciding on my own to try adding a custom attribute "title", rather than reading somewhere that this was the way to do this. So, even though this works for me, I would like to know whether this is good practice, or whether there is a recommended way to do this?
HTML:

jQuery:
$("#test_image").click(function()
{
    alert(this.title);
});

A: title isn't a custom attribute, it's a standard attribute. It gets displayed in a tooltip when you hover over the element.
You should not create custom attributes. HTML5 has a standard mechanism for user-defined attributes, data attributes. All attributes beginning with data- are reserved for the programmer to use. And jQuery has a method for accessing these, .data().

$("#test_image").click(function()
{
    alert($(this).data('title'));
});


text: Q: Perform Mouse Click Event on a second screen I am using vb.net. I have two systems: one is my laptop running the VS and the second system is a thin client to which I only have access to a USB port. This second system is not on the network due to limitations. The objective is to pass on the mouse click function to the thin client from my laptop programmatically. I know the pixel location where the click function is to be performed but how can I pass this command to the thin client machine?


text:
Q: Can we restore My Computer > Manage to prior functionality in Server 2012-R2 In the newer server versions when right clicking on My Computer / This PC, we are presented with the option to 'Manage', when clicked it opens the Server Manager, which can take up to 10-20 seconds in slower machines.  In prior versions, this would open up compmgmt.msc and take 1-2 seconds to open.
At work we make small changes daylong and all our techs have coffee, donut, or phone in their free hands and cannot make use of the Winkey + X start menu.  Thus avoiding those types of responses - double wink.
Is there any way we can just modify the registry forcing the Manage link to behave like it did in older versions of Windows Server i.e. spawn compmgmt.msc instead of server manager.

A: This registry snippet should alleviate all that, run it from Powershell (as admin) and when you right click This PC 'Manage' it will open compmgmt.msc directly. Works instantly.
Enable - Manage via CompMgmt.msc
Set-ItemProperty -Path 'registry::HKEY_CLASSES_ROOT\clsid\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\shell\Manage\command' -Name "(default)" -Value "mmc %SystemRoot%\system32\compmgmt.msc"
#

Restore original setting - Manage via Server Manager.
Set-ItemProperty -Path 'registry::HKEY_CLASSES_ROOT\clsid\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\shell\Manage\command' -Name "(default)" -Value "%SystemRoot%\system32\CompMgmtLauncher.exe"
#

NOTE: One does not simply point to compmgmt.msc or it splashes a metro style half-screen error, cmd /c start /b method avoids it.  Included a restore setting even though the OP didn't ask and probably won't use it.

A: This is probably on top of my list of annoyances on Server 2012.
Thanks for the answer, but that didn't quite work for me. I had to modify it a little and change it to different key:
Set-ItemProperty -Path 'registry::HKEY_CLASSES_ROOT\Launcher.Computer\shell\Manage\command' -Name "(default)" -Value "mmc %SystemRoot%\system32\compmgmt.msc"

This key was locked down so I had to give ownership to local admins and then add full control perms.
Thanks for your solution. My life is a little easier now.


text:
Q: MYSQL Database Design - Source of Income different table - Is there better way than polymorphism The scenario is a user should input his/her source of income whether business, employed or retired.
The data below is my current database table. Is there a better way to handle the scenario without using polymorphism?
user table
sourceOfIncome_type
sourceOfIncome_id

sourceOfincome_business table
 - companyName
 - monthlyIncome
sourceOfincome_employed table
 - companyName
 - position
sourceOfincome_retired table
 - retiredSince

A: Maybe you could use Single table inheritance, where all source of incomes are defined in a single table but your code treats them as separate models.
This way your user model only has the income id to reference its source of income, and you can leverage foreign keys checks and cascade.
I don't think TypeORM supports it by default, you can check how MikroORM implements it
https://mikro-orm.io/docs/inheritance-mapping#single-table-inheritance


text:
Q: Turn off scientific notation and offset globally I have been trying for several hours to globally turn off scientific notation and the offset in matplotlib. my attempt at a solution
import matplotlib  as mpl
import matplotlib.pyplot as plt

The documentation says:

set the rcParam axes.formatter.useoffset=False to turn it off globally, or set a different formatter.

mpl.rcParams.formatter.useoffset = False

Of course this fails because there is no formatter for rcParam
mpl.ticker.FuncFormatter.__setattr__('set_scientific',False)

I am completely lost trying to do this. I have just switched from matlab. So I apologize if this is very basic

A: You need to change the setting in setting file, you can get the current setting file path by following code:
import matplotlib as mpl
print mpl.matplotlib_fname()

if the file is in mpl-data folder, then copy it to user setting folder by following code:
import shutil
shutil.copy(mpl.matplotlib_fname(), mpl.get_configdir())

then restart you python session and show the path again:
print mpl.matplotlib_fname()

edit this file:
axes.formatter.useoffset      : False

Is you only want to disable this in one of your programm, you can set the setting before any plot:
mpl.rcParams["axes.formatter.useoffset"] = False


text:
Q: BrowserMob Proxy + Selenium: Not receiving any HTTP responses Maven/Java project with dependencies:
      <dependencies>
<dependency>
  <groupId>net.lightbody.bmp</groupId>
  <artifactId>browsermob-core</artifactId>
  <version>2.1.4</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.3.4</version>
</dependency>

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>3.7.1</version>
</dependency>

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>23.0</version>
</dependency>
</dependencies>

Code:
public class bmp_Selenium {
@Test
public void test() throws Exception {
    String chromedriverPath = System.getProperty("user.dir") + "/chromedriver";
    System.setProperty("webdriver.chrome.driver", chromedriverPath);

    BrowserMobProxy proxy = getProxyServer(); //getting browsermob proxy
    System.out.println("BrowserMob Proxy running on port: " + proxy.getPort());

    Proxy seleniumProxy = getSeleniumProxy(proxy);

    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);

    WebDriver driver = new ChromeDriver(capabilities);

    proxy.newHar("foo");
    driver.get("http://www.google.com");

    Har har = proxy.getHar();

    // Write HAR Data in a File
    String harFilePath = System.getProperty("user.dir") + "/hars/ww.har";
    File harFile = new File(harFilePath);
    try {
        har.writeTo(harFile);
    } catch (IOException ex) {
         System.out.println (ex.toString());
         System.out.println("Could not find file " + harFilePath);
    }

    List<HarEntry> entries = har.getLog().getEntries();
    for (HarEntry entry : entries) {
        System.out.println("Request URL: " + entry.getRequest().getUrl());
        System.out.println("Entry response status: " + entry.getResponse().getStatus());
        System.out.println("Entry response text: " + entry.getResponse().getStatusText());

    }

    proxy.stop();
    driver.quit();
}

public Proxy getSeleniumProxy(BrowserMobProxy proxyServer) {
    Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxyServer);
    try {
        String hostIp = Inet4Address.getLocalHost().getHostAddress();
        seleniumProxy.setHttpProxy(hostIp + ":" + proxyServer.getPort());
        seleniumProxy.setSslProxy(hostIp + ":" + proxyServer.getPort());
    } catch (UnknownHostException e) {
        e.printStackTrace();
        Assert.fail("invalid Host Address");
    }
    return seleniumProxy;
}

public BrowserMobProxy getProxyServer() {
    BrowserMobProxy proxy = new BrowserMobProxyServer();
    proxy.setTrustAllServers(true);
    proxy.setHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
    proxy.start();
    return proxy;
}

}
Console output:

BrowserMob Proxy running on port: 57547
  Starting ChromeDriver 2.33.506106 (8a06c39c4582fbfbab6966dbb1c38a9173bfb1a2) on port 47157
  Only local connections are allowed.
  Nov 30, 2017 4:48:33 PM org.openqa.selenium.remote.ProtocolHandshake createSession
  INFO: Detected dialect: OSS
  Request URL: http://www.google.com/
  Entry response status: 0
  Entry response text:
  Request URL: http://www.google.com/
  Entry response status: 0
  Entry response text:
  Request URL: http://www.google.com/
  Entry response status: 0
  Entry response text:
  Request URL: http://www.google.com/
  Entry response status: 0
  Entry response text:

Har File:
{
  "log": {
    "version": "1.2",
    "creator": {
      "name": "BrowserMob Proxy",
      "version": "2.1.4",
      "comment": ""
    },
    "pages": [{
        "id": "foo",
        "startedDateTime": "2017-11-30T21:48:34.064Z",
        "title": "foo",
        "pageTimings": {
          "comment": ""
        },
        "comment": ""
      }
    ],
    "entries": [{
        "pageref": "foo",
        "startedDateTime": "2017-11-30T21:48:34.210Z",
        "request": {
          "method": "GET",
          "url": "http://www.google.com/",
          "httpVersion": "HTTP/1.1",
          "cookies": [

          ],
          "headers": [

          ],
          "queryString": [

          ],
          "headersSize": 417,
          "bodySize": 0,
          "comment": ""
        },
        "response": {
          "status": 0,
          "statusText": "",
          "httpVersion": "unknown",
          "cookies": [

          ],
          "headers": [

          ],
          "content": {
            "size": 0,
            "mimeType": "",
            "comment": ""
          },
          "redirectURL": "",
          "headersSize": -1,
          "bodySize": -1,
          "comment": "",
          "_error": "No response received"
        },
        "cache": {},
        "timings": {
          "comment": "",
          "send": 0,
          "wait": 0,
          "receive": 0,
          "ssl": -1,
          "connect": -1,
          "blocked": 0,
          "dns": -1
        },
        "comment": "",
        "time": 0
      }, {
        "pageref": "foo",
        "startedDateTime": "2017-11-30T21:48:34.224Z",
        "request": {
          "method": "GET",
          "url": "http://www.google.com/",
          "httpVersion": "HTTP/1.1",
          "cookies": [

          ],
          "headers": [

          ],
          "queryString": [

          ],
          "headersSize": 417,
          "bodySize": 0,
          "comment": ""
        },
        "response": {
          "status": 0,
          "statusText": "",
          "httpVersion": "unknown",
          "cookies": [

          ],
          "headers": [

          ],
          "content": {
            "size": 0,
            "mimeType": "",
            "comment": ""
          },
          "redirectURL": "",
          "headersSize": -1,
          "bodySize": -1,
          "comment": "",
          "_error": "No response received"
        },
        "cache": {},
        "timings": {
          "comment": "",
          "send": 0,
          "wait": 0,
          "receive": 0,
          "ssl": -1,
          "connect": -1,
          "blocked": 0,
          "dns": -1
        },
        "comment": "",
        "time": 0
      }, {
        "pageref": "foo",
        "startedDateTime": "2017-11-30T21:48:34.225Z",
        "request": {
          "method": "GET",
          "url": "http://www.google.com/",
          "httpVersion": "HTTP/1.1",
          "cookies": [

          ],
          "headers": [

          ],
          "queryString": [

          ],
          "headersSize": 417,
          "bodySize": 0,
          "comment": ""
        },
        "response": {
          "status": 0,
          "statusText": "",
          "httpVersion": "unknown",
          "cookies": [

          ],
          "headers": [

          ],
          "content": {
            "size": 0,
            "mimeType": "",
            "comment": ""
          },
          "redirectURL": "",
          "headersSize": -1,
          "bodySize": -1,
          "comment": "",
          "_error": "No response received"
        },
        "cache": {},
        "timings": {
          "comment": "",
          "send": 0,
          "wait": 0,
          "receive": 0,
          "ssl": -1,
          "connect": -1,
          "blocked": 0,
          "dns": -1
        },
        "comment": "",
        "time": 0
      }, {
        "pageref": "foo",
        "startedDateTime": "2017-11-30T21:48:34.327Z",
        "request": {
          "method": "GET",
          "url": "http://www.google.com/",
          "httpVersion": "HTTP/1.1",
          "cookies": [

          ],
          "headers": [

          ],
          "queryString": [

          ],
          "headersSize": 443,
          "bodySize": 0,
          "comment": ""
        },
        "response": {
          "status": 0,
          "statusText": "",
          "httpVersion": "unknown",
          "cookies": [

          ],
          "headers": [

          ],
          "content": {
            "size": 0,
            "mimeType": "",
            "comment": ""
          },
          "redirectURL": "",
          "headersSize": -1,
          "bodySize": -1,
          "comment": "",
          "_error": "No response received"
        },
        "cache": {},
        "timings": {
          "comment": "",
          "send": 0,
          "wait": 0,
          "receive": 0,
          "ssl": -1,
          "connect": -1,
          "blocked": 0,
          "dns": -1
        },
        "comment": "",
        "time": 0
      }
    ],
    "comment": ""
  }
}

A: As per GitHub user mediga's suggestion, modifying the BMP dependency resolved the issue:
replace this
<dependency>
  <groupId>net.lightbody.bmp</groupId>
  <artifactId>browsermob-core</artifactId>
  <version>2.1.4</version>
  <scope>test</scope>
</dependency>

with
>     <dependency>
>       <groupId>net.lightbody.bmp</groupId>
>       <artifactId>browsermob-core</artifactId>
>       <version>2.1.5</version>
>     </dependency>

https://github.com/lightbody/browsermob-proxy/issues/689#issuecomment-348620752


text:
Q: How to find ratio of values in two rows that have the same identifier using python dataframes I have a dataframe with 4858 rows and 67 columns. This contains the stats from each game in the season for each MLB team. This means that for every game, there are two rows of data. One with the stats from one team and the other with the stats from the team they played. Here are the column names: ['AB', 'R', 'H', 'RBI',
'BB', 'SO', 'PA', 'BA', 'OBP', 'SLG', 'OPS', 'Pit', 'Str', 'RE24',
'WinOrLoss', 'Team', 'Opponent', 'HomeOrAway', 'url', 'Win_Percentage',
'R_Season_Long_Count', 'H_Season_Long_Count', 'BB_Season_Long_Count',
'SO_Season_Long_Count', 'PA_Season_Long_Count', 'R_Moving_Average_3',
'R_Moving_Average_10', 'R_Moving_Average_31', 'SLG_Moving_Average_3',
'SLG_Moving_Average_10', 'SLG_Moving_Average_31', 'BA_Moving_Average_3',
'BA_Moving_Average_10', 'BA_Moving_Average_31', 'OBP_Moving_Average_3',
'OBP_Moving_Average_10', 'OBP_Moving_Average_31', 'SO_Moving_Average_3',
'SO_Moving_Average_10', 'SO_Moving_Average_31', 'AB_Moving_Average_3',
'AB_Moving_Average_10', 'AB_Moving_Average_31', 'Pit_Moving_Average_3',
'Pit_Moving_Average_10', 'Pit_Moving_Average_31', 'H_Moving_Average_3',
'H_Moving_Average_10', 'H_Moving_Average_31', 'BB_Moving_Average_3',
'BB_Moving_Average_10', 'BB_Moving_Average_31', 'OPS_Moving_Average_3',
'OPS_Moving_Average_10', 'OPS_Moving_Average_31',
'RE24_Moving_Average_3', 'RE24_Moving_Average_10',
'RE24_Moving_Average_31', 'Win_Percentage_Moving_Average_3',
'Win_Percentage_Moving_Average_10', 'Win_Percentage_Moving_Average_31',
'BA_Season_Long_Average', 'SLG_Season_Long_Average',
'OPS_Season_Long_Average']
Then, here is a picture of the output from these columns. Sorry, it's only from a few columns but essentially all the stats will just be numbers like this.

The most important column for this question is the url column. This column identifies the game played as there is only one unique url for each game. However, there will be two rows within the dataframe that have this unique url as one will contain the stats from one team in that game and the other will contain the stats from the other team also in that game.
Now, what I am wanting to do is to combine these two rows that are identified by the common url by creating a ratio between them. So, I would like to divide the stats from the first team by the stats from the second team for that specific game with the unique url. I want to do this for each game/unique url. I am able to sum them by using the groupby.sum() function, but I am unsure how to find the ratio between the two rows with the same url. I would really appreciate any suggestions. Thanks so much!

A: Assumptions:

*

*always 2 rows for each url

*in each url, among the 2 rows, you don't care which is divided by which

A small example of your dataset:
df = pd.DataFrame({
    'url': ['1', '1', '2', '2', '3', '3'],
    'non-stat1': np.arange(1., 7.),
    'non-stat2': np.arange(2., 8.),
    'stat1': np.arange(13., 19.),
    'stat2': np.arange(6., 12.),
})

This lists the columns which are the stats that you want to apply division.
columns_for_ratio = ['stat1', 'stat2']

This is how the division works. .values get you an array which always has two rows, so you can unpack the array into two variables, one array for each.
def divide(two_rows):
    x, y = two_rows.values
    return pd.Series(x/y, two_rows.columns)

And finally do the division
df.groupby('url')[columns_for_ratio].apply(divide)


text:
Q: How do I create a custom 410 error page using the Django Redirect App? I am redesigning a website with lots of old (and very poorly optimized) content. It doesn't make sense to migrate the old content, so I am using the Django Redirects App to raise 410 errors in case anybody discovers a link to the old website.
https://docs.djangoproject.com/en/2.1/ref/contrib/redirects/
I am currently getting the default Chrome 410 error page. How do I deliver a custom 410 error page?

A: Why are you using the redirect app? A redirect should be done when the page has moved or you think you can take the user to a better experience (http to https for example).
If the page is gone, you should not redirect, but just return a HttpResponse with status 410.
You can wrap it in a render function to specify a custom template, just be sure to pass a status=410.


text:
Q: How do I access a method from a custom made class? I have a class defined as follows:
export default class MyClass {

    myMethod(code){
        console.log("The code is" + code)
    }
}

How can I access it from my main class? In the main class I have the following  lines of code:
import MC from './MyClass'

...

MC.myMethod("987");

The error I am getting is:
undefined is not a function (evaluating '_MyClass2.default.myMethod("987")'

What am I doing wrong? Also, what do the _, 2, and default mean in the error message next to my class name?

A: That's because you've created an instance method, so you have two options. Either create an instance of that class:
var c = new MyClass();

c.myMethod();

Or set that as a static method:
static myMethod(code) {
  // ...
}

Another way is to export the functions directly:
export myMethod(code) {
  // ...
end

A: When declaring a JS Es6 class, remember that its method members are bound to each instance of the class or bound to the class itself if you used the static keyword :
class MyClass {

     myMethod() {

         // each object created with the *new* keyword will have this method:
         // const o = new MyClass();
         // typeof o.myMethod === "function" will return true
     }

}

class MyClass {

     static myMethod() {

         // typeof MyClass.myMethod === "function" will return true

     }

}

Depending of its declaration, when invoked its lexical context this will either be bound to the instance (first case) or the class itself (2nd form).
You should also now that all instance methods (like the second case) are put inside the prototype property of you class. So you have :
class MyClass () {

    myMethod() {}

}

(typeof MyClass.protototype.myMethod === "function") // true

const o = new MyClass()

(o.myMethod === MyClass.prototype.myMethod); // true

For static methods (or class methods) the method is directly attached to the class object.
The error you see in your case is caused because your method was not declared with the static keyword.

A: You need to declare an object of your class before start calling its methods just like in any other programming languages.
export class MyClass {

    public myMethod(code){
        console.log("The code is" + code)
    }
}

Then import it wherever you want to use
import MC from './MyClass'

Create an object from your import and call the method
var mc = new MC();
mc.myMethod("987");


text:
Q: Count occurunces of a value up to each row I have a sheet like this
   Name     case_type    Count
1  vijam    X            1
2  vijam    X            2
3  vijam    X            3
4  vijam    Y            4
5  vijam    X            5
6  vijam    X            6
7  vijam    X            7
8  vijam    X            8
9  vijam    X            9
10 vijam    Y            10

where the cells in column Count are produced by the formula
=COUNTIF($A$2:$A2,$A2)

but I want the data to be counted for each case type. For example, in the fourth row, the count should be 1 for case type Y. How can I do this?
I want to do this so I can get 15th & 40th case of each category for sample quality checks.

A: If you want to count values in more than one column,
use COUNTIFS:
=COUNTIFS($A$2:$A2,$A2, $B$2:$B2,$B2)

A: Try to use SUMPRODUCT function:
C2: =SUMPRODUCT(($B$2:B2=B2)*($A$2:A2=A2))


text:
Q: Detecting cellular network using connman I am using connman as my network manager. i have plugin a Airtel LTE(Huawei E-382) dongle to my system(ubuntu 12.04).It is working perfectly fine and output of ifconfig showing eth0, wlan0 and ppp0(for this dongle) as interfaces. but while listing technology using connman-
./connmanctl technologies, only ethernet, bluetooth and wifi technologies is visible. i could not find cellular network.
my connman version is 1.15.
if any one have any idea pls share.
thanks!


text:
Q: Query to fetch data from array_aggregate I have column with data in array.
Alphabets
{A,B,C}
{A}
{B,C}

I need a query which gives me output as A for {A}

A: WITH
dataset AS (
  SELECT ARRAY
  [
    ARRAY[1,2,3,4],
    ARRAY[5,6,7,8],
    ARRAY[9,0]
  ] AS items
),
item AS (
  SELECT i AS array_items
  FROM dataset, UNNEST(items) AS t(i)
)
SELECT array_items, sum(val) AS total
FROM item, UNNEST(array_items) AS t(val)
GROUP BY array_items;

In the last SELECT statement, instead of using sum() and UNNEST, you can use reduce() to decrease processing time and data transfer, as in the following example.
WITH
dataset AS (
  SELECT ARRAY
  [
    ARRAY[1,2,3,4],
    ARRAY[5,6,7,8],
    ARRAY[9,0]
  ] AS items
),
item AS (
  SELECT i AS array_items
  FROM dataset, UNNEST(items) AS t(i)
)
SELECT array_items, reduce(array_items, 0 , (s, x) -> s + x, s -> s) AS total
FROM item;

Either query returns the following results. The order of returned results is not guaranteed.
+----------------------+
| array_items  | total |
+----------------------+
| [1, 2, 3, 4] | 10    |
| [5, 6, 7, 8] | 26    |
| [9, 0]       | 9     |
+----------------------+

reference:
https://docs.aws.amazon.com/athena/latest/ug/arrays-and-aggregation.html


text:
Q: Choosing CMS vs Portal vs MVC+Components? I need some help figuring out whether it'd be a good idea to use a CMS or portal solution for my latest project, which is (currently) an ASP.NET MVC application that must serve multiple customers (being a company or some other entity with a list of users) from a single installation (that is, a SaaS solution).
In addition to the core functionality, which includes document management/publishing, I also need to provide basic social features (such as blog, forum, gallery, polls, etc.). However, it is imperative that content is only visible for the customer to which it belongs, and my evaluation of a bunch of CMS and portal solutions has shed little light on whether they support this. They're pretty focused on single-user installations, and documentation on how to integrate with an existing MVC solution is pretty thin.
Essentially I'm looking for some guidance to help me discard dead-end options (the product does not meet requirements, imposes too many restrictions, is not mature, etc.) and find unexplored options before getting too far ahead with the project.
My requirements for the architecture include:

*

*Multi-site support (using a single domain for hosting)

*

*Watertight separation of content between customers

*Full integration across components/features

*

*SSO (single-sign-on)

*Single-site experience (shared header/footer, unified navigation, unified tags, etc.)

*Ease of development and deployment

*

*Custom logic will be written using C# and ASP.NET MVC and any products should support this

*I want to stay in control

*

*Solution should offer features but otherwise stay out of the way (for example, not force stupid idioms on me, like insisting on GUIDs for primary keys)

*Active development community

*

*No single-man efforts

*Recent source control activity

*Reasonable levels of documentation and maturity

*Does not have to be open source

I have spent a fair amount of time evaluating products and components, which I'll briefly share here:

*

*Umbraco

*

*Does not support ASP.NET MVC (yet, as someone is bound to otherwise comment)

*Great community support, active development

*Seems to be lots of work to get started

*Kooboo

*

*No source activity (no updates for almost two months)

*GPL licensed? (need something that allows for closed source applications)

*N2CMS

*

*Partial ASP.NET MVC support

*Every customer must have a separate domain

*Limited source activity (not dead but not vibrant either)

*Orchard

*

*Microsoft-sponsored (which means it's likely to be over-architected, code-bloated and slow, although it does have some well known and respected contributors/leads)

*Built using ASP.NET MVC

*Looks promising feature-wise (but is unlikely to be stable at this stage)

*AtomSite

*

*Feels reasonably mature and has decent documentation, albeit with holes

*Built using ASP.NET MVC

*Limited source activity, single developer

*MojoPortal

*

*Looks good for a portal, but probably requires custom logic to be built as modules around the product (I was hoping to avoid that kind of lock-in if possible)

*DotNetNuke (DNN), CommunityServer and Microsoft Office SharePoint Server (MOSS)

*

*Definitely not my cup of tea ;)

*BlogEngine.NET

*

*Mature and feature-complete

*No ASP.NET MVC support

*Integration possible but not without lots of Web.config voodoo

*Not sure if it supports customer separation

Given the list above I'm leaning towards AtomSite, N2CMS, Orchard or BlogEngine.NET. If I go with the latter I'll be using jitbit AspNetForum, which is a great match for my needs.
I'd probably prefer to use a custom ASP.NET MVC solution and individual components as this is likely to give me the greatest amount of control, but on the other hand, it'll make site theming and integration harder. What combinations have you tried, what worked well and what didn't? Anything important I'm leaving out of my evaluation? Any other relevant advice?
I'd appreciate it if the answers were not simply endorsements of your favorite product or way of doing things, but something that would help me choose or eliminate solution candidates given the requirements outlined above.

A: With the level of requirements you've specified, I'm personally going to have to lean towards the custom approach. You can hire someone to do the design (view) portion of the site for you, or you can buy a theme off the internet from site designers and customize it to your liking. (Sometimes just having somewhere to start is enough for intermediate level customization).

*

*Multi-site support (using a single domain for hosting)

*

*You're probably going to want to have control of your hosting environment, either a VPS (Virtual Private Server) or a dedicated box. This is still possible on shared hosting but not reccomended.

*Watertight separation of content between customers

*

*You'd probably have to spawn a unique app-pool for each customer with thier own services user for 100% seperation.

*Full integration across components/features / SSO (single-sign-on) /Single-site experience (shared header/footer, unified navigation, unified tags, etc.)

*

*This is going to be the tricky part. This Example may have some useful insight for you in the development process, but you're going to want a unified login service and have all sites use it or link to it.

*Ease of development and deployment

*

*This is where it gets tricky. Development ease comes from your background I think. MVC is definately the right choice in this respect then, knowing a lot about the right ways of going about building a site in MVC will aid in this process. Keep up to date by reading community blogs and listening to podcasts like Hanselminutes or DotNetRocks will help keep you in touch with the newest and greatest tools/technologies for making your site get off the ground quickly and effectively.

*Deployment is the tricky spot. MSDeploy still isn't quite there. But if you can you probably will want to come up with a Dev -> Staging -> Release publish structure so you can test your code in a staging (mimiced production) environment.

*Custom logic will be written using C# and MVC and any products should support this
I want to stay in control

*

*If you develop the site in ASP.NET-MVC, you'll be able to build common libraries that you can use not just in your site, but also in your custom tooling. This will greatly reduce your code duplication and helps make sure operational unity is achieved. (Everything works the same way).

*Solution should offer features but otherwise stay out of the way (e.g. not force stupid idioms on me, like insisting on GUIDs for primary keys)

*

*While you'll have control in this situation, I'd strongly reccomend GUID Primary Keys. This allows Merge Replication, which can help you easily restore backups or use failover DB servers when things go awry.

*Active development community

*

*.NET has a great community out there, (including this one) and you should get lots of support if you ask for it politely.

*No single-man efforts

*

*Not sure what you mean here, You'd be the Single-Man unless you hire help, but even 2 people can do great things given a little time. Even one-man can do great things, but the framework you're running on here is backed by a commercially funded huge team.

*Recent source control activity

*

*Doesn't really apply to .NET, but a lot of the libraries that you may use (NHibernate, MVC Contrib, AutoFac, Etc...) will have lots of activity and constantly being improved.

*Reasonable levels of documentation and maturity

*

*.NET and most of the production level libraries developed for .NET (Mentioned above) actually have a pretty good degree of documentation. There's multiple paid & non-paid sources of information for .NET alone, and most libraries (are well supported by the community and known on StackOverflow)

*Does not have to be open source

*

*Look for support libraries that are LGPL (i.e. you can use it in commercial software, but if you modify the library you have to release the new library code if you release the binary.) You're pretty safe here, your site dosen't have to be open source if you use these libraries to support your development.

Well, that's my 2cents. The project you've described is no small job, you're looking at a considerable amount of work even if you go with a pre-built solution (mainly hacking it to work the way you want). I imagine your biggest hangups would be SSO & Security for the pre-done solutions. Not to say it's impossible, just tricky and the end result may not be exactly what you're looking for.
Also, look into OpenID, it may be the best solution for linking all your sites together and most pre-built systems can easily be ported to use it.

A: Take another look at MojoPortal. The CMS is awesome and the main developer , Joe Audette, is very responsive. I'm have several installations of the CMS running single and multiple sites.

A: I would lean towards a CMS based solution. Having a tested and production ready software not only reduces the development time but also helps in continuous upgrade and reduced bug count.
If you go down this route, you may want to also consider Sitefinity. Not only does it support all the features required by you, but also is built on .NET and supports MVC development. The product is built by Telerik, the makers of UX tools.
Disclaimer: I am employed by Telerik.

A: I've recently come across phpFox which is a social networking/forums/community site CMS. This may be of use to you and is fairly inexpensive.

A: The solution for the site of our company has become EBIZ CMS: full-featured site that includes social networking, online store, features a presentation, a forum, create HTML pages and much more, including the maintenance of professional technical support, so we do not even need help for installing by a programmer, and it is only US$ 9/month!


text:
Q: How to remove space in CarouselView (CarouselView inside ScrollView) I use CarouselView inside ScrollView because I only want CarouselView to bind Imgae only. More info shows up as I scroll the page. I don't want to Binding other information inside CarouselView because I only want other information to display outside CarouselView.
<ScrollView VerticalOptions="FillAndExpand" VerticalScrollBarVisibility="Never" HorizontalScrollBarVisibility="Never" HorizontalOptions="FillAndExpand">
<StackLayout Padding="0" Margin="0">
    <StackLayout Padding="0" Margin="0">
        <CarouselView IndicatorView="indicatorView"
                ItemsSource="{Binding ProductInfo.ProductImages}">
            <CarouselView.ItemTemplate>
                <DataTemplate>
                    <StackLayout Padding="0" Margin="0" BackgroundColor="#fff">
                        <Frame HasShadow="False" Padding="0" Margin="15,0" CornerRadius="7" IsClippedToBounds="True">
                            <control:AspectRatioContainer AspectRatio="1">
                                <Image HorizontalOptions="Fill"  Aspect="AspectFill" Source="{Binding Images}"/>
                            </control:AspectRatioContainer>
                        </Frame>
                    </StackLayout>
                </DataTemplate>
            </CarouselView.ItemTemplate>
        </CarouselView>
        <StackLayout Margin="0">
            <IndicatorView x:Name="indicatorView"
                IndicatorColor="#ddd"
                Margin="0,-100,0,0"
                Padding="0"
                BackgroundColor="Transparent"
                SelectedIndicatorColor="#333"
                HorizontalOptions="Center"
                IndicatorSize="5"/>
        </StackLayout>
    </StackLayout>
    <StackLayout Padding="15" Margin="0,0,0,5" BackgroundColor="#fff">
        <Label Text="{Binding ProductInfo.Name}" FontFamily="{StaticResource QuicksandBold}" FontSize="16" HorizontalTextAlignment="Start" TextColor="#333"/>
        <StackLayout>
            <Label TextType="Html" Text="{Binding ProductInfo.ContentsSmall}" HorizontalOptions="Start" HorizontalTextAlignment="Start" FontFamily="{StaticResource QuicksandRegular}" FontSize="13" TextColor="#333"></Label>
        </StackLayout>
    </StackLayout>
</StackLayout>
</ScrollView

However I want to remove the whitespace below.

Please help me any solution except setting HeightRequest of CarouselView. Tks!

A: Since the image is square , we just need to let the height equal to the width on CarouselView , so we can bind HeightRequest with a value(screen width) .
Xaml
 <CarouselView x:Name="cView" IndicatorView="indicatorView" HeightRequest="{Binding ScreenWidth}">

Code behind

public double ScreenWidth { get; set; }
public Page1()
{
    InitializeComponent();
    var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
    ScreenWidth = mainDisplayInfo.Width/mainDisplayInfo.Density;
    this.BindingContext = this;
}


text:
Q: pentesting on IOS 13.5 Iphone device : dump of keychain though Objection I am actually doing some penetration testings and security research on a jailbroken IOS 13.5 Iphone XR, and have some specific questions on how the "keychain-2.db" database and its encryption works.
The phone I use is a IOS 13.5 jailbroken devices, so I manage to get into it through SSH or a tool called "Objection" which a tool to do multiple security things on to a IOS device (More on Objection >> https://sudonull.com/post/8652-iOS-runtime-mobile-exploration-with-Objection-or-Hack-own-application)
The purpose of my tests is to have a look if  I could find some passwords, sensitives infos, for a specific application installed on this device.
I did dump the database called keychain-2.db with objection and kind of export it to a json or txt file.
I can perfectly open it (as a text file), but when I get a closer look at it in some "field" called "data" or "dataHex" I can't find any password (happily) but the data inside seems to be like base64 encoded, when I try to decode it, nothing really comes.
So my question is: is the data inside this keychain-2.db database, once dumped, encoded in some base64 style ? or what is the mecanism in play fort this encryption / encoding ?
it looks like this :
"data": "XXXXXXXXXxxxxxkhkjh/xxxxxxxxxAAAAAAAAAApO8M5DUaQDfk=",
"dataHex": "4d6271724443434XXXXXXXXXXXX=",

Any help, or discussion about this security point is welcome; thanks.


text:
Q: How to kill alert box in Chrome developers tools? example js:
How to kill alert box in chrome developers tools?
in content_scripts -> content.js
window.onload = function () {
   window.alert = function () {}
}

but there not effect,help me.

A: manifest.json
  "content_scripts": [
    {
      "matches": [
        "http://elearn.ecust.edu.cn:86/*"
      ],
      "js": [
        "inject.js"
      ],
      "run_at": "document_start",
      "all_frames": true
    }
  ],

inject.js
window.addEventListener("DOMContentLoaded", function () {
    console.log("----加载inject.js---DOMContentLoaded")
    window.alert = function () { }
    overrideSelectNativeJS_Functions()
})

window.addEventListener("load", function () {
    console.log("----加载inject.js---load")
    window.alert = function () { }
    overrideSelectNativeJS_Functions()
})
window.addEventListener("beforeunload", function () {
    console.log("----加载inject.js---beforeunload")
    window.alert = function () { }
    overrideSelectNativeJS_Functions()
})
window.addEventListener("unload", function () {
    console.log("----加载inject.js---unload")
    window.alert = function () { }
    overrideSelectNativeJS_Functions()
})

addJS_Node(null, null, overrideSelectNativeJS_Functions);

function overrideSelectNativeJS_Functions() {
    window.alert = function alert(message) {
        console.log(message);
    }
}

function addJS_Node(text, s_URL, funcToRun) {
    var D = document;
    var scriptNode = D.createElement('script');
    scriptNode.type = "text/javascript";
    if (text) scriptNode.textContent = text;
    if (s_URL) scriptNode.src = s_URL;
    if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
    targ.appendChild(scriptNode);
}