text:
Q: .obj/.gltf 3D model won't show in ARCore I followed a tutorial online to create an AR app that could show my 3D models in AR.
I put my .obj and .gltf 3d model files in my assets folder,
when the I tap on a plane, the method placeObject() should run and put my model (selectObject) on the place.
but when I test it on my phone,after the plane was detected and I tapped the screen, nothing happened, I checked my logcat and it shows the error when I tapped:
2021-11-04 01:55:46.629 11172-12363/com.example.arcoretest E/ModelRenderable: Unable to load Renderable registryId='testscene.obj'
    java.util.concurrent.CompletionException: java.lang.AssertionError: No RCB file at uri: testscene.obj
        at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:278)
        at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:284)
        at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1629)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:920)
     Caused by: java.lang.AssertionError: No RCB file at uri: testscene.obj
        at com.google.ar.sceneform.rendering.LoadRenderableFromSfbTask.byteBufferToSfb(LoadRenderableFromSfbTask.java:191)
        at com.google.ar.sceneform.rendering.LoadRenderableFromSfbTask.lambda$downloadAndProcessRenderable$0$com-google-ar-sceneform-rendering-LoadRenderableFromSfbTask(LoadRenderableFromSfbTask.java:121)

I'm not sure where the problem is, is it my uri is wrong or I should use other 3d model format?
(I tried .obj/.fbx/.gltf but none of them worked)
(I can't use .sfb or .sfa ,I can no longer use sceneform plugin  to convert files into sfa/sfb because it was deprecated)
here is my grade dependencies:
{
implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.15.0'
implementation 'com.google.ar:core:1.15.0'
implementation 'com.google.ar.sceneform:assets:1.15.0'
...
}
My mainActivity.java:
package com.example.arcoretest;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;

import com.google.ar.core.Anchor;
import com.google.ar.core.HitResult;
import com.google.ar.core.Plane;
import com.google.ar.sceneform.AnchorNode;
import com.google.ar.sceneform.rendering.ModelRenderable;
import com.google.ar.sceneform.rendering.Renderable;
import com.google.ar.sceneform.ux.ArFragment;
import com.google.ar.sceneform.ux.TransformableNode;

public class MainActivity extends AppCompatActivity {
    private ArFragment fragment;
    private Uri selectObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        selectObject = Uri.parse("testscene.obj");

        fragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.sceneFormFragment);

        //when tapped on a plane, code below will run
        fragment.setOnTapArPlaneListener(
                (HitResult hitResult, Plane plane, MotionEvent motionEvent)->{
                    Anchor anchor = hitResult.createAnchor();
                    placeObject(fragment,anchor,selectObject);
                }
        );
    }

    //this method put 3d model in scene
    private void placeObject(ArFragment fragment, Anchor anchor,Uri model){
        ModelRenderable.builder()
                .setSource(fragment.getContext(),model)
                .build()
                .thenAccept( renderable -> addNodeToScene(fragment,anchor,renderable))
                .exceptionally((throwable -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setMessage(throwable.getMessage())
                            .setTitle("Error!");
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    return null;
        }));
    }
    private void addNodeToScene(ArFragment fragment, Anchor anchor, Renderable renderable){
        AnchorNode anchorNode = new AnchorNode(anchor);
        TransformableNode node = new TransformableNode(fragment.getTransformationSystem());
        node.setRenderable(renderable);
        node.setParent(anchorNode);
        fragment.getArSceneView().getScene().addChild(anchorNode);
        node.select();
    }

}

and I put my 3d model files in assets folder like this:

A: I would recommend to update to the latest version of SceneForm. This is a community maintained version, with the latest dependencies of ArCore, Filament and Android. For your usecase the 3d-model-viewer sample might be interesting.


text:
Q: JSlint - make function within for loop vs. evaluating function I have a a function that looks like this:
function strip(o) {
  for (var i in o) {
        var test = basic.arr.some(function(x) {return x === i} );
              //JSlint -- don't make functions within loop
        if (test)
        delete o[i];
  }
  return o;
}

the code works and JSlint complains.
I understand that defining multiple functions with a loop' s repeating expression will end up in creating multiple functions each retaining the last repeating expression's value (because each loop doesn't have a distinct scope);
but in this case , since I'm evaluating the function right away, I can't think of a scenario where the actual value of i would change;
I've already resolved using a forEach method but would like to understand why this can eventually lead to problems.
fiddle

A: By enclosing that anonymous function declaration in for (var i in o) {, you're redefining it each time you iterate, not just once, regardless of whether or not it's "invoked immediately" -- and I'd point out your oversight of that redefinition as the reason you want to remove that construct from your code.
So you want to either get rid of for or you need to define the function earlier. I'm going to take "more" of JSLint's advice and get rid of the for as well.
This lints on JSLint.com as is:
/*jslint white:true, devel:true */
var obj = {
  a: true,
  b: true,
  c: true
};

var basic ={
    arr: ['a', 'b']
};

function strip(o) {
  "use strict";
  var test;

  Object.keys(o).forEach(function (i) {
    test = basic.arr.some(function (x) { return x === i; });
    if (test) {
      delete o[i];
    }
  });
  return o;
}
strip(obj);
console.log(obj);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I recover a single table from a SQL Server 2012 database backup I have accidentally dropped a specific table and I don't want to restore whole database (it is huge) but instead I want to recover only that table from a backup?
What would be most simplest solution?


text:
Q: Rendering array element dynamically in React Js I'm working on a React JS app. I'd like to make a selection of a letter among an array of letters, based on title + date. Then the selected letter should be displayed below. This is what I did:
class ReceivedLetters extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedLetterIndex: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    if (this.props.receivedLetters[0]) {
      this.setState({
        selectedLetterIndex: 0
      });
    }
  }

  handleChange(e) {
    this.setState({ selectedLetterIndex: e.target.value });
  }

  getListOfLetters = () => {
    var list = [];
    for (let i = 0; i < this.props.receivedLetters.length; i++) {
      list.push(
        <option value={i}>
          {this.props.receivedLetters[i].mailingDate}
          {this.props.receivedLetters[i].title} {i}
        </option>
      );
    }
    return list;
  };

  render() {
    return (

          Select the letter:
          <select onChange={this.handleChange} class="form-control" id="sel1">
            {this.getListOfLetters()}
          </select>

          my index is = {this.state.selectedLetterIndex} {/*THIS IS WORKING FINE,I CAN SELECT A LETTER AND RENDER ITS INDEX */}

          {this.props.receivedLetters[0].letterBody} {/* THIS WORKS (render bodyof letter 0)*/}
          {this.props.receivedLetters[this.state.selectedLetterIndex].letterBody } {/*SO WHY IS THIS NOT WORKING? */}

    );
  }
}

export default ReceivedLetters;

When I try to render the body of the selected letter, I got this error:

TypeError: Cannot read property 'letterBody' of undefined

Can someone help me understand what the problem is?

A: My guess is initially, before this.props.receivedLetters[0] actually has value, your component is already rendered, so you are getting this.props.receivedLetters[""].letterBody, which cause the warning. "" is the default value of your this.state.selectedLetterIndex.

A: this.state.selectedLetterIndex should initially be set to 0 not "".

A: Try to null check that state value
{this.state.selectedLetterIndex &&
 this.props.receivedLetters[this.state.selectedLetterIndex].letterBody} // SO WHY IS THIS NOT WORKING?


text:
Q: Glassfish-3.1.2 - Can I inject EntityManger into a stateless bean I came across this blog below, concerning Servlets and injecting EJBs into them.
The author is writing from a standards point-of-view.
http://tamanmohamed.blogspot.ie/2012/03/jpa-why-we-need-to-specifies-type-level.html
http://tamanmohamed.blogspot.ie/2012/03/jpa-thread-safety-when-injecting.html
"injecting EJB 3 stateful beans into servlet instance fields is not thread-safe. Along the same line, injecting EntityManager with @PersistenceContext into servlet instance variables is not thread-safe, either. EntityManager is just not designed to be thread-safe."
Anyhow, I am starting to get worried about the code I'm writing with a colleague in the
Glassfish-3.1.2  implementation.  See below.
I thought it was similar to code I've seen in Duke tutoring tutorial so it should be o.k.
(where FaceServlets call a stateless Request bean with @PersistnceContext EntityManager.)
However I guess I'm assuming the container-managed EntityManager is capable of coping
with lots of concurrent calls of a stateless bean called by many instances of servlets.
Is this a correct assumption for Glassfish-3.1.2 with an Oracle database ? It seems to work fine so far, but maybe it won't under heavy loads.
thanks in advance for any insights. Sorry I'm such a newby to this.
Fiona
Servlet
{
@EJB
private StatelessbeanBlah
:
}

@Stateless
StatelessBeanBlah
{
@PersistenceContext(unitname = "...")
private EntityManager em;

A: There is some confusion in your question, because thread-safety of EntityManager instances depend on whether you are using Container-Managed Entity Managers or Application-Managed Entity Managers. In the first case,

an EntityManager instance's persistence context is automatically
  propagated by the container to all application components that use the
  EntityManager instance within a single Java Transaction API (JTA)
  transaction.
...
By automatically propagating the persistence context, application components don't need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.

(ref. Managing Entities, Java EE 6 Tutorial)
Try to define a JTA-aware data source in your persistence.xml file, and see what happens. I am not keen in injecting a persistence context into a servlet, because when developing Java EE 6 web applications there is JSF, and you don't need to create your own servlets in most of the situations, and I am quite new to this technology, too. However, injecting a persistence context into a managed bean or an enterprise bean (like a Stateless EJB), with a JTA-aware data source, is absolutely fine and thread safe.


text:
Q: Radon-Nikodym derivative of Lebesgue measure with respect to Hausdorff measure is Jacobian term? Consider the measurable space $(\mathbb{R}^n, \mathcal{B}(\mathbb{R}^n))$ with Lebesgue measure $\lambda$. I have a submanifold of $\mathbb{R}^n$ defined as the level set of a smooth function $f:\mathbb{R}^n \to\mathbb{R}^m$ with $n > m$
$$
\mathcal{M} = \left\{x\in\mathbb{R}^n\,:\, f(x) = 0\right\}
$$
This submanifold is $n - m$ dimensional and is embedded in the ambient space $\mathbb{R}^n$. Let $\mathcal{H}$ be the Hausdorff measure on this manifold.

What is the Radon-Nikodym derivative of the Lebesgue measure with respect to the Hausdorff measure?
$$
\frac{d\lambda}{d\mathcal{H}} = ?
$$

Attempted Solution
Intuitively, I would guess this is the "jacobian term"
$$
\frac{d\lambda}{d\mathcal{H}}(x) = \left|J_f(x) J_f(x)^\top\right|^{1/2}
$$
where $J_f(x)$ is the Jacobian matrix of $f$. However I was not able to prove this. To be honest, I am not sure how generally one goes about finding a Radon-Nikodym derivative. What's the strategy one uses, given the two measures?
I know that the definition is
$$
\lambda(A) = \int_A \frac{d \lambda}{d \mathcal{H}} d\mathcal{H}
$$


text:
Q: asp.net json web service sending array error Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]' I want to insert data from JavaScript to database using ajax and webservice,
I have some controls which by jQuery I get their values and make an array of their values.
When I send the array it causes this error:

