text:
Q: Does anybody know what this tool is called? Productive work has crawled to a stop while we try and figure out what the red thing on the cover of Microsoft SQL Server 2012 Internals (2013, 0735658560) is. We think it's a surgical or electrical tool of some sort?

Thoughts?

A: Specifically, it appears to be a Fredrix Canvas Pliers #7400 tool.
Here's a link to the manufacturers page (scroll to the bottom)  Fredrix Canvas Pliers tool manufacturer:

and a vendor page with a picture that more closely matches the book cover,  Fredrix Canvas Pliers tool for sale. It looks like the spring has been removed from the tool on the book cover:

A: It almost looks like a sheet metal seeming tool.

A: It's a pair of canvas pliers. They're used to stretch canvas over braces, used in painting prep.

Answer source: Matt Velic, data professional and noted art graduate.

A: Looks like a sheet metal pliers.

A: Believe it to be a PVC pipe cutter...

A: It looks like a hand held paper hole punch, like the kinds we used to use when we were in grade school, with the blue flip lid trap door thingy that would catch the chads.

A: It's the arm of a spot welding machine.


text:
Q: Get the parent controler in a listview I have a ListView with a list of name and I want to be able to rename each value by double click or with a button.
I already did this for the doubleclick and it's working using this :
WPF
<ListView Grid.Row="0" x:Name="ListProfileView"
          ItemsSource="{Binding ProfilesCollection}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Name}" IsReadOnly="True" VerticalAlignment="Center">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="MouseDoubleClick">
                        <i:InvokeCommandAction
                            Command="{Binding DataContext.RenameCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">
                            <i:InvokeCommandAction.CommandParameter>
                                <MultiBinding Converter="{StaticResource MultiConverter}">
                                    <Binding RelativeSource="{RelativeSource AncestorType={x:Type TextBox}}"/>
                                    <Binding Source="{x:Static classes:BooleanHelper.False}"/>
                                </MultiBinding>
                            </i:InvokeCommandAction.CommandParameter>
                        </i:InvokeCommandAction>
                    </i:EventTrigger>
                    <i:EventTrigger EventName="LostFocus">
                        <i:InvokeCommandAction
                            Command="{Binding DataContext.RenameCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">
                            <i:InvokeCommandAction.CommandParameter>
                                <MultiBinding Converter="{StaticResource MultiConverter}">
                                    <Binding RelativeSource="{RelativeSource AncestorType={x:Type TextBox}}"/>
                                    <Binding Source="{x:Static classes:BooleanHelper.True}"/>
                                </MultiBinding>
                            </i:InvokeCommandAction.CommandParameter>
                        </i:InvokeCommandAction>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </TextBox>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

c# (MVVM model with ICommand):
private ICommand _renameCommand;
/// <summary>
/// Command used to change the name of the selected profile.
/// </summary>
public ICommand RenameCommand
{
    get
    {
        return _renameCommand ?? (_renameCommand = new RelayCommand<object>(obj =>
        {
            if(!(obj is object[] values)) return;
            if(!(values[0] is TextBox txtBox) || !(values[1] is bool value)) return;

            txtBox.IsReadOnly = value;
            if (!value)
            {
                txtBox.Focus();
            }
        }));
    }
}

But for the button, I don't know how to get the path to the textbox to use the same command.
I tried things like that :
<Button Grid.Column="3" Content="{x:Static dictionnaries:ColorConfigurationDictionnary.rename}"
        FontWeight="SemiBold"
        Command="{Binding RenameCommand}">
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource MultiConverter}">
            <Binding ElementName="ListProfileView" Path="ItemContainerGenerator"/>
            <Binding Source="{x:Static classes:BooleanHelper.False}"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

But I'm out of idea... Is that possible ?

A: It seems that there is some sort of misinformation going about so let me describe how MvvM works in the best way I can think of.
Model is where you store your data so let's call that a profile:
namespace Model
{
    public class Profile
    {
         public string Name { get; set; }
    }
}

Now what you need is a ViewModel which will provide Information which is manipulated data:
using VM.Commands;

namespace VM
{
    public class MainViewModel : BaseViewModel
    {
        public MainViewModel()
        {
            ProfilesCollection = new List<Profile>();
            for (int i = 0; i < 100; i++)
            {
                ProfilesCollection.Add(new Profile() {Name = $"Name {i}"});
            }
            RenameCommand = new TestCommand(renameCommandMethod, (o) => true);
        }

    void renameCommandMethod(object parameter)// to manipulate the colleciton you use the Commands which you already do but without the need for converters or any UI elements. Makes it much easier to handle.
    {
        string renameTo = parameter.ToString();
        foreach (var profile in ProfilesCollection)
        {
            profile.Name = renameTo;
        }
    }

    private List<Profile> profilesCollection;

    public List<Profile> ProfilesCollection
    {
        get { return profilesCollection; }
        set { profilesCollection = value; OnPropertyChanged(); }
    }

    private ICommand renameCommand;

    public ICommand RenameCommand
    {
        get { return renameCommand; }
        set { renameCommand = value; }
    }

And the implementation of the RelayCommand:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace VM.Commands
{
public class TestCommand : ICommand
{
    private Action<object> _execute;
    private Predicate<object> _canExecute;
    public TestCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    #region Implementation of ICommand

    public bool CanExecute(object parameter)
    {
        return _canExecute?.Invoke(parameter) ?? true;
    }

    public void Execute(object parameter)
    {
        _execute?.Invoke(parameter);
    }

    public event EventHandler CanExecuteChanged;

    #endregion
}
}

Then UI looks like this:
<Window x:Class="SO_app.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:vm="clr-namespace:VM;assembly=VM"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:converter="clr-namespace:SO_app.Converters"
    xmlns:validation="clr-namespace:SO_app.Validation"
    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    xmlns:local="clr-namespace:SO_app"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:model="clr-namespace:Model;assembly=Model"
    mc:Ignorable="d"
    d:DataContext="{d:DesignInstance Type=vm:MainViewModel, IsDesignTimeCreatable=True}"
    Title="MainWindow" Height="452.762" Width="525" Closing="Window_Closing">
<Window.Resources>
    <CollectionViewSource Source="{Binding ProfilesCollection}" x:Key="profiles"/>
</Window.Resources>
<Window.DataContext>
    <vm:MainViewModel/>
</Window.DataContext>

<Window.Background>
    <VisualBrush>
        <VisualBrush.Visual>
            <Rectangle Width="50" Height="50" Fill="ForestGreen"></Rectangle>
        </VisualBrush.Visual>
    </VisualBrush>
</Window.Background>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <ListView ItemsSource="{Binding Source={StaticResource profiles}}"
              VirtualizingPanel.VirtualizationMode="Recycling">
        <ListView.ItemTemplate>
            <DataTemplate>
                <DataTemplate.Resources>
                    <ToolTip x:Key="Tip">
                        <TextBlock>
                            <Run>Some text here</Run>
                            <LineBreak/>
                            <Run Text="{Binding Name, StringFormat='Actual Text: {0}'}"/>
                        </TextBlock>
                    </ToolTip>
                </DataTemplate.Resources>
                <TextBlock Text="{Binding Name}" ToolTip="{StaticResource Tip}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <StackPanel Grid.Column="1">
        <Button Content="Rename" Command="{Binding RenameCommand}" CommandParameter="NewName"></Button>
    </StackPanel>
</Grid>

What this gives you is:
* Clean UI without any converters
* Every operation is done in the ViewModel without passing any UI elements.
* In UI you would do stuff like Styles with animation or setting font for text elements. But avoid handling clicks there. It is possible and sometimes it can't be avoided but try to utilise your ViewModel to manipulate the data.
BTW there are no controllers in here.
If you have any questions just ask.

A: Here is what I did:
that let me change the name of one value only by disabling the readonly of the textboxes in the list view.
I wrote that in the GUI code behind.
private ICommand _renameCommand;
/// <summary>
/// Command used to change the name of the selected profile.
/// </summary>
public ICommand RenameCommand
{
    get
    {
        return _renameCommand ?? (_renameCommand = new RelayCommand<object>(obj =>
        {

            if(!(obj is object[] values)) return;

            if(!(values[0] is TextBox || values[0] is SetConfiguration) || !(values[1] is bool value)) return;

            if (values[0] is TextBox txtBox)
            {
                txtBox.IsReadOnly = value;
                if (!value)
                {
                    txtBox.Focus();
                    txtBox.SelectAll();
                }
            }

            if (values[0] is SetConfiguration config)
            {
                var listView = ListProfileView.ItemContainerGenerator.ContainerFromItem(config) as ListViewItem;
                var presenter = FindVisualChild<ContentPresenter>(listView);
                if(!(presenter.ContentTemplate.FindName("ProfileName", presenter) is TextBox txtBoxItem)) return;
                if (!value)
                {
                    txtBoxItem.Focus();
                    txtBoxItem.SelectAll();
                }
                txtBoxItem.IsReadOnly = value;
            }

        }));
    }
}

private static TChildItem FindVisualChild<TChildItem>(DependencyObject obj)
    where TChildItem : DependencyObject
{
    for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        var child = VisualTreeHelper.GetChild(obj, i);
        if (child is TChildItem item)
            return item;

        var childOfChild = FindVisualChild<TChildItem>(child);
        if (childOfChild != null)
            return childOfChild;
    }
    return null;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to 'only' get the service 'status' in Windows? (alternative for `systemctl is-active service`) I have been exploring on a windows alternative for following Linux command:
systemctl is-active firewalld

This command only gives us the strings active or inactive as output. So that it becomes helpful in developing various scripts.
I am so far unable to find such command for windows. Could you please help?

A: Powershell:
$serviceName = "firewalld"
(get-service $serviceName).status

Will return Running/Stopped/Deactivated if a service with the name "firewalld" exists.


text:
Q: Polarization of Light Without Reducing Intensity I think I have figured out a way to polarized light with negligible intensity loss using polarizing beam splitters and laser beam combiners. I am just wondering if there is any practical application for such a discovery.

A: Polarizing an unpolarized beam, without reducing the intensity or increasing the etendue, would violate the second law of thermodynamics.
So what's the practical application? It's good pedagogy. You can think more carefully about how your scheme would work, eventually realize that it actually doesn't work after all, and in the process you will come to understand physics a little bit better and even have fun. :-P


text:
Q: API design with Node.JS I am designing an API with express/node, and I would like to know if one does it need to explicitly set the headers for request and/ or response or is that automatically handled? As I just read the following for RESTFUL API best practices:
Use HTTP headers for serialization formats
Both, client and server, need to know which format is used for the communication. The format has to be specified in the HTTP-Header.
Content-Type defines the request format.
Accept defines a list of acceptable response formats.
https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/
However I am not sure what that truly means in practice.
app.delete('/LimeLINE/api/v1/users/delete/:boolean', (req, res) => {
    let inactive;
    try {
        inactive = req.params.boolean
    } catch (e) {
        log('e', 'app.delete(/LimeLINE/api/v1/users/delete/:boolean - e - 291 : ' + e)
        return res.status(500).send({
            message: "INTERNAL SERVER ERROR"
        })
    }
    //res.setHeader('Content-Type', 'application/json');
    user.deleteInActive(inactive, res)
})

A: If you're using Express then it does a lot of work already for you. So, you don't need to specify content-type in header as it already provides methods and handles most of the header portion
ex : res.json() ;
It already sets the content-type to json.
In case of handling errors, you may specify "status" property and set HttpStatus to UNAUTHORIZED , INTERNAL_SERVER_ERROR, BAD_REQUEST , etc.
so you just need to use the inbuilt express functions which does all the work for you.

A: I have an API scope, I use the REST concept with express. You already have ORM for the database using Sequelize.
Follow the link below:
https://github.com/wandersonpereira/easy-api-node


text:
Q: Set window size when launching MS Word I am using classic ASP to download data from my web server into a word document.  I am using the following headers in my ASP script to accomplish this...
    Response.ContentType = "application/msword"
    Response.AddHeader "Content-Disposition", "attachment;filename=gbResults.doc"
    Response.write("<html " & _
    "xmlns:o='urn:schemas-microsoft-com:office:office' " & _
    "xmlns:w='urn:schemas-microsoft-com:office:word'" & _
    "xmlns='http://www.w3.org/TR/REC-html40'>")