Cannot convert object of type 'System.String' to type'System.Collections.Generic.List1[System.String]'

var variables = Array();
var i=0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
    variables[i] = $(this).find('.selected').find(".text").html();
    i++;
});

$.ajax({
    type: 'post',
    data: "{ 'a':'" +variables + "'}",
    dataType: 'json',
    url: 'HomeWebService.asmx/insertAd',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {

        alert("data : " + data.d);
    }
});

This is the C# Code
[WebMethod]
public object insertAd(List<string> a)
{
    return a;
}

A: You need to make your data parameter of the $.ajax call like this: JSON.stringify({'a': variables})
The JSON variable is not available in < IE8 so you'll want to include a JSON implementation like the one mentioned in the answer here
Also, you had an extra } in the success function.
So, in the future, if you want to add extra parameters to your data object passed to the web service, you'd construct it like so:
var someArr = ['el1', 'el2'];

JSON.stringify({
  'param1': 1,
  'param2': 'two'
  'param3': someArr
  // etc
});

JavaScript:
var variables = Array();

var i = 0;
$('#Div_AdSubmition').find('.selectBox').each(function () {

  variables[i] = $(this).find('.selected').find(".text").html();

  i++;
});

$.ajax({
    type: 'post',
    data: JSON.stringify({'a': variables}),
    dataType: 'json',
    url: 'HomeWebService.asmx/insertAd',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {

      alert("data : " + data.d);
    });

});

C#
[WebMethod]
public object insertAd(List<string> a)
{
  return a;
}

A: data: Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So, try to add a new parameter to your ajax call:
$.ajax({
    type: 'post',
    data: { 'a': variables }, // Notice some changes here
    dataType: 'json',
    traditional: true, // Your new parameter
    url: 'HomeWebService.asmx/insertAd',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert("data : " + data.d);
    }
});

Try this way. Maybe you'll need to change the Web service method to expect an array instead of a List, but I'm not sure.

A: Try this
            data: JSON.stringify({ 'a': variables }),


text:
Q: Add Angular Material Ripple effect to Mat-Table on row click I am using Angular Material v6. I want to add a Ripple effect anytime that a row in my mat-table is clicked.
HTML:

  <ng-container matColumnDef="id">
    ID
    {{project.id}}
  </ng-container>

  <ng-container matColumnDef="title">
    Title
    {{project.title}}
  </ng-container>

SCSS:
table {
  width: 90vw;
  margin-top: 1%;
  margin-left: auto;
  margin-right: auto;
}

.mat-row:hover {
  background: rgba(0, 0, 0, 0.04);
}

Module Imports:
AppRoutingModule,
BrowserModule,
BrowserAnimationsModule,
MatToolbarModule,
MatSidenavModule,
MatButtonModule,
MatCheckboxModule

Custom Theme:
@import '~@angular/material/theming';
@import './palette.scss';
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// **Be sure that you only ever include this mixin once!**
@include mat-core();

// Define the default theme (same as the example above).
$light-primary-blue:    mat-palette($primary-blue);
$light-accent-purple:   mat-palette($accent-purple);
$light-theme:           mat-light-theme($light-primary-blue, $light-accent-purple);

// Include the default theme styles.
@include angular-material-theme($light-theme);

// Define an alternate dark theme.
$dark-primary: mat-palette($primary-blue);
$dark-accent:  mat-palette($accent-purple);
$dark-theme:   mat-dark-theme($dark-primary, $dark-accent);

// Include the alternative theme styles inside of a block with a CSS class. You can make this
// CSS class whatever you want. In this example, any component inside of an element with
// `.dark` will be affected by this alternate dark theme instead of the default theme.
.dark {
  @include angular-material-theme($dark-theme);
}

I can't find any documentation on adding a ripple effect to a table, but I have seen a couple Stackblitz instances that have ripple effects on row click. I tried copying what they were doing without any success.

A: Modify your td element as below.

  <ng-container matColumnDef="title">
    Title

        {{project.title}}

  </ng-container>

Style
.mat-ripple-wrapper{
   position: relative;
}

The mat-ripple directive creates a div once the trigger element is clicked which makes it fall out of place if its placed on a row. Best I can get it to work in by wrapping the td data in a div and adding the directive on that div to contain the dynamically generated div.


text:
Q: Grid search with KFold CV and Early Stopping - which validation set? I'm training a NN to solve a regression task.
I want to perform a grid search with Kfold combined with early stopping, but the only way I found is by passing a new validation set (different from the ones randomly generated by the KFold). Since I want to find the optimal hyperparameters, why doesn't early stopping monitor the validation loss of each of the splits chosen as validation set, but rather the one I've passed? Am I losing part of the dataset?
I'm following the book " Hands-on Machine Learning with Scikit-Learn, Keras, and TensorFlow Concepts, Tools, and Techniques to Build Intelligent Systems", Aurélien Géron.
Here is my code:
regressor = KerasRegressor(model=NN,
                           verbose=1,
                           n_layers=2,
                           n_units=100,
                           epochs=n_epochs,
                           decay=0,
                           momentum=0.5,
                           learning_rate=0.1,
                           reg=0.001,
                           nesterov=True,
                           callbacks=[keras.callbacks.EarlyStopping(monitor='val_loss', patience=20, min_delta=0.001, mode='min', verbose=1)]
                          )

cv = KFold(n_splits=3, shuffle=True, random_state=42)

X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=0.1, random_state=1)

rnd_search_cv = RandomizedSearchCV(regressor, param_grid, n_jobs=-1, n_iter=300,
                                 cv=cv, verbose=2, refit=False,
                                 return_train_score=True, scoring=scores)
rnd_search_cv.fit(X_train, y_train, epochs=n_epochs, validation_data=(X_valid, y_valid))


text:
Q: moodle invalid response after successful userlogin i was facing issue in moodle user was not able to logged in so i change the DB collation and user is now able to login into dashboard but i am also getting this error.

Now user is able to login but this popup error is coming.
invalidresponse
Invalid response value detected
File: /lib/externallib.php
Line: 425
Stack trace:
Error in response - Missing following required key in a single structure: tourconfig
Error code: invalidresponse
* line 425 of /lib/externallib.php: invalid_response_exception thrown
* line 250 of /lib/externallib.php: call to external_api::clean_returnvalue()
* line 59 of /lib/ajax/service.php: call to external_api::call_external_function()

A: For me, user was not able to login into Moodle and it was the dmlwrite exception. So i changed the DB collation of user table and it's started throwing an error after user logged in.
We are running this whole setup on digital ocean and due to some issue in CPU & Memory, i recycle my whole kubernetes cluster and error resolve automatically.
So as @adrian-sărmaș suggested clear cache and give it try for me maybe it was only issue of caching.


text:
Q: Spidev read/write audio codec register I am using TI816X custom platform. There is a new SPI based audio codec (ROHM BU76312) device on my platform. I cannot find Linux driver of this codec. Thus, I want to write userspace SPI driver to control this audio codec.
I had created /dev/spidev1.2 node in kernel. But I don't know how to use spidev read/write to control this audio codec. This photo list some register of this audio codec: https://dl.dropboxusercontent.com/u/27415803/photo/rohm_bu76312.jpg
If I want to write 00H/01H register, then read it back, how can I do?
This is my test program, but I don't know how to write register read/write program to control this audio codec based on spidev read/write function.
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define ARRAY_SIZE(array) sizeof(array)/sizeof(array[0])
static const char *spidev = "/dev/spidev1.2";
int main(int argc, char **argv) {
    int i,fd;
    fd = open(spidev, O_RDWR);
    #if 0
    if (write(fd, wr_buf, ARRAY_SIZE(wr_buf)) != ARRAY_SIZE(wr_buf))
        perror("Write Error");
    #endif
    close(fd);
    return 0;
}

By the way, which mode should I use for this SPI based audio codec?
.mode= SPI_MODE_0 or SPI_MODE_3?
struct spi_board_info __initdata ti816x_spi_slave_info[] = {
.modalias   = "spidev",
.irq        = -1,
.max_speed_hz   = 7500000,
.bus_num    = 1,
.chip_select    = 2,
//.mode = SPI_MODE_3, //??
//.mode = SPI_MODE_0, //??
}


text:
Q: Level for questions needed: beginner, intermediate, expert
Possible Duplicates:
I am bad at answering questions on Stackoverflow.com
How about a difficulty rating for questions?

I am a new user to Server Fault and Stack Overflow. I am trying to help and answer questions, but it is difficult, because there are too many questions and it is hard to figure out which questions are answerable with my knowledge. So what about an option like "level of question". Like, beginner, intermediate, expert? I click the Java tag and so many Java questions appear. It's difficult to dig for beginners questions which I can answer.

A: And who decides the hugely subjective complexity number? Something might look like a simple question to the poster but actually be inherently complex and subtle, or it might be a nightmare to the asker (hence asking it), but actually be pretty simple or a FAQ.
Even if you're new to an area, it might easily be that this one thing that nobody else groks is the one thing you've been working at for the last 2 weeks, so you can help with despite your relative inexperience.
I just can't think of a way of making that work in practice... just hang for a little while; there will be questions you can help with.

A: For now, kick back and learn. When I first registered, I had no idea how much I was about to learn. This site works wonders for filling out knowledge, so you shouldn't feel ashamed or useless for not knowing how to answer a majority of the questions. That's normal; I learn a new thing or seventeen every day on the site.
So when a question comes up you are unsure of, pull out your favorite text editor and start working on it yourself. If you find a solution and nobody has posted it, post it! But don't be discouraged if someone beat you to the punch; take it as a learning experience.


text:
Q: Pycharm doesn't recognize existing cone env I have two env on my mac. One for 2.7 and one for 3.5. In pycharm when I try to create a new project, I'm not able to select correct environment. I am only given the option to create condo env, VM and local add.
I'm using PyCharm community edition 2016.1.3