    Response.write "<xml>" & _
        "<w:WordDocument>" & _
        "<w:View>Print</w:View>" & _
        "<w:Zoom>90</w:Zoom>" & _
        "<w:DoNotOptimizeForBrowser/>" & _
        "</w:WordDocument>" & _
        "</xml>" & _

The data I retrieve from my database is generated by this script following the above code and it successfully downloads the data and opens an instance of MS Word that contains the data returned...fully formatted for the user.  This is working as expected.
My question...is it possible to open the instance of word so that the window is not maximized?  We would like to keep the main browser in view because some users are thinking that they have left the application running in the browser because they can't see it when word is maximized.
Of course we do not know what browser the end user will employ so an solution that is cross browser compatible is what we're looking for.
I was unable to find a solution via xml, java or asl so far in my research.  Any help is greatly appreciated.


text:
Q: How to set multiple values as defaultValue using Springfox 2.7.0, 2.9.2 I have a request parameter that accepts an array of string/enums, however when I validate the docs with openapi-generator, it says that the default is not of type 'array'. Looking at the api-docs, I see it made the default value a string, rather than an array.
How do I annotate the Springfox swagger so that I can list multiple values as the default selection?
@GetMapping
public PagedResults<PortfolioDto> getVisiblePortfolios(
        @ApiParam("List of Visibility")
        @RequestParam(defaultValue = "COMPANY,GLOBAL")  List<PublicVisibility> visibility) { }

produces
      {
        "name": "visibility",
        "in": "query",
        "description": "List of Visibility",
        "required": false,
        "type": "array",
        "items": {
          "type": "string",
          "enum": [
            "COMPANY",
            "GLOBAL"
          ]
        },
        "collectionFormat": "multi",
        "default": "[COMPANY,GLOBAL]",
        "enum": [
          "COMPANY",
          "GLOBAL"
        ]
      }

and the error
     -attribute paths.'/api/discover/portfolio'(get).[visibility].default is not of type `array`


text:
Q: How to change the color of the icons in the activity bar using settings.json I've been following this tutorial by Coder Coder to make my vscode look better
(tutorial link https://youtu.be/pGzssFNtWXw).
As per the video I've opened the settings.json file and just wrote some code
But when I try to change the color of the icons in the activity bar, nothing happens, here is the line of code I tried to use to change the color:"activityBarBadge.foreground": "#000000" this does not work though
Here is the code:
"workbench.colorCustomizations": {
        "editor.background": "#000814",
        "sideBar.background": "#000d20",
        "sideBarTitle.foreground": "#ffd60a",
        "sideBarSectionHeader.foreground": "#ffd60a",
        "activityBar.activeBackground": "#ffea81d5",
        "activityBar.background": "#22223b",
        "statusBar.background": "#ffd60a",
    }

Here is the result I got:

A: To change the Activity Bar icon colors use these two colorCustomizations:
"activityBar.inactiveForeground"
"activityBar.foreground"  // for the active icon


text:
Q: Flutter Web: Images uploaded to firebase storage not showing preview I am migrating one of my apps to the web with flutter for the first time. My app uses firebase packages to post images to firebase storage. We know "file path" doesn't work on the web so I had to change to byte. But on the firebase storage, I discovered that the images posted through bytes cannot be previewed. If you click on the token, rather than a preview, it will just download straight away.
Here is a pictorial illustration of what I mean:
Images, when clicked are supposed to be able to show a preview like this

But this is what I get

I see they are uploaded as documents instead of file.
Please how do I rectify this.
This is my code below
  Future selectFile() async {
    final result = await FilePicker.platform.pickFiles(allowMultiple: false, type: FileType.image);

    if (result == null) return;
    final path = result.files.single;

    setState(() => imageFile = path);
  }

//upload
Future  upload() async {
  if (imageFile == null) return;

                    final fileName = imageFile!.name;
                    final destination = 'FTV/Thumbnails/$fileName';

                    // task = FirebaseApi.uploadFile(destination, file!);
                    task = FirebaseApi.uploadBytes(destination, fileBytes!);
                    setState(() {});

                    if (task == null) return;

                    final snapshot = await task!.whenComplete(() {});
                    var urlDownload = await snapshot.ref.getDownloadURL();

                    // print('Download-Link: $urlDownload');
                    setState(() {
                      imageURL = urlDownload;
                    });
}


text:
Q: GKE: Identity-aware proxy > L7 load balancer > Custom host and path rules > Error code 11 I am using GKE Identity-aware proxy > L7 load balancer > Custom host and path rules. It works fine for the root-path. But it does not work for custom paths.
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.global-static-ip-name: "my-static-ip"
spec:
  rules:
  - host: my.custom.org
    http:
      paths:
      - path: /v1/*
        backend:
          serviceName: webv1
          servicePort: 8080
      - path: /v3/*
        backend:
          serviceName: webv3
          servicePort: 8080
      - path: /nginx/*
        backend:
          serviceName: nginx
          servicePort: 80
      - path: /*
        backend:
          serviceName: nginx
          servicePort: 80

Path / and /nginx/ works fine. /v2/ and /v3/ throws There was a problem with your request. Error code 11.
If I disable the IAP, everything works fine.
Environment:

*

*Kubernetes version (use kubectl version): 1.12.7-gke.17

*Cloud provider or hardware configuration: GKE
Setting up HTTP Load Balancing with Ingress @ https://cloud.google.com/kubernetes-engine/docs/tutorials/http-balancer
Enabling Cloud IAP for GKE @ https://cloud.google.com/iap/docs/enabling-kubernetes-howto

A: This error code 11 is related to a misconfiguration of the OAuth client ID1.
I see that you the failing one are using a different serviceport. If you are serving the following 2 URLs from two different backends both may have IAP enabled but configured with different clientIds.
As of GCP does not support different clientIds for different paths, and the effort for IAP to use a single clientId across b/e services is underway. For now, if you can verify the clientId, and change it to a single one if they are different, that would work.
The recommended approach would be setting up an NGINX proxy. The ingress + IAP only have one service to deal with instead of two, and it will work like a charm.


text:
Q: How to import contracts in Cadence using flow.json instead of relative paths Importing contracts using their relative path is not working atm with the last version of the cadence language server. I was wondering what would be the alternative, when developing locally, for importing other contracts. My best guess is that it should be using the flow.json file, defining the paths for the contracts on it, but I cannot find how to specify on my contract that I want to it to use the config file for the imports

A: LSP and flow-cli both read the flow.json file and parse depedencies the same way.
In flow.json you specify the path to a file:

*

*https://github.com/findonflow/find/blob/main/flow.json#L38
In other contracst and interaction you then use the same path to import

*

*contract example: https://github.com/findonflow/find/blob/main/contracts/FindMarketSale.cdc#L1

*script example:https://github.com/findonflow/find/blob/main/transactions/register.cdc#L1
Hope that helps.


text:
Q: Enforcing run-time checks using the Flow type-system? In my application, a UUID is just a string that conforms to a particular regex:
'0b4ba6ba-496f-11e8-a21b-06f9c13aa914' // UUID

'hello world' // Not UUID

Now, I can check the format at run-time like this:
const isUuid = (x : string) : boolean => {
  const pattern = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
  return pattern.test(x);
};

This is a run-time check, but I can leverage the type-system to ensure that the check is performed on all code paths. Basically, I want to create a string-like type that is used to represent a string that has passed the isUuid check.
type Uuid = ?

let s : string = '0b4ba6ba-496f-11e8-a21b-06f9c13aa914';

let x : Uuid = s; // Type error

let y : Uuid = ensureUuid(s); // Type checked, but may throw at run-time

However, I want my existing code that takes UUIDs as strings to continue to work.
Is this possible in Flow?
// @flow

type Uuid = string;

const ensureUuid = (x : string) : Uuid => {
  if (!isUuid(x)) {
    throw new TypeError(x + ' is not a Uuid');
  }

  return x;
};

A: This is possible using the opaque keyword:

Opaque type aliases are type aliases that do not allow access to their underlying type outside of the file in which they are defined.

Docs: https://flow.org/en/docs/types/opaque-types/
You will need two files.
First uuid.js:
// @flow

export opaque type Uuid = string;

export const is = (x : string) : boolean => {
  const pattern = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;

  return pattern.test(x);
};

export const create = (x : string) : Uuid => {
  if (is(x)) {
    return x;
  }

  throw new TypeError('"' + x + '" is not a valid UUID');
};

Then the consumer, index.js:
// @flow

import * as uuid from './uuid';

import type { Uuid } from './uuid';

const s : string = '0b4ba6ba-496f-11e8-a21b-06f9c13aa914';

// const q : Uuid = s; // Type error!

const r : Uuid = uuid.create(s); // Type checked, but might throw a run-time error

// const h : Uuid = 'not allowed!';
// const i : Uuid = ('not allowed!' : Uuid);

With this setup, a Uuid instance can only be created via uuid.create.


text:
Q: Как разбивается выборка для обучения RCNN? Здраствуйте, помогите понять, пожалуйста.
Мнист взят только для описания ситуации:

(x_train, y_train), (x_test, y_test) = mnist.load_data()

Думаю многие видели эту строку, поажлуйста помогите понять как собрать аналог?
У меня дана выборка, два класса. Классификация в тексте, я создал словарь на всю выборку вида:
{name_file: num_class}
Как это всё состыковать, и как понять какие пропорции внутри? Я хочу рандом, без всяких наложений.
Далее у меня идёт такая конструкция в коде:

x_train_split, x_val_split, y_train_split, y_val_split = train_test_split(x_train, y_train_cat, test_size=0.2)
model.fit(x_train_split, y_train_split, batch_size=32, epochs=5, validation_data=(x_val_split, y_val_split))

Здесь я разбиваю вручную. Но в голове не проясняется. Как тут вообще понять в каких пропорциях разбивается общая выборка на тестовую и далее на обучающую с валидационной?
Я пролазил туториалки по тензорфлоу, по керасу, и по аугментациям зачем-то. У меня получилось в однмо варианте создать класс, в другом словарь. Но я не понимаю где и в каком месте далее это всё регулируется и при каких обстоятельствах считывается для сравнения результатов на всех этапах.. Ютуб уже закончился. Я даже класс могу в название файла записать, или разбить вручную по папкам. Взять чужой код с каггла и сделать рабочим, но это не даёт понимания.
Upd: Так, стоп. Я же могу применить train_test_split и в первом случае? а как будет выглядеть взаимодействие и код.. со словарём из названия файлов и класса? оно же не преобразуется в вектор нампи и класс? или да? о боже мой ..  %(

A: Не совсем понятна суть вопроса. Попробую ответить на то, что понял.
Команда:
x_train_split, x_val_split, y_train_split, y_val_split = \
    train_test_split(x_train, y_train_cat, test_size=0.2)

разбивает общую выборку на две части - обучающую 80% и валидационную 20%.
Дальше вы обучаете модель на обучающей выборке (80%) и проверяете качество модели на ваоидационной выборке (20%).
Я нигде не увидел в вашем коде никаких упоминаний о тестовой выборке.

Можно сделать немного по-другому:
разбиваем общую выборку на две части: 90% и 10% (тестовая выборка):
x_train_split, x_test_split, y_train_split, y_test_split = \
    train_test_split(x_train, y_train_cat, test_size=0.1)

При обучении модели можно воспользоваться параметром:

validation_split: Float between 0 and 1. Fraction of the training data to be used as validation data. The model will set apart this
fraction of the training data, will not train on it, and will evaluate
the loss and any model metrics on this data at the end of each epoch.
The validation data is selected from the last samples in the x and y
data provided, before shuffling. This argument is not supported when x
is a dataset, generator or keras.utils.Sequence instance.

model.fit(x_train_split, y_train_split, batch_size=32, epochs=5, validation_split=0.2)

т.е. keras откусит 20% от обучающей выборки x_train_split и будет использовать эту часть для валидации модели.
В самом конце вы можете протестировать модель на тестовой выборке, данные из которой модель не видела ни при обучении ни при валидации.

A:
https://www.tensorflow.org/tutorials/load_data/numpy

в туториале по тензорфлоу описано почти всё, что меня интересовало) спасибо за внимание
Загрузите массивы NumPy с помощью tf.data.Dataset
Предполагая, что у вас есть массив примеров и соответствующий массив меток, передайте два массива в виде кортежа в tf.data.Dataset.from_tensor_slices чтобы создать tf.data.Dataset
train_dataset = tf.data.Dataset.from_tensor_slices((train_examples, train_labels))

test_dataset = tf.data.Dataset.from_tensor_slices((test_examples, test_labels))

Перемешайте и пакетируйте наборы данных
BATCH_SIZE = 64
SHUFFLE_BUFFER_SIZE = 100
train_dataset = train_dataset.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)
test_dataset = test_dataset.batch(BATCH_SIZE)```


text:
Q: (400) Bad Request : Get AccessToken of Salesforce I am trying to fetch all the contacts from Salesforce via oauth in my application. I am getting The remote server returned an error: (400) Bad Request. when trying to get access token via API Token Url on my call back page. even When I have copy the URL and direct paste to the URL it is giving me correct data. but can't get the Access token.
I am using below method to Get Access token. Please experts suggest me where I am doing mistake. Same method is working fine for Google and LinkedIn.
public async Task<TokenResponse> GetAccessToken(string code,string tokenUrl,string consumerKey,string consumerSecretKey,string redirecturl)
    {

        string responseFromServer = "";
        var webRequest = WebRequest.Create(tokenUrl);

        const string queryStringFormat = @"code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code";
        string contents = string.Format(queryStringFormat
                                           , code
                                           , consumerKey
                                           , consumerSecretKey
                                           , redirecturl);

        webRequest.Method = "POST";
        byte[] postcontentsArray = Encoding.UTF8.GetBytes(contents);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.ContentLength = postcontentsArray.Length;
        using (Stream requestStream = webRequest.GetRequestStream())
        {
            requestStream.Write(postcontentsArray, 0, postcontentsArray.Length);
            requestStream.Close();
            WebResponse response = webRequest.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        responseFromServer = reader.ReadToEnd();
                        reader.Close();
                        responseStream.Close();
                        response.Close();
                    }
                }
            }

        }
        return JsonConvert.DeserializeObject<TokenResponse>(responseFromServer);
    }

Please help me to resolve this issue.

A: I'm connecting to Salesforce without issue, but am using HttpClient instead of WebRequest.
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                {"grant_type", "password"},
                {"client_id", _clientId},
                {"client_secret", _clientSecret},
                {"username", _userName},
                {"password", _password}
            }
                );

                using (var httpClient = new HttpClient())
                {
                    var message =
                        await httpClient.PostAsync(_authorizationUrl, content).ConfigureAwait(false);
                    var responseString = await message.Content.ReadAsStringAsync().ConfigureAwait(false);

                    var obj = JObject.Parse(responseString);

                    var oauthToken = (string)obj["access_token"];
                    var serviceUrl = (string)obj["instance_url"];
}


text:
Q: dmidecode and DDR3 memory
Possible Duplicate:
How to detect memory type under Linux?

I got NC9C-550-LF motherboard with 2 GiB DDR3 1033 MHz memory. but when I look at
dmidecode

the memory module is shown as below
 Memory Device
    Array Handle: 0x000C
    Error Information Handle: Not Provided
    Total Width: 64 bits
    Data Width: 64 bits
    Size: 2048 MB
    Form Factor: SODIMM
    Set: None
    Locator: DIMM0
    Bank Locator: BANK0
    Type: DDR2
    Type Detail: Synchronous
    Speed: 667 MHz
    Manufacturer: Manufacturer00
    Serial Number: SerNum00
    Asset Tag: AssetTagNum0
    Part Number: ModulePartNumber00
    Rank: Unknown

also, lshw -c memory shows as below
*-bank:0
      description: SODIMM DDR2 Synchronous 667 MHz (1.5 ns)
      product: ModulePartNumber00
      vendor: Manufacturer00
      physical id: 0
      serial: SerNum00
      slot: DIMM0
      size: 2GiB
      width: 64 bits
      clock: 667MHz (1.5ns)

Are there any other command line tools to identify the memory correctly in Fedora ?


text:
Q: Cannot boot in windows anymore after switching from ubuntu to fedora I had a dual boot setup in a single drive with ubuntu and windows 10. Ubuntu was installed from the install alongside windows option in the installer.
I recently decided to remove ubuntu and install fedora, which I did. But now, Windows no more appear in grub. How can I get Windows back in grub ?
Here is a screenshot of my config from gparted:

EDIT
I also tried to run sudo grub2-mkconfig > /dev/null to see if windows will be detected, but it is not. Here is the result of the command:
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-4.11.9-300.fc26.x86_64
Found initrd image: /boot/initramfs-4.11.9-300.fc26.x86_64.img
Found linux image: /boot/vmlinuz-4.11.8-300.fc26.x86_64
Found initrd image: /boot/initramfs-4.11.8-300.fc26.x86_64.img
Found linux image: /boot/vmlinuz-4.11.8-200.fc25.x86_64
Found initrd image: /boot/initramfs-4.11.8-200.fc25.x86_64.img
Found linux image: /boot/vmlinuz-0-rescue-99fd01fc6f9e4a34bd2f9ef304078b34
Found initrd image: /boot/initramfs-0-rescue-99fd01fc6f9e4a34bd2f9ef304078b34.img
done

A: I had similar challenges with combining Windows and Fedora dual-boot.  I use EasyBCD as the boot manager, installed on the Windows side and pretty straightforward.  It's been working fine for 3 years.


text:
Q: Parsing Python to a list of instances I want to parse Pure-Python Code into something like a list of instances of certain classes that represent various parts of the original code..
An example:
>>> text = '''
... for x in range(100):
...     print x
... '''
>>> tree = parse(text)
>>> print tree
Tree( ForLoop(x,Range(100), [Stmt(Print(x))]) )
# here ForLoop, Range, Stmt, Print are all custom classes

A: The ast module has the tools you need:
>>> import ast
>>> text = '''
for x in range(100):
    print x
'''

>>> m = ast.parse(text)
>>> ast.dump(m)
"Module(body=[For(target=Name(id='x', ctx=Store()), iter=Call(func=Name(id='range', ctx=Load()),
       args=[Num(n=100)], keywords=[], starargs=None, kwargs=None),
       body=[Print(dest=None, values=[Name(id='x', ctx=Load())], nl=True)], orelse=[])])"


text:
Q: Is it acceptable to define a "module" and "class" within a single .VB element? Experiment:
I have found it is possible to define both a "Module" (Namespace?) and a "Class" (Namespace?) within a single .Vb element (Module??).
You can try this at home:

*

*Create a new Console Application Project.
*A new .Vb element named "Module1.Vb" is automatically added to the project.

*Add a new Class .Vb element by right-clicking on the project in Solution Explorer>Add>Class...

*Give the new class the name Test.

*View the code for "Test.Vb" and paste in the following:

Imports System.Runtime.CompilerServices

Module ExtensionsTest
    <Extension()>
    Public Sub ToConsole(ByVal Ex As Exception)
        Dim ForeColor As ConsoleColor
        Console.ForegroundColor = ConsoleColor.Red
        Console.WriteLine()
        Console.WriteLine("An unhandled exception has occurred!")
        Console.WriteLine(Ex.ToString)
        Console.ForegroundColor = ForeColor
    End Sub
End Module

Class Test
    Public Sub Test()
        Try
            Dim test As New Object
            test.SomeMethodDoesntExist()
        Catch ex As Exception
            ex.ToConsole()
        End Try
    End Sub
End Class

View the Code for Module 1 and paste in the following:
Module Module1
    Sub Main()
        Try
            Dim tester As New Test
            tester.Test()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Module

Now go ahead and step through or run the application.  You'll see it all works.  So, let's move on to the...

Meat of the question
Is this acceptable practice?
It may be technically possible - but is it a bad solution for reasons I don't know?  (I'm a Mort and really don't want pick up bad coding practices unwittingly)
I originally had this as a Private method within the class definition like this:
Imports System.Runtime.CompilerServices
Class Test
    Public Sub Test()
        Try
            Dim test As New Object
            test.SomeMethodDoesntExist()
        Catch ex As Exception
            ToConsole(ex)
        End Try
    End Sub

    Private Sub ToConsole(ByVal Ex As Exception)
        Dim ForeColor As ConsoleColor
        Console.ForegroundColor = ConsoleColor.Red
        Console.WriteLine()
        Console.WriteLine("An unhandled exception has occurred!")
        Console.WriteLine(Ex.ToString)
        Console.ForegroundColor = ForeColor
    End Sub
End Class

I decided it would be cleaner to define the ToConsole sub as an extension method for Exception objects, but that's where I ran into trouble.  When I created the Extension attribute within the Class namespace, I got a compiler error:

Extension methods can be defined only in modules.

So, I tried the above experiment and I declared a Module within the same .VB element where my Class is defined.
As the experiment above shows, this all compiles fine and works as expected, but I'd like to know if this is a good idea or not, and why?
Thanks for taking any time to read this and even more thanks for any time taken to comment or answer!

A: In general, the idea of one Class or Module per file is something I first noticed in Java (I believe it is/was a requirement there). C# has continued this as a suggestion, and VB.NET probably now has the same suggestion somewhere.
However, as the VB.NET designers decided you can only have extension methods in Modules, you've provided an example where it makes sense for another unit of code to be so closely related to another Class as to include it in the same file.
Of course, with the concept of Partial classes and modules you have the opposite idea of splitting single units across multiple files available too.
And BTW this concept normally means your Module would be named TestExtensions :-)
To your "Namespace?" notes in your question: VB.NET provides a Project-based namespace for your Modules and Classes, so your classes are now named ProjectNamespace.UnitName. If you provided a
Namespace SomeNamespace
...
End Namespace

the enclosed units would be named ProjectNamespace.SomeNamespace.UnitName.
You can have multiple Namespaces in a file too, and you can override the ProjectNamespace with Global.:
Namespace Global.TopLevelNamespace
...
End Namespace

Rereading your question and noting the "(Module?)" note as well, I'm guessing you're actually asking what is the "formal" VB.NET term for code units that include Class and Module and the similar term for a file of code. Because the .NET Module is so often equivalent to an Assembly, most people would know what you meant if you referred to "Namespace-level" code units as "modules", and source files are just "files". (There may be other places that give alternatve names, but I've based this on Microsoft's Introduction.)

A: As you've found out, code works fine regardless of which file you put it in.  So it comes down to organization... where will you put things?
What I've found is that any departure from the "standard" conventions makes it very difficult to navigate through a code base of any significant size.  You say you have this little helper class, but where the hell is it?  You put it in a different solution, and I have a metadata reference to it, but where did you actually put it?  Unless you adhere strictly to the one file per class/interface/whatever, you've now forced me to do a search, and I'm coming after you with a carving knife.
This Stack Overflow post lists some of the exceptions where it might make sense to break this rule:

*

*Partial classes,

*Extension methods,

*Enums that only pertain to a single class, although I still generally put those in their own file.


text:
Q: Transmission coefficient and transmission probability Are transmission coefficient and transmission probability the same terms? If not, could you please explain how they are related to each other?

A: I think at least in the case of tunneling of particles through potential barriers, the transmission coefficient and the transmission probability are the same. This make sense since
$$R + T = 1$$
where $R$ and $T$ are the reflection and the transmission coefficients respectively. Also the following are always true
$$R, T\ge 0,~\text{and}~ R, T \le 1$$
The two above formula are postulates of probability measures in mathematics.

A: In the context of scattering theory, Transmission coefficient and transmission probability usually mean the same thing, but not the same thing as the transmission amplitude.
Transmission coefficient is however are "more correct" term, as it is defined via the scattering matrix. Interpreting it as a probability may be tricky, as it implies that we need to define the initial and the final states between which the transition occurs or something similar.
Note also that these terms are specific to one-dimensional applications of the scattering matrix formalism - in higher dimensions we cannot meaningfully distinguish transmission and reflection, but rather speak about scattering at certain angle (again, it is not uncommon to say probability of scattering at a certain angle).


text:
Q: Saving Drawable to Disk and retrieving - Android how would I save a drawable to the SDcard (custom folder) and later retrieve it assuming im keeping track of the path of the saved item.
Thanks,
Faisal

A: I assume you want to download images from Internet?
You can use FileOutputStream to save the images, and you can use File.mkdirs() to create custom directory on the SD Card.
If you want to load the image later, you can use BitmapFactory.decodeFile(String pathName).


text:
Q: Realm access from incorrect thread Exception while a copy was sent using copyFromRealm When streaming copy of realm objects instead of realm reference and observing it on Schedulers.IO thread, there is a crash with the famous exception message "Realm access from incorrect thread. Realm objects can only be accessed in the thread they were created."
Shouldn't the copy be thread free? Can I produce it from one thread and process it on a different thread?
This is how I am creating observable.
 public Observable<Brand> getAllBrands() {
    return realm.where(Brand.class)
            .findAll()
            .asObservable()
            .flatMap(Observable::from)
            .map(brand -> realm.copyFromRealm(brand));
}

Following is how I observe getAllBrands().
 Observable<Brand> brandObservable = dataManager.getAllBrands();

    brandObservable.observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Observer<Brand>() {
                @Override
                public void onCompleted() {
                    Log.d("reactive", "completed");
                }

                @Override
                public void onError(Throwable e) {
                    Log.d("reactive", e.getMessage());
                }

                @Override
                public void onNext(Brand brand) {
                    dataSource.add(brand.getName());
                    myAdapter.notifyDataSetChanged();
                }
            });

A: You are subscribing on schedulers.io while using the Realm instance from the UI thread:
realm.where(Brand.class)
        .findAll()
        .asObservable()
        .flatMap(Observable::from)
        .map(brand -> realm.copyFromRealm(brand)) // realm instance on the wrong thread
        .subscribeOn(schedulers.io());

What are you after is an easy way to move a query across threads, which is still work-in-progress here: https://github.com/realm/realm-java/pull/1978. Until then you can work around it by doing it yourself like this:
public Observable<Brand> getAllBrands(final Realm realm) {
    return Observable.create(new Observable.OnSubscribe<List<Brand>>() {
        @Override
        public void call(final Subscriber<? super List<Brand>> subscriber) {
            Realm obsRealm = Realm.getInstance(realm.getConfiguration());
            final RealmResults<Brand> results = obsRealm.where(Brand.class).findAll();
            final RealmChangeListener listener = new RealmChangeListener() {
                @Override
                public void onChange() {
                    subscriber.onNext(realm.copyFromRealm(results));
                }
            };
            results.addChangeListener(listener);
            subscriber.add(Subscriptions.create(new Action0() {
                @Override
                public void call() {
                    realm.removeChangeListener(listener);
                    realm.close();
                }
            }));

        }
    })
    .flatMap(Observable::from);
}

Note that Realm Changelisteners only work on Looper threads which means you probably need to change your worker thread to a H
HandlerThread bgThread = new HandlerThread("workerThread");
Handler handler = new Handler(bgThread.getLooper());

getAllBrands(realm).subscribeOn(HandlerScheduler.from(handler));

A: QUESTION

Can I produce it from one thread and process it on a different thread?

Answer is NO. You can read the description of realm in here

Although Realm files can be accessed by multiple threads concurrently, you cannot hand over Realms, Realm objects, queries, and results between threads. The thread example shows how to use Realm in a multithreading environment.


text:
Q: If $a^{n-1} \equiv 1 \pmod{n}$, can we say that $(a,n) = 1$? If $a^{n-1} \equiv 1 \pmod{n}$, can we say that $(a,n) = 1$? If not, what conditions do we need to make this argument true? Any idea?
Thanks,

A: We have the following two elementary facts that you may be overlooking:

*

*If $a\equiv b\pmod{n}$, then $\gcd(n,a) = \gcd(n,b)$ (since $\gcd(n,a) = \gcd(n,a+kn)$ for any $k$, and $a\equiv b\pmod{n}$ implies that $b=a+kn$ for some $k$).

*If $a|b$, then $\gcd(n,a)|\gcd(n,b)$. Simply note that any common divisor of $n$ and $a$ must be a common divisor of $n$ and $b$, since $a|b$ holds.
So, if $m\geq 1$ and $a^m\equiv 1\pmod{n}$, then since $a|a^m$ we have
$$\gcd(n,a) \;|\; \gcd(n,a^m) = \gcd(n,1) = 1,$$
hence $\gcd(n,a)=1$.
In particular, for $a^{n-1}\equiv 1 \pmod{n}$: if $n\gt 1$, then apply the observation above with $m=n-1$. If $n=1$ then you cannot apply the observation, since then you have $n-1 = 0$, but if $n=1$, then $\gcd(n,a) = \gcd(1,a) = 1$ as well.

A: Yes. Suppose $n>1$. Since $a^{n-1}$ is relatively prime to $n$, $a$ and $n$ can share no common prime factors.
In fact, you may note that the invertible elements in the ring of integers mod $n$ are precisely the integers (or residue classes thereof) prime to $n$. So since $a$ has an inverse in this ring (namely, $a^{n-2}$), $a$ must be relatively prime to $n$.
(If $n =1$, the statement is true automatically.)

A: Or as noted, that holds for any $m\geq 1.$ Since, if $\gcd(a,n)=d$ then $d|n|a^m-1$ and $d|a.$ Hence, $d|1$ and we're done.


text:
Q: Mockito Java doAnswer This won't compile. I get an UnfinishedStubbingException. I've read the Mockito api and other questions on this site and I think that my syntax shouldn't be wrong, but it fails at doAnswer(new Answer() {, so I figure it has to be wrong, but I don't know where. Thanks.
doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                ((CrestronNioSocketHandler.NioEventReceiver) args[0]).onDataReceived(new byte[wantedNumber]);
                return null;
            }
        }).when(mockedChannel.read(any(ByteBuffer.class)));

A: It should be like this
doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                ((CrestronNioSocketHandler.NioEventReceiver) args[0]).onDataReceived(new byte[wantedNumber]);
                return null;
            }
        }).when(mockedChannel).read(any(ByteBuffer.class));

Check this question about different ways of stubbing with Mockito.


text:
Q: Указатели Си,среднее арифметическое Почему не работает?Задача состоит в нахождении среднего арифметического с помощью указателей.
Выдаёт Segmentation fault (core dumped)
  #include <stdio.h>
    #include <stdlib.h>
    float main() {
    float* a ;
    float* b ;
    float* c ;
    float* res;
    scanf("%float", a);
    scanf("%float", b);
    scanf("%float", c);
    *res = (float)(*a + *b + *c) / 3;
    printf("%f\n", *res);
    return 0;
    }

A: #include <stdio.h>
#include <stdlib.h>

int main(void) {   // int, не float!!
    float a, b, c, res;
    scanf("%f", &a);  // Не %float!
    scanf("%f", &b);
    scanf("%f", &c);
    res = (a + b + c) / 3;
    printf("%f\n", res);
}

Ну, держите указатели...
#include <stdio.h>
#include <stdlib.h>

int main(void) {   // int, не float!!
    float *a = malloc(2*sizeof(float));
    *(a+1) = 0;
    for(int i = 0; i < 3; ++i)
    {
        scanf("%f", a);  // Не %float!
        *(a+1) += *a;
    }
    printf("%f\n", *(a+1)/3);
    free(a);
}

A: Ну, если только указатели...
#include <stdio.h>
#include <stdlib.h>

int
main (int ac, char *av[])
{
  float a, b, c,
    *pa = &a, *pb = &b, *pc = &c;

  if (scanf("%f %f %f", pa, pb, pc) == 3)
    printf("%f\n", (*pa + *pb + *pc) / 3);
  else
    puts("input error");

  return puts("End") == EOF;
}

Конечно, память можно было бы и malloc()-м выделить, например, вот так
float *pa = malloc(sizeof(float) * 3),*pb = pa + 1, *pc = pa + 2;
но решил не усложнять пример для новичка


text:
Q: How to replace key val in json using shell sample Json file
{
    "abc":"n",
    "123":"y",
    "atom" :"csv",

}
after replaced the json
{
    "abc":"try",
    "123":"finish",
    "atom" :"err",

}

A: you can use jq:
jq '."abc"="try" | ."123"="finish" | ."atom"="err"' d.json

output :
{
  "abc": "try",
  "123": "finish",
  "atom": "err"
}

but unfortunately jq does not support in-place editing, so you must redirect to a temporary file first and then replace your original file with it, or use sponge utility from the more utils package, like that:
jq '."abc"="try" | ."123"="finish" | ."atom"="err"' file.json|sponge file.json


text:
Q: Speed up createFile call on volumes I'm writing a software to communicate to a recording device that
if connected to the pc via USB emulates a mass storage device.
Some special features are accessed on that device by communicating
on a special sector on that device. To get access on that sector on windows
I need to:

*

*open a handle to the newly arrived drive

*fetch the physical drive number via deviceIOControl and IOCTLVolumeGetVolumeDiskExtents

*Open the physicaldrive found there and read and write to a special sector.

So far so good - everything is working fine but getting the first initial
volume handle can take quite long.
what I'm doing is basically this:
var hdl : THandle;
    start, stop, freq : INT64;
begin
     hdl := INVALID_HANDLE_VALUE;

     QueryPerformanceFrequency(freq);
     QueryPerformanceCounter(start);

     fHandle := CreateFile( PChar('\\.\' + fDriveLetter + ':'),
                        GENERIC_READ,
                        FILE_SHARE_WRITE or FILE_SHARE_READ,
                        nil,
                        OPEN_EXISTING,
                        0,
                        0);

     QueryPerformanceCounter(stop);
     OutputDebugString( PChar( Format('Open drive took %.3fms', [(stop - start)/freq*1000]) ));

     if hdl = INVALID_HANDLE_VALUE then
        raise EVolumeError.Create( 'Cannot Open Drive: '+fDriveLetter+#13#10+
                               SysErrorMessage(GetLastError));
end;

This call can take seconds right until the drive arrived.
My guess is that windows first reads the complete FAT which takes long on
this little recording device which actually always creates files that
reserves the complete disk space (4GB).
Anyone has an idea how to speed up that process? I never need to read anything
from the file system but rather I need the handle the get information
about the underlying physicaldrive number and from there I do my read and write operations.


text:
Q: AppEngine Standard Python 3.7 does not provide error message with 500 response I'm creating an AppEngine application with python3.7 standard environment. The application works ok locally, but when uploaded it throws a 500 error in the browser it shows:
"Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application."

Debugging is not enabled for python3.7 (it tells me that when viewing the debugger). And the log entries don't have the hint of an error message within them against the 500 response.
How do I proceed to debug and understand what's happening to the application?
I should note that I'm attempting to use a Selenium webdriver to run headless chrome and I'm not 100% sure this is compatible with this environment, I was just trying to give it a go.
Adding in log as suggested
https://console.cloud.google.com/logs/viewer?project={project-id}&resource=gae_app%2Fmodule_id%2Fdefault%2Fversion_id%2F20180916t193009&minLogLevel=0&expandAll=false&timestamp=2018-09-17T18%3A18%3A21.295000000Z&customFacets&limitCustomFacetWidth=true&interval=PT1H&scrollTimestamp=2018-09-17T18%3A16%3A59.235127000Z&advancedFilter=resource.type%3D%22gae_app%22%0Aresource.labels.zone%3D%22us-west2-3%22%0Aresource.labels.project_id%3D%22{project-id}%22%0Aresource.labels.version_id%3D%2220180916t193009%22%0Aresource.labels.module_id%3D%22default%22%0Atimestamp%3D%222018-09-17T18%3A16%3A57.883459000Z%22%0AinsertId%3D%225b9fef9e0005ebc57890705d%22&dateRangeUnbound=both

{
 httpRequest: {
  status:  500
 }
 insertId:  "5b9fef9e0005ebc57890705d"
 labels: {
  clone_id:  "00c61b117c38b726d0ba73ce89f222fe10b9b189fae907de84b949ab7a3b88ec4bdc4484"
 }
 logName:  "projects/{project-id}/logs/appengine.googleapis.com%2Frequest_log"
 operation: {
  first:  true
  id:  "5b9fef9900ff0d7b03fbff00a7c100016d7e7370656e642d6d6f6e69746f720001323031383039313674313933303039000100"
  last:  true
  producer:  "appengine.googleapis.com/request_id"
 }
 protoPayload: {
  @type:  "type.googleapis.com/google.appengine.logging.v1.RequestLog"
  appEngineRelease:  "1.9.64"
  appId:  "m~{project-id}"
  cost:  4.7272999999999996e-8
  endTime:  "2018-09-17T18:17:02.387819Z"
  finished:  true
  first:  true
  host:  "{project-id}.appspot.com"
  httpVersion:  "HTTP/1.1"
  instanceId:  "00c61b117c38b726d0ba73ce89f222fe10b9b189fae907de84b949ab7a3b88ec4bdc4484"
  instanceIndex:  -1
  ip:  "80.195.185.178"
  latency:  "4.504360s"
  line: [
   0: {
    logMessage:  "This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application."
    severity:  "INFO"
    time:  "2018-09-17T18:17:02.387649Z"
   }
  ]
  megaCycles:  "6127"
  method:  "GET"
  requestId:  "5b9fef9900ff0d7b03fbff00a7c100016d7e7370656e642d6d6f6e69746f720001323031383039313674313933303039000100"
  resource:  "/"
  responseSize:  "423"
  startTime:  "2018-09-17T18:16:57.883459Z"
  status:  500
  traceId:  "37cee4aaaa0b14fbaa6d57b7842527dc"
  traceSampled:  true
  urlMapEntry:  "auto"
  userAgent:  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
  versionId:  "20180916t193009"
  wasLoadingRequest:  true
 }
 receiveTimestamp:  "2018-09-17T18:17:02.563417716Z"
 resource: {
  labels: {
   module_id:  "default"
   project_id:  "{project-id}"
   version_id:  "20180916t193009"
   zone:  "us-west2-3"
  }
  type:  "gae_app"
 }
 severity:  "INFO"
 timestamp:  "2018-09-17T18:16:57.883459Z"
 trace:  "projects/{project-id}/traces/37cee4aaaa0b14fbaa6d57b7842527dc"
 traceSampled:  true
}

A: In order to debug this further I inserted a try/catch block like so:
try:
   {application code}
except Exception as e:
   return str(e)
This lands the top level error message in the browser when the application fails.


text:
Q: Right way to handle list of objects in a "polymorphic" way I am looking for way to handle a list of objects in a "polymorphic" way in the manner that you can for a single object.  Just to recap what does work:
interface Animal{
   fun sayHello(): String
}
class Dog: Animal{
   override fun sayHello() = "Hello, I'm a dog"
}
class Cat: Animal{
   override fun sayHello() = "Hello, I'm a cat
}

fun printGreeting(animal: Animal){
   println(animal.sayHello())
}

Then of course I can do the following:
val cat = Cat()
val dog = Dog()
printGreeting(cat) // "Hello, I'm a cat"
printGreeting(dog) // "Hello, I'm a dog"

Now imagine I have a List<Animal> and want to handle that in a similar way.  I know the following won't work:
fun List<Cat>.sayHello() = "Hello, we are a herd of cats"
fun List<Dog>.sayHello() = "Hello, we are a pack of dogs"

fun printGreeting(animals: List<Animal>){
    println(animals.sayHello())
}

I understand that, due to JVM type erasure, the compiler won't even allow you to declare the above extension functions, since after the erasure it amounts to a redeclaration of the same function.
I am looking for a design pattern that allows me to get the the desired behavior.  Any ideas?


text:
Q: JetBrains DotTrace I have setup the dotTrace for the website hosted in IIS server. When JetBrains dotTrace starts, the IIS website running fine and the profile starts. After the completing profile, the IIS website is not loading and it seems locked by the dotTrace. The website cannot able to start from IIS server.
The website again starts running if JetBrains dotTrace starts running again. This seems some service related with IIS webserver is getting locked by the dotTrace.
Please have a look at the issue.


text:
Q: Align ylabel in gnuplot multiplot Is there a way to align vertically the y labels of in gnuplot's multiplot so that they are below each other? The problematic example is below (the red line is annotation showing the problem):
set xrange[0:10]
set multiplot layout 2,1 margins 0.1,0.95,0.1,0.95 spacing 0,0
set ylabel "y1\nlabel"
set ytics
set format y "%.2f"
plot -1000*cos(x)**2 w l lt 4 lw 2
set ylabel "y2\nlabel"
set format y "%.1f"
plot cos(x) w l lt 5 lw 2
unset multiplot

which generates:

And I would like to automatically position the labels such, that the red annotated line "touches the same text". Note that I am really interested in automatic way or more correct way that a workaround using a trial and error with set ylabel "lable" offset -x,0

A: As you already noted, you can set an offset to the x- or y-label (check help xlabel), however, no absolute position.
This you can do with setting your own label. You can set the position relative to the screen and/or relative to the graph. gnuplot keeps these values for the second plot, no need to specify again. Check help label.
Check the following example:
Code:
### align ylabels in multiplot
reset session

set xrange[0:10]

set multiplot layout 2,1 margins 0.15,0.95,0.1,0.95 spacing 0,0

    set format x ""
    unset ylabel
    set label 1 "y1\nlabel" at screen 0.02, graph 0.5 center rotate by 90
    set ytics 200
    set ytics add ("" -1000)   # remove -1000
    set format y "%.2f"
    set grid x,y
    plot -1000*cos(x)**2 w l lt 4 lw 2

    set format x
    set label 1 "y2\nlabel"
    set ytics 0.4
    set format y "%.1f"
    plot cos(x) w l lt 5 lw 2

unset multiplot
### end of code

Result:


text:
Q: Innodb : cannot allocate the memory for the buffer pool My innodb keeps crashing. This is the error message below. Does anyone know why this keeps happening?
InnoDB: by InnoDB 49201616 bytes. Operating system errno: 12
InnoDB: Check if you should increase the swap file or
InnoDB: ulimits of your operating system.
InnoDB: On FreeBSD check you have compiled the OS with
InnoDB: a big enough maximum process size.
InnoDB: Note that in most 32-bit computers the process
InnoDB: memory space is limited to 2 GB or 4 GB.
InnoDB: We keep retrying the allocation for 60 seconds...
0 processes alive and '/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf ping' resulted in
/usr/bin/mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
InnoDB: Fatal error: cannot allocate the memory for the buffer pool
[ERROR] Default storage engine (InnoDB) is not available

A: You're running out of memory. That's what OS error 12 is. (see /usr/include/asm-generic/errno-base.h)
It looks like it's happening on startup.  What else are you running on the box? How big a buffer pool are you asking InnoDB to create? Are you running 64-bit or 32-bit? Do you have any swap?
Wade.


text:
Q: How to enforce HTTP redirect to HTTPS on Node.js? I have a node server that looks like this:
const express = require("express");
const app = express();
const port = 8000;
const https = require("https");
const fs = require("fs");

const credentials = {
  key: fs.readFileSync("../auth/key.pem"),
  cert: fs.readFileSync("../auth/cert.pem"),
};

const server = https.createServer(credentials, app);
const io = require("socket.io")(server, { cors: { origin: "*" } });

app.get("/", (req, res) => {
  console.log("redirecting http to https");
  if (req.headers.host.match(/^www/) !== null || !req.secure) {
    return res.redirect(
      "https://" + req.headers.host.replace(/^www\./, "") + req.url
    );
  }
});

server.listen(port, () => console.log(`Server is running on port ${port}`));

It should redirect any query from http to https. However, if I go to http://.com/ I get:
<myurl>.com didn't send any data.
ERR_EMPTY_RESPONSE

I assume this is because in my server, I used https, not http. I can't use http, as I need the server to have an ssl certificate, which requires https. Whatever I end up with, it can only run on one port, so is there any way to implement logic that if a request hits http://.com/ it redirects to https?

A: Usual practice to have your express server to stay http and use nginx reverse proxy to handle http to https redirections. Also you most probably care for domain names only in production, so make it work in dev on localhost:someport first, then when you have your server deployed check that your domain resolved to ip address of your vm and specify that domain name in nginx config.


text:
Q: Is opIndexAssign possible in C++? The D Programming Language Version 2 has a nifty method to overload an expression like this:
classInstance[someName] = someValue;

Or as D Function defined in this little example:
ref Map opIndexAssign(ref const(ValueT) value, ref const(NameT) name)
{
    this.insert(name, value);
    return this;
}

Is this possible in C++ (ideally without using the STL)? If so, how?

A: Normally, you would use a proxy object as the return type of operator[]; that object will have a custom operator= defined.  The vector<bool> specialization in the C++ Standard Library uses a proxy to get the behavior you are looking for.  The proxy-based solution isn't as transparent as the D version, though.  The code is something like:
class proxy;

class my_map {
  public:
  proxy operator[](const key_type& k);
  // Rest of class
};

class proxy {
  my_map& m;
  key_type k;
  friend class my_map;
  proxy(my_map& m, const key_type& k): m(m), k(k) {}

  public:
  operator value_type() const {return m.read(k);}
  proxy& operator=(const value_type& v) {m.write(k, v); return *this;}
};

proxy my_map::operator[](const key_type& k) {
  return proxy(*this, k);
}

A: Not being familiar with D, I'm going to have to assume that your first code snippet ends up calling opIndexAssign with value = someValue and name = someName?
If so, it can be done in C++, but not in such a simple manner. You could overload the [] operator, and return a proxy object with a custom = operator as follows (very basic, contrived example):
class MyProxy
{
    public:
        MyProxy (int& ref) : valueRef(ref) { }
        MyProxy& operator = (int value) { valueRef = value; return *this; }
    private:
        int& valueRef;
};

class MyClass
{
    public:
        MyProxy operator [] (std::string name);
    private:
        int myVal;
};

MyProxy& MyClass::operator [] (std::string name)
{
    if (name.compare("myVal"))
        return MyProxy(myVal);

    ...
}

int main ( )
{
    MyClass mc;

    mc["myVal"] = 10; // Sets mc.myVal to 10
}

I'd like to strongly stress that the above is not very pretty/well formed code, just an illustration. It has not been tested.
EDIT: Too quick for me Jeremiah!!!


text:
Q: how to save entire recordset that was checked on checkboxes I have a form for tracking work progress of each staff. Since one staff can do many tasks at a day. Therefore to save working time, I created checkboxes for task so that i can select and save as multi-records at a time. My code is as below

        <%
          if rsPdtn_sizeColor.eof then
             call displayNotFoundRecord
          Else
             Do Until  rsPdtn_sizeColor.Eof
        %>

<input type="checkbox" name="pdtn_szcl_id" value="<%=rsPdtn_sizeColor.fields.item("pdtn_szcl_id")%>"> <%=rsPdtn_sizeColor.fields.item("pdtn_st_size")%>   <%=rsPdtn_sizeColor.fields.item("pdtn_st_color")%>

<input type="text" name="pdtn_qty" value="<%=rsPdtn_sizeColor.fields.item("pdtn_st_qty_est")%>" size="7">

        <%
             rsPdtn_sizeColor.movenext
             Loop
           End if

        rsPdtn_sizeColor.movefirst
        %>

<input name="pdtn_note" value="<%=pdtn_note%>" size="39">

However, with this code, only field "pdtn_szcl_id" that can pass only recordset that i checked. I want "pdtn_qty" to do the same as well. So could you please help me on this. Thank you

A: The problem is that you should not have form elements like input with duplicate names. There are a couple of possible solutions but this is probably the safest.
In your code add the database id to the name of the checkbox and qty textbox, something like this:

<input type="checkbox" name="pdtn_szcl_id_<%=rsPdtn_sizeColor.fields.item("pdtn_szcl_id")%>"> <%=rsPdtn_sizeColor.fields.item("pdtn_st_size")%>   <%=rsPdtn_sizeColor.fields.item("pdtn_st_color")%>

<input type="text" name="pdtn_qty_<%=rsPdtn_sizeColor.fields.item("pdtn_szcl_id")%>" value="<%=rsPdtn_sizeColor.fields.item("pdtn_st_qty_est")%>" size="7">

Then when you want to retrieve the values you will need to open your recordset again and loop through the rows checking if the checkbox has been checked and getting the value, something like this:
<%
'Open your rsPdtn_sizeColor recordset again
Do Until rsPdtn_sizeColor.Eof
    If Request.Form("pdtn_szcl_id_" & rsPdtn_sizeColor.fields.item("pdtn_szcl_id")) = "on" Then
         'This checkbox was checked
         id = rsPdtn_sizeColor.fields.item("pdtn_szcl_id")
         qty = Request.Form("pdtn_qty_" & rsPdtn_sizeColor.fields.item("pdtn_szcl_id"))
         'This gives you the ID and Qty entered for each row
    End If
    rsPdtn_sizeColor.movenext
Loop
%>

NB. I used Request.Form but if you use form method GET then you should change to Request.QueryString.


text:
Q: tomcat atomikos hibernate NullPointerException Hope to get an appropriate advice from you to solve my problem as i wasn't able to fix this bug for several days.
I have embedded tomcat and trying to work with JTA transactions. However, when i am trying to use my DAO class, i get NullPointerException.
I tried to follow this article: http://www.javacodegeeks.com/2013/07/spring-jta-multiple-resource-transactions-in-tomcat-with-atomikos-example.html
Here is my Controller:
@Controller
@RequestMapping(value = "student")
public class StudentController {

@Autowired
StudentService studentService;

public StudentController() {

}

@RequestMapping(value = "/test/{id}/pass/{testId}", method = RequestMethod.GET, produces = "application/json")
public
@ResponseBody
Response getCurrentTest(@PathVariable("id") String id,@PathVariable("testId") String testId){
    TestDTO testDTO = studentService.getCurrentTest(id,testId);

    return Response.status(200).entity(testDTO).build();

}

}
Here is my spring-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<context:component-scan base-package="com.bionic"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
    <property name="persistenceUnitName" value="com.bionic.quiz" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
            <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
        </bean>
    </property>
</bean>

<bean id="jpaVendorAdapter"
      class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="database" value="HSQL"/>
    <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect"/>
</bean>

<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>

<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
    <property name="forceShutdown" value="false" />
</bean>

<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.J2eeUserTransaction">
    <property name="transactionTimeout" value="300" />
</bean>

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"
      depends-on="atomikosTransactionManager,atomikosUserTransaction">
    <property name="transactionManager" ref="atomikosTransactionManager" />
    <property name="userTransaction" ref="atomikosUserTransaction" />
    <property name="allowCustomIsolationLevels" value="true" />
</bean>

<bean id="dataSource"
      class="com.atomikos.jdbc.AtomikosDataSourceBean"
      init-method="init" destroy-method="close">
    <property name="uniqueResourceName">
        <value>DataSource</value>
    </property>
    <property name="xaDataSourceClassName">
        <value>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</value>
    </property>
    <property name="xaProperties">
        <props>
            <prop key="databaseName">quizzes</prop>
            <prop key="serverName">localhost</prop>
            <prop key="port">3306</prop>
            <prop key="user">root</prop>
            <prop key="password">1</prop>
            <prop key="url">jdbc:mysql://localhost:3306/quizzes</prop>
        </props>
    </property>
</bean>

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee>

<display-name>BQP</display-name>

<!--Spring-->
<servlet>
    <servlet-name>Spring MVC Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc-context.xml</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>Spring MVC Servlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

<resource-ref>
    <description>MySQL DS</description>
    <res-ref-name>jdbc/DataSource</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

<!--/Spring-->

Here is what i get when debugging my project:

in chrome:

end finally my log file, i will post it as a picture because i have problem with formatting here:

Also, i think, the problem is here, i have several warings before exceptions:
WARNING: atomikos connection proxy for com.mysql.jdbc.jdbc2.optional.JDBC4ConnectionWrapper@c20ee4: WARNING: transaction manager not running?


text:
Q: Ubuntu nohup shutdown specific script lets say we do:

sudo nohup ./start.sh process1
sudo nohup ./start.sh process2
sudo nohup ./start.sh process3

./start.sh is running a python file that loops forever.
Now, how do I kill the 'process2'?
I can do killall python and all of them would be shutdown.
Is it possible to kill 'proccess2' specifically somehow mark it or something?

A: You can try this;
user@host:/tmp/pythontest$ cat start.sh
#!/bin/sh
/usr/bin/python /tmp/pythontest/$1 &

user@host:/tmp/pythontest$ ./start.sh test1.py
user@host:/tmp/pythontest$ ./start.sh test1.py
user@host:/tmp/pythontest$ ./start.sh test1.py

user@host:/tmp/pythontest$ ps -ef | grep -i python
user   19447  2062  0 14:37 pts/32   00:00:00 /usr/bin/python /tmp/pythontest/test1.py
user   19449  2062  0 14:37 pts/32   00:00:00 /usr/bin/python /tmp/pythontest/test1.py
user   19451  2062  0 14:37 pts/32   00:00:00 /usr/bin/python /tmp/pythontest/test1.py
user   19454 11980  0 14:38 pts/32   00:00:00 grep --color=auto -i python

Second field is pid number.
user@host:/tmp/pythontest$ kill -9 19449

user@host:/tmp/pythontest$ ps -ef | grep -i python
user   19447  2062  0 14:37 pts/32   00:00:00 /usr/bin/python /tmp/pythontest/test1.py
user   19451  2062  0 14:37 pts/32   00:00:00 /usr/bin/python /tmp/pythontest/test1.py
user   19457 11980  0 14:38 pts/32   00:00:00 grep --color=auto -i python


text:
Q: Excel Web Query Parameters Error I'm having troubles adding parameters to a Web Query that reads currency rates.
Parameter: date format that updates daily (YEARMONTHDAY) in Cell ("A1") - As ["datums"]
URL: http://www.bank.lv/vk/ecb.xml?date=["datums"]
Error - in URL:

Error - in Excel:

Excel - Parameter:


text:
Q: iOS: parse url of a selected row in didSelectRowAtIndexPath method A. Is it possible/appropriate to initialize NSXML parse for a selected row inside didSelectRowAtIndexPath in order to populate the detail view that the method pushes to? I want to parse the URL associated with the title of a selected item as a detailview...
B. If yes, then how can I make it happen? I have 'afeed.title' In the following critter:
NSXMLParser *urlParser = [[NSXMLParser alloc] initWithContentsOfURL:afeed.url];

A caution line exclaims at afeed.url: "Incompatible pointer types sending 'NSString *' to parameter of type 'NSURL *'"
afeed is create by this:
ArticleGroupLink *afeed = [array objectAtIndex:indexPath.row];

ArticleGroupLink is a class containing title (title was used in the cellForRowAtIndexpath method) & url (string & @ property), which synthesizes them.
Let me know anything else that I need to share : )

A: As the compiler is trying to tell you is that it's expecting a NSURL object but instead you are giving it a NSString object.
So you can try to convert your NSString into a NSURL by doing something like this:
NSString *urlString = afeed.url;
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Then you can do:
NSXMLParser *urlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];


text:
Q: How to use Erlang Distribution Function Scipy I want to randomly generate numbers that follow a Erlang Distribution for an arrival process. I want to set the number of arrivals k as a parameter of the Erlang Distribution.
scipy.stats.erlang.rvs(a, loc=0, scale=1, size=1, random_state=None)

I am not so sure what loc and scale mean, as in the documentation they did not really clarify what they represent.
Any help would be appreciated.

A: As Erlang distribution is a particular case of the Gamma distribution, by checking the gamma documentation:

The probability density above is defined in the "standardized" form. To shift and/or scale the distribution use the loc and scale parameters. Specifically, gamma.pdf(x, a, loc, scale) is identically equivalent to gamma.pdf(y, a) / scale with y = (x - loc) / scale. Note that shifting the location of a distribution does not make it a "noncentral" distribution; noncentral generalizations of some distributions are available in separate classes.

In the case of Erlang distribution, a should be an integer and the scale should be 1/lambda.


text:
Q: What is the correct way to update a record using hibernate, changes are not reflected in db? I have the following mapping:
<hibernate-mapping>
<class name="com.jurnil.db.hibernate.Order" table="order_table">
    <id name="id" type="long" column="id">
        <generator class="identity"/>
    </id>
    <property name="shippingTotal">
        <column name="shipping_total" not-null="false"/>
    </property>
    <one-to-one name="shippingInfo" class="com.jurnil.db.hibernate.OrderShipping" cascade="all">
  </one-to-one> </class>
</hibernate-mapping>

I am trying to retrieve existing "order" from DB modify some of the values in order and update them back to DB.
Following is the DAO method I have:
public boolean updateOrder(Order o) {
    Session s = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = getTransaction(s);
    o.setUpdated(new Date());
    s.saveOrUpdate(o);
    tryCommit(tx);
    return true;

And I call the orderDAO.updateOrder(order);
The changes are not reflected in database, and in the hibernate logs i can see Duplicate entry '332' for key 'PRIMARY'
When i try to rewrite the session in updateOrder function as
Session s = HibernateUtil.getSessionFactory().openSession();

s.saveOrUpdate(o); give me the following error, Duplicate entry '332' for key 'PRIMARY'
After trying the suggestion @Guillaume
changed DAO Method:
public boolean updateOrder(BigDecimal cartTotal, OrderShipping shippingInformation, BigDecimal taxes,
            BigDecimal orderTotal, BigDecimal shippingTotal, Long id) {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = getTransaction(s);
        Order order = (Order) s.load(Order.class, id);
        order.setCartTotal(cartTotal);
        order.setShippingInfo(shippingInformation);
        order.setTaxPaid(taxes);
        order.setTotalPaid(orderTotal);
        order.setShippingTotal(shippingTotal);
        order.getShippingInfo().setOrder(order);
        order.setUpdated(new Date());
        tryCommit(tx);
        return true;
    }

The data is not updated still in DB, In the SQL Logs i can see the transaction is rolling back, why that happens ?
Below is the SQL logs
[2020-09-17 17:45:44,125] DEBUG org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader - Done entity load : com.jurnil.db.hibernate.Order#335
[2020-09-17 17:45:44,126] DEBUG org.hibernate.engine.transaction.spi.AbstractTransactionImpl - committing
[2020-09-17 17:45:44,126] DEBUG org.hibernate.event.internal.AbstractFlushingEventListener - Processing flush-time cascades
[2020-09-17 17:45:44,135] DEBUG org.hibernate.event.internal.AbstractSaveEventListener - Generated identifier: 335, using strategy: org.hibernate.id.ForeignGenerator
org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [com.jurnil.db.hibernate.OrderShipping#335]
[2020-09-17 17:45:44,136] DEBUG org.hibernate.engine.transaction.spi.AbstractTransactionImpl - rolling back

A: Your Order object needs to be associated with the same session as the session you're using for the transaction. For instance if you want to update the order with id #322:
Session s = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = getTransaction(s);
Order o = s.load(Order.class, 322);
o.setUpdated(new Date());
tryCommit(tx);

Note that the saveOrUpdate was removed: when the transaction is committed, Hibernate will see that the Order was modified and update the database.


text:
Q: Type error - Object is possibly 'null' for event object In my angular app i am using this function below.
@HostListener('drop', ['$event'])
    onDrop(event: DragEvent): void {
        const textData = event.dataTransfer.getData('text');
        this.inputElement.focus();
        this.pasteData(textData);
        event.preventDefault();
}

Tslint is complaining here event.dataTransfer. I am getting this error - Returns the DataTransfer object for the event. Object is possibly 'null'.

A: This is common if you turned on error catching by TSLint.
you can use any of the below.
if(event.dataTransfer != undefined){
    const textData = event.dataTransfer.getData('text');
}

Or simply (note the ?)
const textData = event.dataTransfer?.getData('text');


text:
Q: Set tapping instead of clicking for Arch Mouse I am looking for a way to TAP the arch mouse and NOT click the mouse button for the same clicking action. I am using a MacBook Pro 2017.
I go to System Preferences -> Microsoft Mouse and there is no option to replace clicking for tapping.  My index finger is taking a toll every time I click the left mouse button.


text:
Q: Active Record - Rails 6, Having a model that two unrelated models use Lets say Im building a watch classifier system in rails 6. I have a model called material, material is use by both the watch body and bracelet.
the model would be something like this:
Material:
    description - text (gold, platinum, steel, silver etc)

Bracelet:
    style - text
    Material - has_many references (could be silver and rose gold etc)
    clasp - text
    etc

Watch
    brand - text
    Material - has_many references (case could be gold & white Gold etc)
    etc

As you can see both Bracelet and Watch are dependent on material in one to many, but material doesn't care or need to know about Watch or Bracelet so belongs_to: doesn't suit, nor does a polymorphic association
How do I model this in rails 6? and what would the migrations look like?
Thanks

A: Something like this:
class CreateMaterials < ActiveRecord::Migration[6.0]
  def change
    create_table :materials do |t|
      t.integer :description, default: 0

      t.timestamps
    end
  end
end

class Material < ApplicationRecord
  enum description: %i[gold, platinum, steel, silver] # etc

  has_and_belongs_to_many :watches
  has_and_belongs_to_many :bracelets
end

class CreateBracelets < ActiveRecord::Migration[6.0]
  def change
    create_table :bracelets do |t|
      t.text :style
      t.text :clasp
      # etc

      t.timestamps
    end
  end
end

class Bracelet < ApplicationRecord
  has_and_belongs_to_many :materials
end

class CreateWatches < ActiveRecord::Migration[6.0]
  def change
    create_table :watches do |t|
      t.text :brand
      # etc

      t.timestamps
    end
  end
end

class Watch < ApplicationRecord
  has_and_belongs_to_many :materials
end

class CreateMaterialsBracelets < ActiveRecord::Migration[6.0]
  def change
    create_table :materials_bracelets, id: false do |t|
      t.belongs_to :material, foreign_key: true
      t.belongs_to :bracelet, foreign_key: true
    end
  end
end

class CreateMaterialsWatches < ActiveRecord::Migration[6.0]
  def change
    create_table :materials_watches, id: false do |t|
      t.belongs_to :material, foreign_key: true
      t.belongs_to :watch, foreign_key: true
    end
  end
end

How do you like this decision? If something is wrong, then say it.


text:
Q: How to Refer to Specified Item in List Where Name is Reserved I have a list (aList) of which item 1 is
{{issued:{|date-parts|:{{2000, 11}}}, |number|:"CMU/SEI-2000-TR-030", |id|:"noauthor_cmmi_2000", title:"CMMI SM for Systems Engineering/ Software Engineering/ Integrated Product and Process Development, Version 1.01 (CMMI-SE/SW/IPPD, V1.01). Staged Representation.", |citation-key|:"noauthor_cmmi_2000", language:"en", publisher:"Carnegie Mellon Software Engineering Institute", |type|:"report"}}

from which I want to retrieve the 'number' item. Other list items may not have a number item or a different number of items and hence I want to try and retrieve the value ("CMU/SEI-2000-TR-030") using the item's key - 'number' rather than the order position
i.e.
try
    set documentID to ". " & number of item 1 of aList
end try

which fails because number is a reserved term.
Is there a way to get around this to retrieve this?

A: The pipe character (|) that many of your variables are surrounded with, force the enclosed characters to be treated as a variable. As an item within 'aList', you use |number|, so continue to surround 'number' with pipes when you use it later.
set documentID to ". " & |number| of item 1 of alist

FWIW, this is discussed under Identifiers in the Language Guide (as vertical bar character in identifiers) and the practice is not recommended.


text:
Q: Find the $k$ of the formula $k\pi ^m=\sum_{n=0}^{\infty }\frac{1}{(2n+1+\frac{a}{3})^m}+\frac{1}{(2n+1-\frac{a}{3})^m}$ $$k\pi ^m=\sum_{n=0}^{\infty }\frac{1}{(2n+1+\frac{a}{3})^m}+\frac{1}{(2n+1-\frac{a}{3})^m}$$ when $a$ an even integer number if $$a\geq 4 $$ $$gcd(a,3)=1$$
I want to find $k$ with $m$
if $m$ is an even integer number
Hint: for $m=2$ the $k=1$

A: Hint: Prove that, for $m=2$, $S(a)=\bigg[\dfrac\pi2\sec\bigg(a\dfrac\pi6\bigg)\bigg]^2$, then differentiate both sides with regard to a an even number of times.

A: Since
$$\frac{\pi^2}{\sin^2(\pi z)}=\sum_{n\in\mathbb{Z}}\frac{1}{(z-n)^2}$$
it follows that:
$$\frac{\pi^2}{\cos^2(\pi z)}=\sum_{n\in\mathbb{Z}}\frac{1}{\left(\frac{1}{2}-z-n\right)^2}=\sum_{n=0}^{+\infty}\left(\frac{1}{\left(\frac{1}{2}-z-n\right)^2}+\frac{1}{\left(\frac{3}{2}-z+n\right)^2}\right)\tag{1}$$
so we can find the value of $k\in\mathbb{Q}$ by differentiating the previous identity.


text:
Q: Xamarin.Forms - How to use one instance of class when using Appshell routing? I am new to Xamarin.Forms and have been following a guide where I use a plugin for video calling.
In the example they are not using AppShell but other type of navigation.
In the iOS project appdelegate.cs they do this:
    try {
            LoadApplication(new App(VidyoController.GetInstance()));
        } catch (Exception e) {
            Logger.GetInstance().Log(e.Message);
        }

Then in the app.xaml.cs they do this in order to get the videocontroller instance to the appropriate view:
        public App(IVidyoController vidyoController)
    {
        InitializeComponent();
        this.mVidyoController = vidyoController;

        HomePage homePage = new HomePage(vidyoController);
        MainPage = new NavigationPage(homePage);
    }

I am now wondering how do I get the instance from the appdelegate to my view using AppShell routing?
I started writing something like this:
        public App(IVidyoController vidyoController)
    {
        InitializeComponent();
        this.mVidyoController = vidyoController;

        MainPage = new AppShell();
    }

But I really have no clue what to do next. The videoController is not going to be used on the first page in the application.

A: First, you can not use the appshell to pass the videocontroller instance to the other page. But you can define the videocontroller in the other page.
Second, if you want the videocontroller automatically start you can use the OnAppearing() method and write the code.


text:
Q: Unity Instantiate with transform position? I know this is second time i ask this kind of question but i have no solution for this. Ok this is my code:
public GameObject ball;
public GameObject Mycamera;
GameObject mainplayer;
private void Update()
{
mainplayer= Instantiate(ball, playerspawpoint.position, playerspawpoint.rotation);

    float horizon = Input.GetAxis("Horizontal");

    Mycamera.transform.RotateAround(mainplayer.transform.position,new Vector3(0,mainplayer.transform.position.y,0) ,10 * Time.deltaTime*horizon);
}

Ok, my main purpose is making camera move around the ball that has instantiated. But when i hit <- or -> it just move around somewhere very far away and i have tried alot of different ways, no succeed. Please help me

A: Can you call the Instantiate() in the Start() method.
suggestion:
  mainplayer= Instantiate(ball, playerspawpoint.position, playerspawpoint.rotation) as Gameobject;


text:
Q: How do I use a procedure to run a select that exports to an excel spreadsheet? How do I use a procedure to run a select that exports to an excel spreadsheet?
Using PL/SQL - Oracle 11g
We currently have people copy pasting information into spread sheets that they use for testing every release. I am trying to convert all of their statements into one procedure that will run it for them instead of wasting days worth of time pasting.

A: With the following simple query you could have your whole set of tables converted in XML, one clob row for each table:
SELECT DBMS_XMLQUERY.getxml('select * from ' || table_name)
FROM user_tables;

The package DBMS_XMLQUERY has many option to control the format, but you could just write down XML on files (with a custom client, or directly by PLS UTL_FILE), spreadsheets area able to import them.


text:
Q: Introductory (online) texts on Bayesian Network. I would like to ask for some recommendation of introductory online texts on Bayesian Network.
What I am searching for is some accessible and instructive text not necessarily covering the subject in great depth, but explaining the main ideas. Simply an accessible introductory text (possibly online) for a fast orientation in the subject.

A: Here is a small list of references:

*

*Kevin Murphy's A Brief Introduction to Graphical Models and Bayesian Networks

*Kevin Murphy's Phd Thesis

*Michael Jordan's Graphical Models

*Collection of papers appearing in Michael Jordan's Learning in Graphical Models


text:
Q: why does header and content fall short of body width I am having a weird situation with the code below, my body width is set to 980px and my header and content width is set to 100% so they should stretch throughout screen but in firefox they fall short by few pixels and in chrome they just reach the half way, the weird thing is body of page is covering whole screen I checked it by setting background:black for body and whole page turned black then how header and content can fall short with width:100% .But this code works fine on cssdesk cssdesk so what is wrong with my browsers. My screen resolution is 1366x768.

body {
    width: 980px;
    margin: 0;
    background-color: #000;
}
.header {
    color: #fff;
    margin: 0;
    width: 100%;
    height: 60px;
    background-color: #F23F21;
}
#container {
    width: 100%;
}
.one {
    height: 200px;
    float: left;
    border: 1px solid red;
    width: 25%;
    box-sizing: border-box;
}
.two {
    height: 200px;
    display: inline-block;
    border: 1px solid blue;
    box-sizing: border-box;
    width: 50%;
}
.three {
    height: 200px;
    float: right;
    border: 1px solid green;
    box-sizing: border-box;
    width: 25%;
}

This is header

A: The body is not stretching to fill the screen. There are just special rules for how the background colour is handled on the body element (it is used to colour the viewport itself).
The body is the width you gave it. That width is narrower than your browser window.
Everything else is constrained within it.

A: Dont fix width of your body, inside body create a container div
i have modified your code check this

This is header


text:
Q: Knockout native templates equivalent to the jQuery .tmpl(data) function I am currently migrating my knockout.js app from using the jQuery tmpl library to use the native knockout templating library. One of the lines of code I have to migrated is:
$("#someTemplate").tmpl(data.SomeDataFromServer).appendTo(someHtmlElement);

The tmpl() function is obviously part of the jQuery tmpl library (see http://api.jquery.com/tmpl/)
Given I have now changed my template to:

... what would the new call to the template look like?

A: You would use the template binding like:

or

or

This works with native templates as well as jQuery Templates.  If you are only using jQuery templates, then make sure that you are not referencing the jQuery Templates plugin.
If your data is an observable, then initially it can be null and nothing will get rendered.  Then, when you populate it from an AJAX call then it will be updated with your data.
Another option is to use ko.applyBindingsToNode, which would look like:
var data = [ { name: "one" }, { name: "two" } ];

ko.applyBindingsToNode(document.getElementById("test"), { template: { name: 'someTemplate', foreach: data } });


text:
Q: pytorch tensor indices is confusing When I use Pytorch tensor indices, a strange result has occurred:
import numpy as np
import torch
a = torch.tensor([1,2,3,4,5,6,7,8,9,10,11,12], dtype=torch.long)
b = np.zeros(shape=((32,500)))
print(a[b])

The program is normal and the output is a 35*500 tensor, but when I change  the slices:
c = np.zeros(shape=((31,500)))
print(a[c])

The program reported an error:
IndexError: too many indices for tensor of dimension 1

I don't know why. Please tell me why.
Thanks!


text:
Q: Logging method for thrown exception I have methods that are defined as...
public static void myMethod throws IOException ....
how can I use the Logger class to log the exception that is thrown to a file say named "test.log". I've heard of using logger.throwing... but it doesn't seem to work. Could anyone give me a step by step tip on how to do this? I just basically need to log the exception that is thrown (I didn't use try catches). Thank you so much!

A: You'll need to add a catch clause.  Below is a start for using the java.util.logging.Logger.  Note that many projects use an Apache logger which is a bit more powerful and more complicated.  Let's say you have a class com.myCompany.Foo that reads some file stuff
typically, at the start of the class in the static field declarations you will have
private static final Logger LOGGER = Logger.getLogger("com.myCompany.Foo");

then, when you have a method that throws exceptions (this is a stupid method!)
int readFirstCharOfFile(File f) throws IOException {
   FileReader reader = null;
   try {
      reader = new FileReader(f);
      return reader.read();
   }
   catch (IOException ioe) {
      // You have a lot of possibilities here, but this seems most reasonable
      LOGGER.log(Level.SEVERE, ioe.getMessage(), ioe);

      // whether you rethrow the Exception "depends" on the contract, but, in our case
      // the method declaration says that we do, so we do.
      throw ioe;
   }
   finally {
      if (reader != null)
         reader.close();
   }
}

The harder part is configuring the Logger to write where you want.  IIRC, by default it goes to standard error.  There is a lot of "magic" there that I never fully understood so I couldn't explain all the intricacies.
You can Google to get info, here are a couple useful links I found.  link1 and link2

A: If you want a more automatic approach than the one given by user949300, you could take a look at Aspect-Oriented Programming (AOP), which allows you to do exception logging for all methods with just a little bit of code. Just google for aspectj log exceptions or java aop log exceptions.
See also question Audit Java: system to detect exceptions thrown / caught (aop?)

A: Try to use jcabi-aspects and its @LogException annotation:
public class Resource {
  @LogExceptions
  public String load(URL url) {
    return url.openConnection().getContent();
  }
}


text:
Q: Sending a JQuery var into php var I installed OpenCart CMS and wanted to modify some option in the admin panel mainly the look and feel of the template. I also added the jpicker script for color picking. Also i  created the css file with the standard php code and it works fine
<?php header("Content-type: text/css; charset: UTF-8"); ?>

<?php
        $headerColor;
        $menuColor = '#121212';
        $bodyColor = '#fffaaa';

?>

    #header {
        background-color: <?=$headerColor; ?>;
    }

In order to create the color picker view you need to add the id of the div in a script
$(document).ready(function(){
  $('#Expandable').jPicker(
    {
      window:
      {
        expandable: true
      }
    });
 });

And here is the standard code for the html

I am not very good at JQuery but i know that it can be done either with .ajax or post. What i want to do is send the hex value from the jpicker to a php variable in the css file so it can change the color. Here is the link to jpicker http://www.digitalmagicpro.com/jPicker/. I also found an example
  var colorValue = '#ababab';
  $.post("view/stylesheet/stylesheet-template.css", {var_value: colorValue}, function(data) {
    alert(colorValue);
});

It only sends alert and the colorValue from the variable, but i still don't know how to send the colorValue to php from the jpicker.
Thanks

A: function sendToPhp(jCell){
$.ajax({
    url: "php/ajax.php",
    data: {cell: jCell, queryNr: "0"},
    type: "POST",
    async: false,
    success: function(data){ callback(data); }
    });
}

now cell and queryNr is sent to php
if u do a switch case function depending on query nr you can access multiple functions in php this way

for the comment:
function sendToPhp(jCell, phpUrl){
$.ajax({
    url: phpUrl,
    data: {cell: jCell, queryNr: "0"},
    type: "POST",
    async: false,
    success: function(data){ callback(data); }
    });
}

now you can hand over a specific path by calling the function like:
sendToPhp("VAR YOU WANT TO SEND TO PHP", "php/ajax.php"); // or any other path