text:
Q: curl is working but HttpClient PostAsync is not I am having trouble replicating a cUrl statement in .NET. I am working against an Oauth API (ORICD SSO), and the following curl statement worked perfectly.
curl -i -L -H "Accept: application/json" --data "client_id=APP-XXXXXXXXXXXXXXXX&client_secret=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&grant_type=authorization_code&code=VicdvK&redirect_uri=https%3a%2f%2ftst.dev.local%2fsite%2fssocallback.aspx" "https://sandbox.orcid.org/oauth/token"

I get what I need from the API. However, I can't seem to replicate that success in C#. It keeps failing with a 401 Unauthorized. In Method 1 I tried sending the data as JSON.
var postdata = new Dictionary<string, string>()
{
    { "client_id", Context.Settings.ClientId },
    { "client_secret", Context.Settings.ClientSecret },
    { "grant_type", Context.Settings.GrantType },
    { "code", Context.HttpContext.Request.Params["code"] },
    { "redirect_uri", Context.Settings.RedirectUri },
};
var jsonContent = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(postdata), Encoding.UTF8, "application/json");
var response = (new HttpClient())
    .PostAsync(Context.Settings.TokenUrl, jsonContent)
    .Result;

In Method 2 I tried using FormUrlEncodedContent and changed it up with the client to set the accept headers.
var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("client_id", Context.Settings.ClientId),
    new KeyValuePair<string, string>("client_secret", Context.Settings.ClientSecret),
    new KeyValuePair<string, string>("grant_type", Context.Settings.GrantType),
    new KeyValuePair<string, string>("code", Context.HttpContext.Request.Params["code"]),
    new KeyValuePair<string, string>("redirect_uri", Context.Settings.RedirectUri)
});
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsync(Context.Settings.TokenUrl, formContent).Result;

When that did not work, for Method 3 I built the data string manually so that it would look exactly like the curl statement from the ORCID page. I also changed up the client again, thinking that maybe there were some default accept headers messing things up.
var sb = new StringBuilder();
sb.Append("client_id=");
sb.Append(HttpUtility.UrlEncode(Context.Settings.ClientId));
sb.Append("&client_secret=");
sb.Append(HttpUtility.UrlEncode(Context.Settings.ClientSecret));
sb.Append("&grant_type=");
sb.Append(HttpUtility.UrlEncode(Context.Settings.GrantType));
sb.Append("&code=");
sb.Append(HttpUtility.UrlEncode(Context.HttpContext.Request.Params["code"]));
sb.Append("&redirect_uri=");
sb.Append(HttpUtility.UrlEncode(Context.Settings.RedirectUri));
var stringContent = new StringContent(sb.ToString(), Encoding.UTF8, "application/json");

HttpResponseMessage response;
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    using (var request = new HttpRequestMessage(new HttpMethod("POST"), Context.Settings.TokenUrl))
    {
        request.Content = stringContent;
        response = client.SendAsync(request).Result;
    }
}

All of these methods have failed. After option 3 failed, I tested with the curl statement above and it worked! The data in the curl statement above was ripped directly from the immediate window in Visual Studio from the String Builder value, so I know for sure that both of them are using the same, correct creds.
I do not know what else to test.
Note that the website I am working on is currently hosted on the same Windows 10 laptop that I ran the curl statement on.
I also tried watching the out going call with Fiddler, but it didn't pick up the POST call from my local IIS server. It would only show the browser redirects, but not the post from code.

A: I figured it out. It was close to Method 2:
HttpResponseMessage response;
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Add("Accept", "application/json");

    var formContent = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("client_id", Context.Settings.ClientId),
        new KeyValuePair<string, string>("client_secret", Context.Settings.ClientSecret),
        new KeyValuePair<string, string>("grant_type", Context.Settings.GrantType),
        new KeyValuePair<string, string>("code", Context.HttpContext.Request.Params["code"]),
        new KeyValuePair<string, string>("redirect_uri", Context.Settings.RedirectUri)
    });

    response = client.PostAsync(Context.Settings.TokenUrl, formContent).Result;
}

By default, the header for the FormUrlEncodedContent is "Content-type", "application/x-www-form-urlencoded" which is what it needed to be. Unfortunately, the documentation didn't clarify that, and I did not understand it.. until now.


text:
Q: C++ - run-time crashing of linear probing program I wrote a program in C++ for hashing using linear probing. The code is showing no error at the time of compilation but when I run it, computer shows the notification that the program has stopped working. I am giving the entire code below. Please help me out.
#include<iostream>
#include<vector>
using namespace std;
class Acc
{
    public:
        int iData;
        double dData;
        Acc(int id,double dd)
        {
            iData = id;
            dData = dd;
        }
        void displayAcc()
        {
            cout<<"iData = "<<iData<<"\n";
            cout<<"dData = "<<dData<<"\n";
        }
};
class Linear_Hash
{
    private:
        vector<Acc*> hashArray;
        int nElem;
        Acc* noElem;
    public:
        Linear_Hash(int max)
        {
            nElem = max;
            hashArray.resize(nElem);
            noElem = new Acc(-1,1.1);
            for(int i = 0;i<max;i++)
            {
                hashArray[i] = NULL;
            }
        }
        int hashfunc(int key)
        {
            return key%nElem;
        }
        void insertAcc(int id,double dd)
        {
            Acc* newacc = new Acc(id,dd);
            int hashVal = hashfunc(id);
            while(hashArray[hashVal]->iData!=-1&&hashArray[hashVal]!=NULL)
            {
                hashVal++;
                hashVal = hashVal%nElem;
            }
            hashArray[hashVal] = newacc;
        }
        Acc* search(int key)
        {
            int hashVal = key%nElem;
            while(hashArray[hashVal]->iData!=key&&hashArray[hashVal]!=NULL)
            {
                hashVal++;
                hashVal = hashVal%nElem;
            }
            if(hashArray[hashVal]->iData==key)
            {
                return hashArray[hashVal];
            }
            else
                return NULL;
        }
        bool deleteAcc(int key)
        {
            int hashVal = hashfunc(key);
            while(hashArray[hashVal]->iData!=key&&hashArray[hashVal]!=NULL)
            {
                hashVal++;
                hashVal = hashVal%nElem;
            }
            if(hashArray[hashVal]==NULL)
                return false;
            else
            {
                Acc* pTemp = hashArray[hashVal];
                hashArray[hashVal] = noElem;
                delete pTemp;
                return true;
            }
        }
};
int main(void)
{
    int key;
    char val;
    Linear_Hash lh(20);
    lh.insertAcc(100,100.1);
    lh.insertAcc(204,204.204);
    lh.insertAcc(105,105.10);
    lh.insertAcc(237,348.23);
    lh.insertAcc(209,923.23);
    lh.insertAcc(230,230.23);
    lh.insertAcc(403,348.34);
    lh.insertAcc(405,938.50);
    lh.insertAcc(450,348.23);
    lh.insertAcc(945,495.409);
    while(val!='x')
    {
        cout<<"Enter the key to be searched\n";
        cin>>key;
        if(lh.search(key)==NULL)
            cout<<key<<" could not be found\n";
        else
            lh.search(key)->displayAcc();
        cout<<"Enter the key to be deleted\n";
        cin>>key;
        if(lh.deleteAcc(key))
            cout<<key<<" has been deleted\n";
        else
            cout<<"Invalid request\n";
        cout<<"Do you want to continue\n";
        cin>>val;
    }
    return 0;
}

I am unable to use the debugger in this case as I don't know where the error is. I have also tried dry-running it on paper but wasn't able to pin point the bug.

A: Near the top of main you do this:
Linear_Hash lh(20);
lh.insertAcc(100,100.1);

The first line sets up the vector:
for(int i = 0;i<max;i++)
{
    hashArray[i] = NULL;
}

So, before the second line you have a vector of NULLs.
The second line then does this:
    Acc* newacc = new Acc(id,dd);
    int hashVal = hashfunc(id);
    while(hashArray[hashVal]->iData ...

So, hashArray contains NULLS, then you try to look at hashArray[hashVal]->iData i.e.
NULL->iData

You should check hashArray[hashVal]!=NULL before you try to do anything with it.


text:
Q: Does ipad app with only landscape mode will be accepted by apple or not I have app in which i have used rotation for the app fixed to landscape apple will accept the app or not.

A: Yes. Why not. You can develop app for one orientation.


text:
Q: Magento edit PDF renderer for configurable and bundle products I want to edit the way the invoice looks and followed the advice available here https://magento.stackexchange.com/questions/41650/how-to-change-pdf-invoice-layout and here https://www.hummingbirduk.com/remove-tax-pdf-invoices-magento/.

*

*Magento version is 1.9.3.7

*I am not looking for modules that modify the invoice look.

What I want is to realign the columns and make the TAX column dissapear. I managed to do so for simple products.
The problem is that configurable and bundle products still show the components with tax column included and the others are still displaced.

code/local/mage/sales/model/order/pdf/Invoice.php ( commenting the lines starting at line 77)

$lines[0][] = array(
            'text'  => Mage::helper('sales')->__('Tax'),
            'feed'  => 495,
            'align' => 'right'
        );

will hide the header label which is ok.

code/local/mage/sales/model/order/pdf/Items/Invoice/Default.php (commenting this fragment starting at line 106)

$lines[0][] = array(
            'text'  => $order->formatPriceTxt($item->getTaxAmount()),
            'feed'  => 495,
            'font'  => 'bold',
            'align' => 'right'
        );

will make tax field to be hidden for simple products, yet not for those from the simple products that are components of the bundle/configurable.
The problem is that neither of these files is responsible for the way the configurable and bundle are rendered in the PDF invoice.

What I could identify is that these kind of products are rendered using this function in

code/local/mage/sales/model/order/pdf/Abstract.php (line 760)

protected function _drawItem(Varien_Object $item, Zend_Pdf_Page $page, Mage_Sales_Model_Order $order)
    {
        $orderItem = $item->getOrderItem();
        $type = $orderItem->getProductType();
        $renderer = $this->_getRenderer($type);

        $this->renderItem($item, $page, $order, $renderer);

        $transportObject = new Varien_Object(array('renderer_type_list' => array()));

        Mage::dispatchEvent('pdf_item_draw_after', array(
            'transport_object' => $transportObject,
            'entity_item'      => $item
        ));

        foreach ($transportObject->getRendererTypeList() as $type) {
            $renderer = $this->_getRenderer($type);
            if ($renderer) {
                $this->renderItem($orderItem, $page, $order, $renderer);
            }
        }

        return $renderer->getPage();
    }

Yet I cannot find where the renderers for configurable are defined.

A: Copy files to

local/Mage/Bundle/Model/Sales/Order/Pdf/Items

from

core/Mage/Bundle/Model/Sales/Order/Pdf/Items

In Invoice.php comment lines 146&147
$tax = $order->formatPriceTxt($_item->getTaxAmount());
$line[] = array('text'  => $tax,'feed'  => 495,'font'  => 'bold',    'align' => 'right');


text:
Q: Prove that the number of subgroups of $G$ with order $p^r$ is equivalent to $1 \pmod{p}$ by using group action.
Claim. Let $G$ be a group, $p$ be a prime number and $r \in \Bbb{N}$ such that $p^r$ divides $|G|$. If $n_G(p^r)$ is the number of subgroups of $G$ with order $p^r$. Show that $n_G(p^r) \equiv 1 \pmod{p}$.

I'm trying to proof this claim using group action. My professor gave me some hints, but I could not see some implications. I will to write a sketch of my attempt.
Sketch. Let $|G| = p^rm$ and $A$ the set
$$A = \{S \subset G \mid |S| = p^r\}.$$
The map $g\cdot S = gS$ is an action of $G$ on $A$. Let $T \subset A$, then
$$orb_G T = \{g\cdot T \mid g \in G\}.$$
There is $S \in (orb_G T)\cap A$ with $e \in S$. Define the action of $stab_G S$ on $S$ by $g \cdot s = gs$.

There is $k \leq r$ such that
  $$|stab_G S| = p^{k}\tag{1}$$

and so,
$$|orb_G S| = p^{r-k}m.$$
Also,
$$|orb_G S| = m \Longleftrightarrow S \leq G.$$
Therefore, $n_G(p^r)$ is the number of orbits of lenght $m$.

By the Conjugacy Class Equation
  $$|A| \equiv n_G(p^r)m\pmod{pm}.\tag{2}$$

From now on I think I can finish.

My problem is to justify $(1)$ and $(2)$. Thanks for the advance!

A: For the claim $(1)$, observe that $\text{Stab}_G(S)$ is a subgroup of $G$ and $\lvert G \rvert = p^r$. Hence $\lvert \text{Stab}_G(S) \rvert =p^k$ for some $k \leq r$ by Lagrange's theorem.
For the claim $(2)$, note that all orbits have size $p^{r-k}m$, so they are divisible by $pm$ unless their size is $m$. You have observed that this happens exactly when $S$ is a subgroup of $G$ and there are $n_G(p^r)$ subgroups. The union of orbits is $A$ proving the claim.


text:
Q: jquery ajax Reloading part of a page returning undefined I'm trying to reload a section of a page:
function LoadAssets() {
  console.log($('#AssetResults').html());
  $.ajax({
    url : 'Assets_Home.cfm',
    type : 'POST',
    success : function(data) {
      console.log($(data).find('#AssetResults').html());
      $("#AssetResults").html($(data).find('#AssetResults').html());
    }
  });
}

Where Assets_Home.cfm is the current page. Data returns the page correctly, $(data) looks like this in the console:
w.fn.init(38) [text, comment, text, script, text, meta, text, link, text, script, text, script, text, script, text, script, text, link, text, link, text, link, text, link, text, title, text, style, text, div#NavigationBar, text, comment, text, div, text, div#AssetResults, text, script]

And $(data).find('#AssetResults').html() is undefined.
Am I not selecting it right?

A: find() searches the contents of elements, but it doesn't find the top-level elements themselves. So you need to wrap the returned value in another element.
var div = $("<div>", { html: data });
var assetResults = div.find("#assetResults").html();

You could also use the .load() method, which allows you to put a selector in the URL.
$("#AssetResults").load('Assets_Home.cfm #AssetResults');


text:
Q: need help in writing an sql query I have this tables in sql
Genre: genreCode, genreName
Movie: movieCode, movieName, duration, director, publishDate
Copy: movieCode , copyNum
Belongs: movieCode, genreCode
Language: languageNum, languageName
CopiesInLanguages: movieCode, copyNum, languageNum
how can i get all genres that have movies in all languages in the system?
thanks for your help :)

A: Do you need below  -
SELECT genreName, COUNT(movieCode)
  FROM Belongs B
  JOIN Genre G ON B.genreCode = G.genreCode
  JOIN CopiesInLanguages CL ON B.movieCode = CL.movieCode
 GROUP BY movieCode
HAVING COUNT(movieCode) = (SELECT DISTINCT COUNT(languageNum)
                             FROM Language)


text:
Q: Basic arithmetic with matrices round two We have matrices. (Same matrices as in post earlier).
You can find earlier post from here.
$$A=\begin{bmatrix}
-2 & 0 \\
-5 & 6 \\
\end{bmatrix}\\
B^{-1}=\begin{bmatrix}
-7 & 8 \\
2 & -8 \\
\end{bmatrix}\\
C=\begin{bmatrix}
-15 & -2 \\
-8 & -14 \\
\end{bmatrix}
$$
I would like to solve $X$ from this equation
$$CX=-6X+I$$
$$CX+6X=I$$
$$X(C+6)=I$$
Multiplying both sides with $(C+6)^{-1}$
$$XI=I(C+6)^{-1}$$
$$X=(C+6)^{-1}$$
Is this correct ?
$$X=(\begin{bmatrix}
-15 & -2 \\
-8 & -14 \\
\end{bmatrix}+6)^{-1}$$
$$X=(\begin{bmatrix}
-9 & -2 \\
-2 & -8 \\
\end{bmatrix})^-1$$
$$X=\begin{bmatrix}
-\frac{2}{17} & \frac{1}{34} \\
\frac{1}{34} & -\frac{9}{68}
\end{bmatrix}$$


text:
Q: Rails scope doesn't return correct data When I use scope which I prepared in model, rails returns incorrect data.
My Model:
class CurrencyRate < ActiveRecord::Base
    scope :eur_today, -> {where(currency: "eur").where(date: Time.now.in_time_zone.to_date).first}
end

Inforamation from rails console:
2.3.0 :011 > CurrencyRate.eur_today

CurrencyRate Load (0.2ms)  SELECT  "currency_rates".* FROM
"currency_rates" WHERE "currency_rates"."currency" = ? AND
"currency_rates"."date" = ?  ORDER BY "currency_rates"."id" ASC LIMIT 1
[["currency", "eur"], ["date", "2017-08-09"]]
CurrencyRate Load (0.2ms)  SELECT "currency_rates".* FROM
"currency_rates"

 => #<ActiveRecord::Relation [#<CurrencyRate id: 2, currency: "eur",
 sale: 4.248546249999998, purchase: 4.265333125, date: "2017-08-08",
 created_at: "2017-08-08 20:52:08", updated_at: "2017-08-08 20:54:10",
 sale_percentage_diff: nil, purchase_percentage_diff: nil>]>

When I use the same query like in scope, returned data is correct:
2.3.0 :012 > CurrencyRate.where(currency: "eur").where(date: Time.now.in_time_zone.to_date).first

CurrencyRate Load (0.2ms)  SELECT  "currency_rates".* FROM
"currency_rates" WHERE "currency_rates"."currency" = ? AND
"currency_rates"."date" = ?  ORDER BY "currency_rates"."id" ASC LIMIT 1
[["currency", "eur"], ["date", "2017-08-09"]]

=> nil

Why scope doesn't work correct?

A: Because scopes must return an ActiveRecord::Relation. Get rid of the first call in your scope and use that outside the scope. Why? Because scopes have to be chainable.


text:
Q: Трансформирование элемента с помощью css transform (rotate) и его финальное положение на странице При трансформировании элемента, например, повороте на 90%, элемент поворачивается от своего центра.
Вопрос: как повернуть элемент, чтобы его прибило к краю блока?

A: В общем ...применил flexbox, в  котором стилизуем положение текста и линии с одного разрешения на другое через order, а положение родительского блока при вёрстке само по себе имеет позицию в самом верху слева ...
Если нам потребуется с десктопной версии перевернуть блок т.е сделать его вертикальным нам не надо поворачивать или ещё что то а просто указать width и height который требуется
Здесь полный эксперимент + 100% рабочая версия: https://codepen.io/topicstarter/pen/drZKEX

.item {
  display: inline-block;
  background: red;
  text-align: center;
  padding: 10px;
}

.item div:first-child {
  display: inline-block;
  text-align: center;
  margin-bottom: 20px;
  height: 50px;
  width: 2px;
  background: #fff;
}

.item div:last-child {
  writing-mode: vertical-rl;
  color: #FBFBFB;
  font-size: 20px;
}

@media(max-width:768px) {
  .item {
    display: flex;
    flex-direction: column;
    width: 18px;
    align-items: center;
  }
  .item div:first-child {
    order: 2;
    margin-top: 20px;
  }
  .item div:last-child {
    order: 1;
  }
}
<meta name="viewport" content="width=device-width, initial-scale=1.0">

о компании


text:
Q: Python "REPLACE" command in a SQL query(Error message) I am new in python and I need this query to check my database if it is working. There are lots of queries but it is only one of them.
import pyodbc
db_file = 'C:\\Users\\****\\Desktop\\bbbb.mdb' #define the location of your Access file
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s' %(db_file) # define the odbc connection parameter
conn = pyodbc.connect(odbc_conn_str)
cursor = conn.cursor() # create a cursor
sql_update_statement = "UPDATE NUMARATAJ SET KAPINUMERIK = IIf (ISNUMERIC (LEFT (REPLACE(KAPINO,'-','/'),4)=-1),LEFT(KAPINO,4))" # edit the SQL statement that you want to execute
cursor.execute(sql_update_statement) # execute the SQL statement
cursor.commit()
cursor.close()
conn.close()

When I try to run this code it says;
  File "C:\Users\****\Desktop\aa2a.py", line 9, in <module>
    cursor.execute(sql_update_statement) # execute the SQL statement
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Sürücüsü] Undefined 'REPLACE' function in the expression. (-3102) (SQLExecDirectW)")

How can I fix it, or get it work, can you help me?

A: It could be:
sql_update_statement = "UPDATE NUMARATAJ SET KAPINUMERIK = LEFT(KAPINO,4) WHERE ISNUMERIC(LEFT(REPLACE(KAPINO,'-','/'),4)"

However, Replace is a VBA function, not Access SQL, so that is probably why you receive the error.
Try simply:
sql_update_statement = "UPDATE NUMARATAJ SET KAPINUMERIK = LEFT(KAPINO,4) WHERE ISNUMERIC(LEFT(KAPINO),4)"

A: There are several "VBA functions" that were not directly supported by the older "Jet" ODBC driver (Microsoft Access Driver (*.mdb)) but are directly supported by the newer "ACE" ODBC driver (Microsoft Access Driver (*.mdb, *.accdb)). Replace is one of those functions.
So if you really need to use the Replace function you can download and install the 32-bit version of the Access Database Engine Redistributable and use the newer ODBC driver.


text:
Q: Error in Date parsing : CSV to DB using python I am trying to extract date from a CSV file using python and upload it into a database.In CSV, the date format is dd/mm/YYYY HH:MM  like 21/04/14 17:24,7/4/2014 17:12.
Before trying to insert the date into the DB(Sql server),I am printing it on python console.
But the following format is creating an error[date between 0-9/month between 0-9/year],for instance 7/4/2014 17:12,04/02/2014 are creating the following error
ValueError: time data '7/4/2014 17:12' does not match format '%d/%m/%y %H:%M'

My code is like this
formatter_string = "%d/%m/%Y %H:%M"
                for row in reader:
                        datetime_object = datetime.strptime(row[9], formatter_string)
                        row[9] = str(datetime_object.date())
                        print "insert into "+UploadTable+" values ("+nullcheckstr(row[9])+")"

Additional Info:nullcheckstr() ensures the date is not null and row[9] is date column in CSV

A: Thanks behzad.nouri,There was an issue with the CSV file.some dates are in dd/mm/YYYY format some are in dd/mm/YY format.I've corrected them and uploaded the file into the DB.


text:
Q: How come I didn't have to instantiate the NSCharacterSet object first before using it? I'm following a tutorial learning about delegates and protocols while using the UITextField object.  In the tutorial I noticed that I didn't have to instantiate the NSCharacterSet object first by typing
let letterCharacters = NSCharacterSet()

The tutorial's code worked by reaching directly for the letters variable of NSCharacterSet which is mind blowing.  I assumed objects always needed to be instantiated first before using them or making reference to them.  Here is the full function that works:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let existingTextHasDecimalSeperator = textField.text?.range(of: ".")
        let replacementTextHasDecimalSeperator = string.range(of: ".")
        let letterCharacters = NSCharacterSet.letters
        let foundCharacter = string.rangeOfCharacter(from: letterCharacters)

        if existingTextHasDecimalSeperator != nil && replacementTextHasDecimalSeperator != nil {
            return false
        } else if foundCharacter != nil {
            return false
        } else {
            return true
        }
    }

Why am I allowed to use NSCharacterSet.letters directly instead of creating a NSCharacterSet object first?

A: From the Apple documentation:
class var letters: CharacterSet

A character set containing the characters in Unicode General Category
  L* & M*.

The key piece here is the class part of that definition. If it is a class variable, than you do not need to instantiate the object with NSCharacterSet().
A quick primer on variable types.

*

*A class variable can be accessed simply by calling the variable with the class name CharacterSet.letters for example

*An instance variable needs to have its class instantiated first before it can be accessed, characterSet.inverted would be an example of this

Typically, a class variable would never change so it has no need to maintain state. An instance variable likely will.

A: If you look closely into the documentation (I prefer use jump to definition over apple docs) you can see that the class NSCharacterSet does offer class variables
You could compare this to enum with cases, but this a bit different case since you get actual values and well... just not cases. Difference between static and class variable are that class variables can be overriden, static cannot.
But to answer your question: You can access these variables directly because they are static.
You can create yourself a nice example, if you open playground:
class Car {

// This might be bad example, but you will see on next lines...
  class var brand: String { return "Volkswagen" }

  /// Because Volkswagen... :D
  class func emitSmog() {
     // Do wonderful things to earth and basically product rainbows
    }
}

// You don't need to create the Car instance
print(Car.brand)

// Again, this function is static, so you don't need to construct anything...
Car.emitSmog()

Please refer to Apple documentation:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html
See Type methods.


text:
Q: Centering tabular-looking nodes in TikZ I've recently decided to make a formal study of LaTeX so I can upgrade my talents from "copy, paste & hack" TeX user to well, someone who knows how to use the tools. One of the things I'm trying to learn is the use of TikZ to draw figures and diagrams.
So, what I'm attempting to do is to draw three table structures connected by arrows such that one points to the next. I'll include a hand-drawn sketch of what I intend at the conclusion of this question.
After hours of frustration (and some shouting at the computer, admittedly), I came up with the following MWE that produces almost exactly what I want.
\documentclass{article}

\usepackage{tikz}
\usepackage{tabularx}
\usepackage{amsmath}
\usepackage{mathtools}

\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{shadows}
\usetikzlibrary{positioning}

\begin{document}

    \tikzstyle{box} = [
        draw,
        fill=white!7,
        minimum width=5em,
        text centered,
        minimum height=2em,
        drop shadow
    ]

    \begin{tikzpicture}
        \node (dir0) [box, minimum width=16em, minimum height=4em] {\vdots};

        \node (dir1)  [box, anchor=north, minimum width=16em] at
            (dir0.south) {\texttt{Kernel Memory Pages}};

        \node (dir2L) [box, anchor=north west, minimum width=8em] at
            (dir1.south west) {\texttt{Permissions}};

        \node (dir2R) [box, anchor=north east, minimum width=8em] at
            (dir1.south east) {\texttt{Table Address}};

        \node (dir3)  [box, anchor=north, minimum width=16em] at
            (dir2R.south west) {\texttt{User Memory Pages}};

        \node (dir4L) [box, anchor=north west, minimum width=8em] at
            (dir3.south west) {\texttt{Permissions}};

        \node (dir4R) [box, anchor=north east, minimum width=8em] at
            (dir3.south east) {\texttt{Table Address}};

        \node (dir5)  [box, anchor=north, minimum width=16em, minimum
        height=4em] at (dir4R.south west) {\vdots};
    \end{tikzpicture}
\end{document}

This produces the following output, which is my first-ever drawing with TikZ:

Now, while I'm perfectly happy with the graphical results, I come from the school that believes that elegance in appearance of code is a virtue, and so I've started to rewrite the above example in a different style (like an example documented here under "Diagrams" - the "definition/declaration/linking" style), as once I add the other tables, the above code is bound to get messy, and I'm fearful it might be unmaintainable if I need to adjust it later on.
So, I've produced the following, which I'm much more happy with. You can tell that I've added the other two types of tables as well.
\documentclass{article}

\usepackage{tikz}
\usepackage{tabularx}
\usepackage{amsmath}
\usepackage{mathtools}

\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{shadows}
\usetikzlibrary{positioning}

\begin{document}
    \begin{tikzpicture} [
            % ----- Node definitions ----- %
            dirtablenode/.style = {
                rectangle,
                rectangle split,
                rectangle split parts = 6,
                fill = white!5,
                minimum width  = 5em,
                minimum height = 2em,
                text centered,
                drop shadow
            },
            pagetablenode/.style = {
                rectangle,
                rectangle split,
                rectangle split parts = 3,
                fill = white!5,
                minimum width  = 5em,
                minimum height = 2em,
                text centered,
                drop shadow
            },
            memmapnode/.style = {
                rectangle,
                rectangle split,
                rectangle split parts = 4,
                fill = white!5,
                minimum width  = 5em,
                minimum height = 2em,
                text centered,
                drop shadow
            }
    ]

        % ----- Node constructions ----- %
        \node [dirtablenode] (directory) {
            \nodepart [minimum width = 16em, minimum height = 4em] {one}
                \vdots
            \nodepart [minimum width = 16em, minimum height = 2em] {two}
                \texttt{Kernel Memory Pages}
            \nodepart [minimum width = 8em, minimum height = 2em]  {three}
                \texttt{Permissions}
            \nodepart [minimum width = 8em, minimum height = 2em]  {four}
                \texttt{Table Address}
            \nodepart [minimum width = 16em, minimum height = 2em] {five}
                \texttt{User Memory Pages}
            \nodepart [minimum width = 8em, minimum height = 2em]  {six}
                \texttt{Permissions}
            \nodepart [minimum width = 8em, minimum height = 2em]  {seven}
                \texttt{Table Address}
            \nodepart [minimum width = 16em, minimum height = 4em] {eight}
                \vdots
        };

        \node [pagetablenode] (kpagetable) [right=of directory] {
            \nodepart [minimum width = 16em] {kbase}  \texttt{Base Address}
            \nodepart [minimum width = 16em] {klimit} \texttt{Address Limit}
            \nodepart [minimum width = 16em] {kperms} \texttt{Permissions}
        };

        \node [pagetablenode] (upagetable) [below=of kpagetable] {
            \nodepart [minimum width = 16em] {ubase}  \texttt{Base Address}
            \nodepart [minimum width = 16em] {ulimit} \texttt{Address Limit}
            \nodepart [minimum width = 16em] {uperms} \texttt{Permissions}
        };

        \node [memmapnode] (sysmemory) [below=of directory] {
            \nodepart [minimum width = 16em, minimum height = 4em] {one} \vdots
            \nodepart [minimum width = 16em, minimum height = 4em] {kernel}
                \texttt{Kernel \\ Memory \\ (Protected)}
            \nodepart [minimum width = 16em, minimum height = 4em] {user}
                \texttt{User \\ Memory \\ (Unprivileged)}
            \nodepart [minimum width = 16em, minimum height = 4em] {one} \vdots
        };

        % ----- Connection lines ----- %
        % ??
    \end{tikzpicture}
\end{document}

To put it all together and to better indicate what I'm trying to do (rather than sit here and assume people on TeX.SE read minds), here's a doodle of what I've envisioned the entire tikzpicture looking like:

So, here come the parts of the question, which I've broken down. I've tried searching here for answers, but I can't find anything that addresses the issue, and looking through the TikZ manual is intimidating (to say the least) for a beginner.

*

*Does \nodepart support alignment in the same way that hand-created nodes are aligned? You'll notice that I declared the first (directory node to have 6 parts, although it actually has 8 nodeparts. Can I use the same anchor and at <reference> within \nodepart options to align these?

*Does the \node alignment (i.e. [right=of directory]) accept multiple alignment constraints, and if so, how would I align it such that the tops and bottoms of the respective pagetablenode instances are properly aligned with the directory?

*How would I align the bottom table (sysmemory) such that it lies centered between the two upper tables, with (ideally) hemispherical-ish lines connecting the right upper tables to it (as in the drawing)?
In short, what changes would I need to make to the second, more orderly MWE in order to fulfill the diagram as I have it envisioned? Keep in mind you may need to break this down for me a little bit - I'm green as grass to TikZ. I'm as interested in how the answer is right as I am in the actual answer.

A: As Zarko suggested you should read rectangle split information (pages 726--728) and positioning library information.
From first you will learn that minimum width is valid for vertically splitted rectangles but minimum height is ignored. Then all these options in each nodepart can be suppressed. Rectangle split width will be fixed by maximum of inner part widths or minimum width.  If you want to fix a certain minimum width you can do it in node options like is shown in kpagetable below.
When some minimum height is needed in some nodeparts we need other tools. A possible tool could be parbox (see [Yiannis' answer](https://tex.stackexchange.com/a/10273/1952  You also need to read about) to understand all parameters) but a 0 width rule \rule{0pt}{...} or phantom texts could also be used.
Reading information about positioning library you'll understand that
right= 3cm of directory.north east, anchor=north west

will force corresponding node to be placed 3cm right from upper right corner of directory node and aligned with its top line.
Similar constructions can be used to align other nodes with bottom corners.
Finally an aux node has been defined to place sysmemory node. Of course, there exist other constructions to obtain similar results.
Some more cleaning has been done on your code. First, as all blocks only differ in their parts, only one style with split parts being a parameter has been defined. If needed, minimum width option could be added to each particular node declaration.
Second, instead of \texttt{...} for each text part, option font has been used. It saves some typing.
Last comment, as it's not possible to horizontally divide a part, two part boxes and a manually drawn division have been used for lines containing permissions and table address.
\documentclass{article}

\usepackage{tikz}

\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{shadows}
\usetikzlibrary{positioning}

\begin{document}
    \begin{tikzpicture} [
            % ----- Node definitions ----- %
            dirtablenode/.style = {
                    draw,
                rectangle,
                rectangle split,
                rectangle split parts = #1,
                fill = white!5,
                align=center,
                drop shadow,
                font=\ttfamily
            },
    ]

        % ----- Node constructions ----- %
        \node [dirtablenode=6] (directory) {
            \nodepart{one}
                \parbox[t][15mm][c]{1cm}{\vdots}
            \nodepart[]{two}
                Kernel Memory Pages
            \nodepart{three}
                \parbox[t][][c]{3cm}{\centering Permissions}\parbox[t][][c]{3cm}{\centering Table Address}
            \nodepart{four}
                User Memory Pages
            \nodepart{five}
                \parbox[t][][c]{3cm}{\centering Permissions}\parbox[t][][c]{3cm}{\centering Table Address}
            \nodepart{six}
                \parbox[t][15mm][c]{1cm}{\vdots}
        };
          \draw (directory.two split)--(directory.three split);
          \draw (directory.four split)--(directory.five split);

        \node [dirtablenode=3, minimum width=5cm, right= 3cm of directory.north east, anchor=north west] (kpagetable) {
            \nodepart{one} Base Address
            \nodepart{two}  Address Limit
            \nodepart{three} Permissions
        };

        \node [dirtablenode=3, right=3cm of directory.south east, anchor=south west] (upagetable) {
            \nodepart{one}  Base Address
            \nodepart{two} Address Limit
            \nodepart{three} Permissions
        };

          \path (directory.south east) -- (upagetable.south west) coordinate[midway] (aux);

        \node [dirtablenode=4, below=of aux, anchor=north](sysmemory) {
            \nodepart{one} \vdots
            \nodepart{two}
                Kernel \\ Memory \\ (Protected)
            \nodepart{three}
                User \\ Memory \\ (Unprivileged)
            \nodepart{four} \vdots
        };

        % ----- Connection lines ----- %
       \draw[rounded corners,->] (directory.three east)--++(0:1cm)--([xshift=-1cm]kpagetable.north west)--(kpagetable.north west);
       \draw[rounded corners,->] (directory.five east)--++(0:1cm)--([xshift=-1cm]upagetable.north west)--(upagetable.north west);
       \draw[->] (kpagetable.two east) to[out=-10,in=5] (sysmemory.two east);
       \draw[->] (upagetable.two east) to[out=-10,in=5] (sysmemory.three east);
    \end{tikzpicture}
\end{document}

A: ... I change the mind ... after while I compared my solution (hich is based on of Ignasi first solution) again to  Ignasi solution, I estimated that differences are small but not negligible. So, here is my solution:
\documentclass{article}
\usepackage{tabularx}
\newcolumntype{C}{>{\centering\arraybackslash}X}

\usepackage{tikz}
\usetikzlibrary{arrows.meta,
                positioning,
                shadows,shapes}
\newcommand{\myvdots}{\vdots\rule[-2ex]{0ex}{5ex}}

\begin{document}
    \begin{tikzpicture} [% TikZ presets
                > = {Straight Barb[length=5pt]},
    node distance = 0mm and 24mm,
dirtablenode/.style args = {#1/#2}{%
        rectangle split,
        rectangle split parts = #1,
        draw,
        fill=white,
        inner sep=2mm,
        font=\ttfamily,
        text width=#2,
        align=center,
        drop shadow,
                },
                    ]
% ----- Node constructions ----- %
\node (directory)   [dirtablenode=6/16em]
{
    \nodepart{one}      \myvdots
    \nodepart{two}      Kernel Memory Pages
    \nodepart{three}    \begin{tabularx}{\hsize}{C C}
                Permissions &   Table Address
                        \end{tabularx}
    \nodepart{four}     User Memory Pages
    \nodepart{five}      \begin{tabularx}{\hsize}{C C}
                Permissions &   Table Address
                        \end{tabularx}
    \nodepart{six}      \myvdots
};
\draw   (directory.two split)  -- (directory.three split)
        (directory.four split) -- (directory.five  split);
%
\node (kpagetable) [dirtablenode=3/12em,
                    below right= of directory.north east]
{
    \nodepart{one}      Base Address
    \nodepart{two}      Address Limit
    \nodepart{three}    Permissions
};
%
\node (upagetable) [dirtablenode=3/12em,
                    above right=of directory.south east]
{
    \nodepart{one}  Base Address
    \nodepart{two} Address Limit
    \nodepart{three} Permissions
};
\path (directory.south east)-- coordinate (mid) (upagetable.south west);
\node (sysmemory) [dirtablenode=4/12em,
                   below=12mm of mid]
{
    \nodepart{one}      \myvdots
    \nodepart{two}      Kernel Memory  (Protected)
    \nodepart{three}    User   Memory  (Unprivileged)
    \nodepart{four}     \myvdots
};
% ----- Connection lines ----- %
\draw[rounded corners,->]
(directory.three east) --++ (0:1cm) -- ([xshift=-1cm]kpagetable.north west) -- (kpagetable.north west);
\draw[rounded corners,->]
(directory.five east) --++ (0:1cm) -- ([xshift=-1cm]upagetable.north west) -- (upagetable.north west);
\draw[->] (kpagetable.two east) to[out=-30,in=0,looseness=1.2] (sysmemory.two east);
\draw[->] (upagetable.two east) to[out=-30,in=0,looseness=1.5] (sysmemory.three east);
    \end{tikzpicture}
\end{document}

Main differences: for vertical dots I define new command, which to dots add more vertical space, multipart node has two arguments, one for number of parts, second for width of node (it is determined by \text width, so a longer text can be automatic broken into more lines), for arrows I use arrows.meta and made them bigger and with this better visible, loops are bigger and more close to be symmetric. I also remove all unnecessary option (mentioned in my comments) and package.
Result is slightly different:


text:
Q: Async and parallel function execution in JavaScript and Node.js I'm currently using two approaches to parallelize the execution of async functions in JavaScript Node.js. I do not intend to find which of the Promise or callback approach is best, but I'm likely searching for a better approach to parallelize functions execution in Node.js without using child_process.fork(), so that it can be used in the same process.
Assumed that my functions are Promise, hence a typical function will be like

var myFunc = () => new Promise((resolve, reject) => {
  setTimeout(() => resolve("some task"), 500)
})
myFunc().then(_ => console.log(_)).catch(err => console.err(err))

One approach is using Promise.all in this way:

var promiseAllP = function(items, block) {
  var promises = [];
  items.forEach(function(item, index) {
    promises.push(function(item, i) {
      return new Promise(function(resolve, reject) {
        return block.apply(this, [item, index, resolve, reject]);
      });
    }(item, index))
  });
  return Promise.all(promises);
} //promiseAll
promiseAllP([...Array(3).keys()], (item, index, resolve, reject) => {
    setTimeout(() => resolve("task "+index), 500 * index)
  })
  .then(_ => console.log(_)).catch(err => console.err(err))

the other approach would be using async execution with a callback like

var tasks = [
  (cb) => setTimeout(() => cb(null, "task 1"), 500 * 1),
  (cb) => setTimeout(() => cb(null, "task 2"), 500 * 2),
  (cb) => setTimeout(() => cb(null, "task 3"), 500 * 3),
];

function parallel(tasks, cb) {
  var results, pending, keys
  var isSync = true

  if (Array.isArray(tasks)) {
    results = []
    pending = tasks.length
  } else {
    keys = Object.keys(tasks)
    results = {}
    pending = keys.length
  }

  function done(err) {
    function end() {
      if (cb) cb(err, results)
      cb = null
    }
    if (isSync) process.nextTick(end)
    else end()
  }

  function each(i, err, result) {
    results[i] = result
    if (--pending === 0 || err) {
      done(err)
    }
  }

  if (!pending) {
    // empty
    done(null)
  } else if (keys) {
    // object
    keys.forEach(function(key) {
      tasks[key](function(err, result) {
        each(key, err, result)
      })
    })
  } else {
    // array
    tasks.forEach(function(task, i) {
      task(function(err, result) {
        each(i, err, result)
      })
    })
  }

  isSync = false
}

parallel(tasks, (err, res) => {
  if (err) console.error(error)
  else console.log(res)
});

The last one can be easily adapted to support Promise instead of callback. The problem is that I didn't find any improvement in executing my tasks through the first approach or the second one, so which is the best solution among them or is out of there a better approach to execute parallel tasks without using Node.js child_process.fork()?
The tasks to run have different execution times, they do not share memory, and I can run a callback or Promise.resolve to notify the caller that the task ended gracefully or Promise.reject if some error occurred.


text:
Q: How to specify castellations in gerber files I am making gerbers where I want one edge of the PCB to have castellations ( plated half-holes) on the edge.
What is the safest way to specify castellations in the gerbers that will ensure that:

*

*The fab how makes the castellations "properly", without making any mistakes. For example one possible mistake is that if the castellations are specified as vias chopped in half by the edge, then a CNC router cutting the board edge may tend to rip the copper off of the castellation through its high-speed spinning motion.

*The flat edge itself must be plated - not just the hole part!! See how the flat part of the edge is supposed to be plated in the vicinity of the hole:

A: Castellations are special, custom, and highly fab-dependent.
I've done it with holes that are cut in half by the outline layer.  But I supplied an extra drawing explaining what I wanted.  The castellations came out fine after some negotiation.  The board vendors tend to do some massaging of the CAD data anyway, so whatever extra work was required for castellations did not bother them.
The plating is an extra step that has to be done after routing, so expect to spend rather more money than a standard-spec board would cost.

A: Adding to what markrages already said: most board fabs will plate any copper that is over or directly touches the edge of a hole or routed feature. So a 'standard' way of defining this is just to have copper over the edges of your castellations. This is how vias and plated through holes work - and conversely, this is how non-plated holes work as well (you just pull back the copper a little bit from the hole).
This will work fine with very cheap board houses that are hard to communicate with (e.g. iteadstudio, pcbcart, makepcb). Almost always at no extra charge, it's just part of the workflow. However, if you are doing a production run you will definitely want to communicate any and all special features. Make sure that it is abundantly clear what you mean, use pictures and highlight what you want in the pictures as well as in the gerber files. That will save you from having to do multiple test runs (and waste everybody's time) before you go into actual production.


text:
Q: Bind CheckBoxFor to bool? How to bind nullable bool to checkbox in MVC 2. I try with  this code in view:
<%: Html.CheckBoxFor(model =>  model.Communication.Before)%>

But show me compilation error.
Thanks in advance.

A: I know about this issue. You  can try to use this workaround:
Create new property  called Before in yours ViewModel:
public class YoursViewModel
{
    public Communication Communication { get; set; }

    public bool Before
    {
        get
        {
            bool result;
            if (this.Communication.Before.HasValue)
            {
                result = (bool)this.Communication.Before.Value;
            }
            else
            {
                result = false;
            }

            return result;
        }
        set
        {
            this.Communication.Before = value;
        }
    }
}

Also you  have to  be careful for Communication property this have to be instanced before use. For example when you  initialize ViewModel in controller you  also have to  initialize this property.
ControllerAction()
{
  YoursViewModel model = ViewModelFactory.CreateViewModel<YoursViewModel >("");
  model.Communication = new Communication ();
  return View(model);
}

Thanks
Ivan Baev

A: A checkbox can have two states: ckecked/uncheked, true/false, 1/0. So trying to bind a checkbox to a property that could potentially have three states doesn't really fit the picture. I would recommend you adapting your view model so that it uses a non nullable boolean property. If in your domain model you have a nullable boolean which you cannot change you could do this in the mapping layer between your domain model and view model.

A: One way to bind Checkbox in MVC View
With EF database first, boolean (bit) field in the database produces a nullable bool? Property in the generated class. For demo I have a table named Dude with the fields

*

*Id uniqueidentifier

*Name varchar(50)

*IsAwesome bit

The following class is generated by EF:
namespace NullableEfDemo
{
 using System;
 public partial class Dude
 {
    public System.Guid Id { get; set; }
    public string Name { get; set; }
    public Nullable<bool> IsAwesome { get; set; }
 }
}

To be able to bind IsAwesome to checkbox I simply extend the class Dude. This is to avoid editing the generated class, if I need to refresh it.  So I added a code file DudePartial.cs to my project (the name is irrelevant). Don't forget to declare or using the project namespace:
namespace NullableEfDemo
{
 partial class Dude
 {
    public bool Awesome
    {
        get { return IsAwesome ?? false; }
        set { IsAwesome = value; }
    }
  }
}

This declares a new property Awesome of type bool that can be bound to the checkbox in the Edit view
@Html.CheckBoxFor(model => model.Awesome, new { @class = "control-label" })

In the HttpPost I'm binding the models Awesome property instead of IsAwesome.
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,Awesome")] Dude dude)
    {…


text:
Q: Account suspended because college friend offered bounty and upvoted a few of my answers I don't know if moderators are actually trying to understand my predicament here, but a few years back I had a friend from college who used to share me the links of his questions to answer questions on Stack Overflow. He might have offered me a bounty and few upvotes. I just got to know this because those questions were deleted by moderators. I discussed this matter with him and got to know his account was deleted by moderators.
Can any moderator please help me here?

A: SO moderator here, not previously involved in your case. I've reviewed the history here. You were sent a message describing your suspension, as with all suspensions.
We don't disclose our methods for determining when vote fraud is occurring. The moderators involved in your suspension saw convincing evidence of voting fraud and acted appropriately.
Your best path forward is to wait for the end of the suspension, and explain to your friend that targeted voting is not helpful. Also, note that deleting and recreating accounts won't work to circumvent a suspension (in fact, it'll only make things worse).


text:
Q: Pomelo.EntityFrameworkCore.MySql problem when access property Today I migrate my project to .NET 6 with MySql db.
I tried Pomelo.EntityFrameworkCore.MySql for the first time but several errors had occur.
I fixed some of them but the last one, I couldn`t.
System.InvalidOperationException: The property 'SqlClass.Disabled' is of type 'byte' which is not supported by the current database provider. Either change the property CLR type, or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

             entity.Property(e => e.Disabled)
           //.HasConversion<int>()
            .IsRequired()
            .HasMaxLength(255)
            .HasColumnName("disabled")
            .HasColumnType("tinyint(1)");

    [Required]
    [MaxLength(255)]
    public byte Disabled { get; set; }

Any ideas ? Thank you.

A: There are basically 3 simple options, all demonstrated here with the IceCream.Available property:

1. Use System.Boolean instead of System.Byte
Pomelo translates tinyint(1) to System.Boolean by default. So if you change the CLR type of your property from byte to bool, it works out-of-the box:
Program.cs
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace IssueConsoleTemplate
{
    public class IceCream
    {
        public int IceCreamId { get; set; }
        public string Name { get; set; }

        [Required]
        [Column(TypeName = "tinyint(1)")] // <-- redundant (bool is translated to tinyint(1) by default)
        public bool Available { get; set; } // <-- use bool
    }

    public class Context : DbContext
    {
        public DbSet<IceCream> IceCreams { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var connectionString = "server=127.0.0.1;port=3306;user=root;password=;database=So70198786";
            var serverVersion = ServerVersion.AutoDetect(connectionString);

            optionsBuilder
                .UseMySql(connectionString, serverVersion)
                .UseLoggerFactory(
                    LoggerFactory.Create(
                        b => b
                            .AddConsole()
                            .AddFilter(level => level >= LogLevel.Information)))
                .EnableSensitiveDataLogging()
                .EnableDetailedErrors();
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<IceCream>(
                entity =>
                {
                    // Not needed if you are using data annotations:
                    //
                    // entity.Property(e => e.Available)
                    //     .IsRequired()
                    //     .HasColumnType("tinyint(1)"); // <-- redundant (bool is translated to tinyint(1) by default)

                    entity.HasData(
                        new IceCream
                        {
                            IceCreamId = 1,
                            Name = "Vanilla",
                            Available = true, // <-- bool
                        },
                        new IceCream
                        {
                            IceCreamId = 2,
                            Name = "Chocolate",
                            Available = false, // <-- bool
                        });
                });
        }
    }

    internal static class Program
    {
        private static void Main()
        {
            using var context = new Context();

            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            var availableIceCreams = context.IceCreams
                .Where(i => i.Available) // <-- bool
                .ToList();

            Trace.Assert(availableIceCreams.Count == 1);
            Trace.Assert(availableIceCreams[0].Name == "Vanilla");
        }
    }
}

Output (SQL)
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.0 initialized 'Context' using provider 'Pomelo.EntityFrameworkCore.MySql:6.0.0-rtm.1' with options: ServerVersion 8.0.25-mysql SensitiveDataLoggingEnabled DetailedErrorsEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (38ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      DROP DATABASE `So70198786`;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (13ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE DATABASE `So70198786`;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (15ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      ALTER DATABASE CHARACTER SET utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (47ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `IceCreams` (
          `IceCreamId` int NOT NULL AUTO_INCREMENT,
          `Name` longtext CHARACTER SET utf8mb4 NULL,
          `Available` tinyint(1) NOT NULL,
          CONSTRAINT `PK_IceCreams` PRIMARY KEY (`IceCreamId`)
      ) CHARACTER SET=utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (9ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      INSERT INTO `IceCreams` (`IceCreamId`, `Available`, `Name`)
      VALUES (1, TRUE, 'Vanilla');
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (10ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      INSERT INTO `IceCreams` (`IceCreamId`, `Available`, `Name`)
      VALUES (2, FALSE, 'Chocolate');
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT `i`.`IceCreamId`, `i`.`Available`, `i`.`Name`
      FROM `IceCreams` AS `i`
      WHERE `i`.`Available`

2. Use tinyint instead of tinyint(1)
In case you definitely want to use System.Byte as the CLR type of your property, use tinyint instead of tinyint(1). All tinyint except tinyint(1) are translated to System.Byte by default:
Program.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace IssueConsoleTemplate
{
    public class IceCream
    {
        public int IceCreamId { get; set; }
        public string Name { get; set; }

        [Required]
        [Column(TypeName = "tinyint")] // <-- redundant (byte is translated to tinyint by default)
        public byte Available { get; set; }
    }

    public class Context : DbContext
    {
        public DbSet<IceCream> IceCreams { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var connectionString = "server=127.0.0.1;port=3306;user=root;password=;database=So70198786_01";
            var serverVersion = ServerVersion.AutoDetect(connectionString);

            optionsBuilder
                .UseMySql(connectionString, serverVersion)
                .UseLoggerFactory(
                    LoggerFactory.Create(
                        b => b
                            .AddConsole()
                            .AddFilter(level => level >= LogLevel.Information)))
                .EnableSensitiveDataLogging()
                .EnableDetailedErrors();
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<IceCream>(
                entity =>
                {
                    // Not needed if you are using data annotations:
                    //
                    // entity.Property(e => e.Available)
                    //     .IsRequired()
                    //     .HasColumnType("tinyint"); // <-- redundant (byte is translated to tinyint by default)

                    entity.HasData(
                        new IceCream
                        {
                            IceCreamId = 1,
                            Name = "Vanilla",
                            Available = 1, // <-- byte
                        },
                        new IceCream
                        {
                            IceCreamId = 2,
                            Name = "Chocolate",
                            Available = 0, // <-- byte
                        });
                });
        }
    }

    internal static class Program
    {
        private static void Main()
        {
            using var context = new Context();

            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            var availableIceCreams = context.IceCreams
                .Where(i => i.Available != 0) // <-- byte
                .ToList();

            Trace.Assert(availableIceCreams.Count == 1);
            Trace.Assert(availableIceCreams[0].Name == "Vanilla");
        }
    }
}

Output (SQL)
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.0 initialized 'Context' using provider 'Pomelo.EntityFrameworkCore.MySql:6.0.0-rtm.1' with options: ServerVersion 8.0.25-mysql SensitiveDataLoggingEnabled DetailedErrorsEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (42ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      DROP DATABASE `So70198786_01`;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (41ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE DATABASE `So70198786_01`;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (19ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      ALTER DATABASE CHARACTER SET utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (48ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `IceCreams` (
          `IceCreamId` int NOT NULL AUTO_INCREMENT,
          `Name` longtext CHARACTER SET utf8mb4 NULL,
          `Available` tinyint NOT NULL,
          CONSTRAINT `PK_IceCreams` PRIMARY KEY (`IceCreamId`)
      ) CHARACTER SET=utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (9ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      INSERT INTO `IceCreams` (`IceCreamId`, `Available`, `Name`)
      VALUES (1, 1, 'Vanilla');
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (10ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      INSERT INTO `IceCreams` (`IceCreamId`, `Available`, `Name`)
      VALUES (2, 0, 'Chocolate');
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (6ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT `i`.`IceCreamId`, `i`.`Available`, `i`.`Name`
      FROM `IceCreams` AS `i`
      WHERE `i`.`Available` <> 0

3. Change default System.Boolean mapping to bit(1) or remove it altogether
Finally, if you need to map exactly tinyint(1) to System.Byte, then you can change the default mapping that Pomelo is using for System.Boolean by setting a DbContext option in your UseMySql() call:
Program.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;

namespace IssueConsoleTemplate
{
    public class IceCream
    {
        public int IceCreamId { get; set; }
        public string Name { get; set; }

        [Required]
        [Column(TypeName = "tinyint(1)")] // <-- necessary (otherwise gets translated to tinyint)
        public byte Available { get; set; }
    }

    public class Context : DbContext
    {
        public DbSet<IceCream> IceCreams { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var connectionString = "server=127.0.0.1;port=3306;user=root;password=;database=So70198786_02";
            var serverVersion = ServerVersion.AutoDetect(connectionString);

            optionsBuilder
                .UseMySql(
                    connectionString,
                    serverVersion,
                    options => options.DefaultDataTypeMappings( // <-- change default data type mappings
                        m => m.WithClrBoolean(MySqlBooleanType.Bit1))) // <-- or even MySqlBooleanType.None
                .UseLoggerFactory(
                    LoggerFactory.Create(
                        b => b
                            .AddConsole()
                            .AddFilter(level => level >= LogLevel.Information)))
                .EnableSensitiveDataLogging()
                .EnableDetailedErrors();
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<IceCream>(
                entity =>
                {
                    // Not needed if you are using data annotations:
                    //
                    // entity.Property(e => e.Available)
                    //     .IsRequired()
                    //     .HasColumnType("tinyint(1)"); // <-- necessary (otherwise gets translated to tinyint)

                    entity.HasData(
                        new IceCream
                        {
                            IceCreamId = 1,
                            Name = "Vanilla",
                            Available = 1, // <-- byte
                        },
                        new IceCream
                        {
                            IceCreamId = 2,
                            Name = "Chocolate",
                            Available = 0, // <-- byte
                        });
                });
        }
    }

    internal static class Program
    {
        private static void Main()
        {
            using var context = new Context();

            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            var availableIceCreams = context.IceCreams
                .Where(i => i.Available != 0) // <-- byte
                .ToList();

            Trace.Assert(availableIceCreams.Count == 1);
            Trace.Assert(availableIceCreams[0].Name == "Vanilla");
        }
    }
}

Output (SQL)
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 6.0.0 initialized 'Context' using provider 'Pomelo.EntityFrameworkCore.MySql:6.0.0-rtm.1' with options: ServerVersion 8.0.25-mysql SensitiveDataLoggingEnabled DetailedErrorsEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (40ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      DROP DATABASE `So70198786_02`;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (13ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE DATABASE `So70198786_02`;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (19ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      ALTER DATABASE CHARACTER SET utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (86ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `IceCreams` (
          `IceCreamId` int NOT NULL AUTO_INCREMENT,
          `Name` longtext CHARACTER SET utf8mb4 NULL,
          `Available` tinyint(1) NOT NULL,
          CONSTRAINT `PK_IceCreams` PRIMARY KEY (`IceCreamId`)
      ) CHARACTER SET=utf8mb4;
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      INSERT INTO `IceCreams` (`IceCreamId`, `Available`, `Name`)
      VALUES (1, 1, 'Vanilla');
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      INSERT INTO `IceCreams` (`IceCreamId`, `Available`, `Name`)
      VALUES (2, 0, 'Chocolate');
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT `i`.`IceCreamId`, `i`.`Available`, `i`.`Name`
      FROM `IceCreams` AS `i`
      WHERE `i`.`Available` <> 0

Unrelated to the topic of this question, [MaxLength(255)] or .HasMaxLength(255) have no effect on non-string columns.


text:
Q: Spark create multiple Data frames from one Data frame I am using Spark 2.1 with Cassandra (3.9) as data source. C* has a big table with 50 columns, which is not a good data model for my use case. so I created split tables for each of those sensors along with partition key and clustering key cols.
All sensor table
-----------------------------------------------------
| Device |   Time     | Sensor1 | Sensor2 | Sensor3 |
|  dev1  | 1507436000 |  50.3   |    1    |    1    |
|  dev2  | 1507436100 |  90.2   |    0    |    1    |
|  dev1  | 1507436100 |  28.1   |    1    |    1    |
-----------------------------------------------------
Sensor1 table
-------------------------------
| Device |   Time     | value |
|  dev1  | 1507436000 | 50.3  |
|  dev2  | 1507436100 | 90.2  |
|  dev1  | 1507436100 | 28.1  |
-------------------------------

Now I am using spark to copy data from old table to new ones.
df = spark.read\
    .format("org.apache.spark.sql.cassandra")\
    .options(table="allsensortables", keyspace="dataks")\
    .load().cache()
df.createOrReplaceTempView("data")
query = ('''select device,time,sensor1 as value from data  ''' )
vgDF = spark.sql(query)
vgDF.write\
    .format("org.apache.spark.sql.cassandra")\
    .mode('append')\
    .options(table="sensor1", keyspace="dataks")\
    .save()

copying data one by one is taking a lot of time (2.1) hours for a single table. is there any way i can select * and create multiple df for each sensors and save at once ? (or even sequentially).

A: One issue in the code is the cache
df = spark.read\
.format("org.apache.spark.sql.cassandra")\
.options(table="allsensortables", keyspace="dataks")\
.load().cache()

Here I don't see how df is used multiple times apart from save. SO here cache is counter productive. You are reading the data, filter it and saving it to a separate cassandra table. Now the only action happening on the dataframe is the save and nothing else.
So there is no benefit from caching the data here. Removing the cache will give you some speed up.
To create multiple tables sequentially. I would suggest to use partitionBy and write the data first to HDFS as partitioned data w.r.t sensor and then write it back to cassandra.


text:
Q: C++ How to pass a vector of pointers (double pointers) as a constant to a function I have a class A in C++ with many attributes:
 class A{
   public:
      B** tab;// B is another class or structure
      ....
      void compute();//this function does calculations on elements inside tab
   };

In a third class C, there is a function that uses the tab variable as input, reads each element and does some calculations to write results on another attribute of the class C:
C::compute(B** tab){
     ....// I need that **tab be protected inside this function and its elements does not change
 }

How can I make tab: the vector of pointers protected (or constant) ?

A: One possible way is something like this:
C::compute(B * const * tab){
   // nothing in this array of pointers will be changed
   tab[0] = (B *) 0x3254; // compile error as desired
}

Or you can ban changing even pointer to pointers like this:
C::compute(B * const * const tab){
   // nothing in this array of pointers will be changed
   tab = (B * const *) 0x3254; // compile error
}

If you need to protect only pointers in array the first example is your choice

A: How about using vector:
class A {
    vector<vector<B> > tab;
    //...
}

C::compute(const vector<vector<B> >& tab) {
    // tab, tab[0] and tab[0][0] are all const
}


text:
Q: Qt: Background color on QStandardItem using StyleSheet I have a class that inherits QStandardItem and I put the elements in a QTreeWidget. The class receives notifications from the outside and I want to change the background color of the item based on what happened.
If I do not use stylesheets, it works just fine, like this:
void myClass::onExternalEvent()
{
    setBackground(0, QColor(255,0,0)));
}

However, as soon as I put a stylesheet on the QTreeWidget, this has no effect : the stylesheet seems to override the setBackground() call.
So I tried :
void myClass::onExternalEvent()
{
    this->setStyleSheet("background-color: red");
}

but this is probably all wrong, it changed the color of some other element on my screen, not sure why.
Does anyone have an idea on how I can alter the background color like with setBackgroundColor but still be able to use stylesheet on my QTreeWidget?

A: Palettes propagate to the children of a widget, and it's bad to mix and match style-sheet controls and native controls (I do not have a citation for the latter handy, but I have read it in the QT docs somewhere).
That being said, try setting setAutoFillBackground(false) on your QStandardItem derived class.
EDIT: Sorry - also, are you specifying the QTreeWidget in the stylesheet or just setting "background-color:"? If you specify the QTreeWidget only in the stylesheet that might take care of it as well.
QTreeWidget { background-color: white; }

But I think you still have to set the autoFillBackground(false).


text:
Q: Get elements of a permutation I have an 1D-array whose elements are a permutation of 0:N, and I need to take the first K elements of this permutation
For example, in the case the permutation is
0    [[9]
1     [0]
2     [1]
3     [2]
4     [3]
5     [4]
6     [5]
7     [6]
8     [7]
9     [8]]

The first 3 elements are 9 , 8 , 7
The code is
    n = start
    r = zeros (nodeCount, dtype = int)
    i = 0
    while (self.nodes[n][direction] != stop):
        r[i] = n
        n = self.nodes[n][direction]
        i+=1

I need a faster way to extract the elements from permutation.

A: This works, but I don't think it is going to be especially fast:
>>> a
array([9, 0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> n = 3
>>> b = np.empty((n,), dtype=a.dtype)
>>> b[0] = a[0]
>>> for k in xrange(1, n):
...     b[k] = a[b[k-1]]
...
>>> b
array([9, 8, 7])

A: Is numpy.roll what you're after?
>>> a = np.arange(10)
>>> b = np.roll(a,1)
>>> b
array([9, 0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> np.roll(b[::-1],1)[:3]
array([9, 8, 7])

That last line of code is pretty cryptic, but b[::-1] reverses the array, np.roll shifts it, and the [:3] only takes the first three elements.