text:
Q: Numeric UpDown control using dependency properties So I'm at a loss to understand this.  I have a custom control that uses up/down buttons to increase/decrease the time as displayed on toggle buttons.  I have the Content property of the Toggles displaying the correct values of the Hour and Minute properties, and I'm now trying to set up the code-behind to increase the values.  According to the VS2010 debugger, it is increasing the value of the Hour property, but it's not changing the content of the Toggles to reflect this.  I have the binding mode set to TwoWay, and I'm using {Binding RelativeSource={RelativeSource TemplatedParent}, Path=Hour, Mode=TwoWay} to bind to the value as this is within the generic.xaml file of the custom control.  Any ideas on how to make the displayed value update correctly?
XAML:  (Style templates removed to save space)
    <Style TargetType="{x:Type local:TimePicker}">
    <Setter Property="Height" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Height}" />
    <Setter Property="Width" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Width}" />
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="FontSize" Value="14" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="Transparent"
                        BorderThickness="1">
                    <StackPanel  x:Name="PART_Root"
                                 Orientation="Horizontal"
                                 HorizontalAlignment="Center"
                                 VerticalAlignment="{TemplateBinding VerticalAlignment}">
                        <!--Region Hour Button-->
                        <ToggleButton x:Name="PART_Hour"
                                      VerticalAlignment="{TemplateBinding VerticalAlignment}"
                                      Margin="0"
                                      BorderBrush="Transparent"
                                      BorderThickness="0"
                                      Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Hour, Mode=TwoWay, BindsDirectlyToSource=True}">
                        </ToggleButton>
                        <!--EndRegion-->
                        <Label HorizontalContentAlignment="{TemplateBinding HorizontalAlignment}"
                               VerticalContentAlignment="{TemplateBinding VerticalAlignment}"
                               FontSize="14"
                               Content=":"/>
                        <!--Region Minute Button-->
                        <ToggleButton x:Name="PART_Minute"
                                      VerticalAlignment="{TemplateBinding VerticalAlignment}"
                                      Margin="0"
                                      BorderBrush="Transparent"
                                      Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Minute}">
                        </ToggleButton>
                        <!--EndRegion-->
                        <StackPanel x:Name="PART_IncDecPanel"
                                    HorizontalAlignment="Center"
                                    VerticalAlignment="Center"
                                    Orientation="Vertical">
                            <Grid Height="{Binding ElementName=PART_Hour, Path=ActualHeight}">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*"/>
                                    <RowDefinition Height="*"/>
                                </Grid.RowDefinitions>
                                <Viewbox Stretch="Fill" Grid.Row="0">
                                    <!--Region Increase Button-->
                                    <Button x:Name="PART_IncreaseTime"
                                            HorizontalContentAlignment="{TemplateBinding HorizontalAlignment}"
                                            VerticalContentAlignment="{TemplateBinding VerticalAlignment}"
                                            BorderBrush="Transparent"
                                            BorderThickness="0"
                                            FontFamily="Marlett"
                                            Foreground="DimGray"
                                            Content="5"
                                            Padding="0"
                                            Click="PART_IncreaseTime_Click">
                                    </Button>
                                    <!--EndRegion-->
                                </Viewbox >
                                <Viewbox Stretch="Fill" Grid.Row="1">
                                    <!--Region Decrease Button-->
                                    <Button x:Name="PART_DecreaseTime"
                                            HorizontalContentAlignment="{TemplateBinding HorizontalAlignment}"
                                            VerticalContentAlignment="{TemplateBinding VerticalAlignment}"
                                            BorderBrush="Transparent"
                                            BorderThickness="0"
                                            FontFamily="Marlett"
                                            Foreground="DimGray"
                                            Content="6"
                                            Padding="0">
                                    </Button>
                                    <!--EndRegion-->
                                </Viewbox>
                            </Grid>

                        </StackPanel>

                    </StackPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Code:
public class TimePicker : Control
{
    #region Dependency Property Declarations
    public static DependencyProperty HourProperty = DependencyProperty.Register("Hour", typeof(int), typeof(TimePicker),
        new FrameworkPropertyMetadata((int)12, new PropertyChangedCallback(OnHourChanged)));

    public static DependencyProperty MinuteProperty = DependencyProperty.Register("Minute", typeof(string), typeof(TimePicker),
        new FrameworkPropertyMetadata((string)"00", new PropertyChangedCallback(OnMinuteChanged)));

    #endregion

    #region Properties
    public int Hour
    {
        get { return (int)GetValue(HourProperty); }
        set { SetValue(HourProperty, value); }
    }

    public string Minute
    {
        get { return (string)GetValue(MinuteProperty); }
        set { SetValue(MinuteProperty, value); }
    }
    #endregion

    #region Events
    private static void OnHourChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        TimePicker time = new TimePicker();
        time.Hour = (int)e.NewValue;
        MessageBox.Show("Hour changed");
    }

    private static void OnMinuteChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {

    }
    #endregion

    static TimePicker()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(TimePicker), new FrameworkPropertyMetadata(typeof(TimePicker)));
    }
}

public partial class TimePickerEvents : ResourceDictionary
{
    TimePicker time = new TimePicker();

    void PART_IncreaseTime_Click(object sender, RoutedEventArgs e)
    {
        time.Hour += 1;

    }
}

A: Not sure why you are using a Togglebutton to display the hour/minutes, I would think a Label/TextBlock would be better suited for that.
Change the binding of your ToggleButtons to
Content="{TemplateBinding Hour}"

Then in the code, override OnApplyTemplate as such
public override void OnApplyTemplate()
{
    var upButton = GetTemplateChild("PART_IncreaseTime") as Button;
    upButton.Click += IncreaseClick;

    var downButton = GetTemplateChild("PART_DecreaseTime") as Button;
    downButton.Click += DecreaseClick;
}

private void IncreaseClick(object sender, RoutedEventArgs e)
{
    // Here would be a place to see what toggle button is checked
    // (or which TextBlock last had focus) and increase Hour/Minute
    // based on that info
    Hour += 1;
}

private void DecreaseClick(object sender, RoutedEventArgs e)
{
    // Here would be a place to see what toggle button is checked
    // (or which TextBlock last had focus) and decreaseHour/Minute
    // based on that info
    Hour -= 1;
}

This should get you started.
FYI: Within your OnHourChanged and OnMinuteChanged the sender is your control (TimePicker). So you can cast the sender to TimePicker and access all of your properties. Even your private properties.

A: Why don't you use the WPF toolkit's numerical up down control?
http://wpftoolkit.codeplex.com/wikipage?title=NumericUpDown
All you have to do is bind it to your properties two way.


text:
Q: I want to connect to my ubuntu terminal using putty. I have installed putty already. How can I do it? I want to see the terminal using putty in my ubuntu machine. I have installed ubuntu and tried with 127.0.0.1 and the IP assigned by DHCP to my machine. But unable to connect. How can I do it?

A: 127.0,.0.1 is the loopback address, meaning the machine "talks to itself" You need to enter the address of the ubuntu machine you want to connect to. You can find out on your router, or from a terminal prompt (on the ubuntu machine) with ifconfig and look for an ip address near one of the interfaces (wlan0,eth0 etc..) (not interface lo)

A: Are you sure you have installed openssh server during ubuntu installation? If not you can install it like this from the terminal:
 sudo apt-get update && sudo apt-get install openssh-server
And have a look at the ssh configuration guide: https://help.ubuntu.com/community/SSH/OpenSSH/Configuring

A: What system you have?
If Ubuntu, use terminal (CTRL+ALT+T) put in windows 'ssh user@111.222.333.444'
user - username in remote system
111.222.333.444 - ip addres remote host.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vertical fixed nav flex content on hover I am trying to create a nav essentially like the one found on the google venture website (http://www.gv.com/portfolio/).
I want the nav to be a vertical and fixed on the left of the page and pop out on hover. However because my nav is fixed, I don't know how to make the main content flex with the popout on hover.
Is there a way to do this without the use of javascript?


text:
Q: On the compactification of partial semigroups We begin by introducing some relevant definitions.
Definition: A $\textit{partial semigroup}$ is a pair $(S,.)$ where $.$ maps a subset of $S \times S$ to $S$ and for all $a,b,c \in S, (a.b).c=a.(b.c)$ in the sense that if either side is defined, then so is the other and they are equal.
Definition : Let $(S, .)$ be a partial semigroup.
(a) For $x \in S, \phi(x)= \phi_S(x) = \{y \in S : x.y \; \mbox {is defined}  \}.$
(b) The semigroup $S$ is $\textit{adequate}$ if and only if for every $F \in \mathcal{P}_f(S),$ the collection of finite subsets of $S,$ $\bigcap\limits_{x \in F} \phi(x) \neq \emptyset.$
(c) $\delta S = \bigcap\limits_{x \in S} cl_{\beta S} (\phi(x)),$ where $cl_{\beta S}(A)$ is the closure of $A$ with respect to the topology of $\beta S$, the Stone Cech compactification of $S.$
Definition: Let $T$ be a partial semigroup. Then $S$ is an $\textit{adequate partial subsemigroup}$ of $T$ if and only if $S \subseteq T, S$ is an adequate partial semigroup under the inherited operation, and for all $F \in \mathcal{P}_f(T)$ there exists $H \in \mathcal{P}_f(S)$ such that $\bigcap\limits_{x \in H} \phi_S(x) \subseteq \bigcap\limits_{x \in F} \phi_T(x).$
Definition: Let $S$ be a partial semigroup.
(a) A subset $I$ of $S$ is a left ideal of $S$ if and only if $x.y \in I$ whenever $x \in S$ and $y \in I \cap \phi(x).$
(b) A subset $I$ of $S$ is a right ideal of $S$ if and only if $x.y \in I$ whenever $x \in I$ and $y \in \phi(x).$
(c) A subset $I$ of $S$ is an ideal of $S$ if and only if $I$ is both a left ideal and a right ideal of $S.$
We begin by introducing some relevant definitions.
Let $E^{\diamond} $ be an adequate partial subsemigroup of $S^l,$ the product of $l$ copies of $S,$ with $\{(\overbrace{a,a,\cdots , a}^{l}) : a \in S\}\subseteq E^{\diamond}$ and $I^{\diamond}$ be the two sided adequate partial ideal of $E^{\diamond}.$
Define $I = \bigcap\limits_{\bar{x} \in I^{\diamond}} cl_{\beta S^l} \phi(\bar{x}).$
My questions are the following: 1) Is $I^{\diamond} \subseteq I.$ In particular, can we identify the elements of $I^{\diamond}$ by some ultrafilters from $I?$
2) How does $S,$ a partial semigroup, sit inside $\delta S?$


text:
Q: App crashes on start when remote debugging is disabled I am trying to install my react-native app on my phone (iPhone). It installs alright but then crashes on start with this error message -
undefined is not an object (evaluating 'navigator.userAgent.indexOf')

<unknown>
     :12:71
loadModuleImplementation
    require.js:213:12
<unknown>
    getScrollPosition.js:12:31

If i then enable remote js debugging, it reloads and everything works fine. I disable remote debugging, the app goes back to crashing. Any idea what might be happening here?
Update - The culprit code is in fbjs package - https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/dom/getDocumentScrollElement.js
They check if navigator is defined or not and then try to access the second level property on it - navigator.userAgent.indexOf.
I can either fake navigator.userAgent somehow or send a PR to fbjs.

A: navigator is a global Web API available in browsers. This is not available in React Native as it's not a web browser. All of the Web APIs are not part of the global environment. This is why navigator.userAgent.indexOf is throwing the undefined error.
Now the reason why your program runs fine when debugging JS remotely is because React Native will switch to using the JavaScript engine provided by Chrome (or whatever you are debugging through) instead of the core one when you remote debug. So when debugging, you will have access to the global Web API that browsers normally have.
This is a very tricky gotcha that will often trip people up as most people develop with debugging turned on all the time. Rule of thumb: React Native is not a browser. Don't use any of the globals that you would normally use when doing web development and you'll avoid most of these types of gotcha errors.
If you would like to see how these globals are polyfilled (often with empty objects) in React Native's JavaScript engine, you'll want to look at initializeCore.js. Here you can see that React Native will polyfill navigator like this:
// Set up Geolocation
let navigator = global.navigator;
if (navigator === undefined) {
  global.navigator = navigator = {};
}

// see https://github.com/facebook/react-native/issues/10881
polyfillObjectProperty(navigator, 'product', () => 'ReactNative');
polyfillObjectProperty(navigator, 'geolocation', () => require('Geolocation'));

Edit: To answer the follow-up and give a workaround.
You can shim it, but you need to do it before importing any of your other files in index.js (the root of your application). This is how it's done in node-libs-react-native with their globals.js file where they too set a default user agent string. Adapting that, you can achieve the same result by doing the following:

*

*Create file to hold your shims, globals.js:
global.navigator.userAgent = 'React Native';

*Import/Require it prior to importing any of your other files in index.js:
import { AppRegistry } from "react-native";
import globals from "./globals";
import App from "./App";

AppRegistry.registerComponent("RNSandbox", () => App);

If for some reason you want the userAgent to be different or be dependent on whether you are debugging or not, you can add your own logic to the globals.js.


text:
Q: dojo.ready call shows error in Worklight 6.0 I have created a dojo based Worklight project and a hybrid application it.
I did a drag and drop of a dojo mobile button which gets added inside a dojo mobile view. All of this works fine and renders fine in the various environments (common, android etc.). It also correctly shows the look and feel in Rich Page Editor.
But then i added a script that has a very simple dojo.ready call. Now when i run this application i get a console error saying ReferenceError: dojo is not defined. Any idea why that is happening?
I know that i have correctly setup the dojo as other pieces seem to work. I have also checked that the dojo.js is loading (which is obvious as the other pieces are working). I am using IBM Worklight 6.0 developer edition with all capabilities installed.
Here is my sample code
<!DOCTYPE HTML>
<html>
        <head>
            <meta charset="UTF-8">
            <title>jmdwl</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
            <meta name="apple-mobile-web-app-capable" content="yes">
            <link rel="shortcut icon" href="images/favicon.png">
            <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
            <link rel="stylesheet" href="css/jmdwl.css">
            <script>window.$ = window.jQuery = WLJQ;</script>
            <script type="text/javascript" src="dojox/mobile/deviceTheme.js"></script>
            <script type="text/javascript" data-dojo-config="isDebug: false, async: true, parseOnLoad: true, mblHideAddressBar: false" src="dojo/dojo.js"></script>
            <script>
            dojo.ready(function() {
                alert("Here");
            });
            </script>
        </head>
        <body id="content" style="display: none;">
            <div data-dojo-type="dojox.mobile.ScrollableView" id="view0" data-dojo-props="selected:true">
                <!--application UI goes here-->

                    <button data-dojo-type="dojox.mobile.Button">Label</button>
            </div>
            <script src="js/initOptions.js"></script>
            <script src="js/jmdwl.js"></script>
            <script src="js/messages.js"></script>
        </body>
</html>

Thanks,
Gaurav

A: If you want to use dojo.ready you must initialize it first.
<script>
  require(["dojo/ready"], function(ready){
        ready(function() {
            alert("Here");
        });
  });

Here's the reference : http://dojotoolkit.org/reference-guide/1.8/dojo/ready.html#dojo-ready
Update 1
Which Version of dojo do you use by now? 1.6 or 1.7+ ?
The new AMD requires to initialize the modules like i write before.
Have you read this threads? There seem to be an failure while importing the dojo Libarys. I guess this could have something to do with your error.
worklight fail to require DOJO Combobx on real device -fail to load ... /dijit/form/nls/it/ComboBox.js
and
Worklight core-web-layer.js errors
Regards, Miriam


text:
Q: sort a queue in C# Even though this question sounds as a duplicate, I searched a lot but couldn't find a proper solution.
I have following classes
public enum ChangeType
{
    Add,
    Modify,
    Delete
}

public enum ChangedObjectType
{
    Project,
    Customer,
    Border,
    Photo
}

public struct ChangeInfo
{
    public ChangeType typeofChange { get; private set; }
    public ChangedObjectType objectType { get; private set; }

    public string objectID { get; private set; }

    public ChangeInfo(ChangeType changeType, ChangedObjectType changeObj, string objectId):this()
    {
        typeofChange = changeType;
        objectType = changeObj;
        objectID = objectId;
    }

}

thread :
public class ChangeInfoUploader
{
    static Queue<ChangeInfo> changeInfoQueue = new Queue<ChangeInfo>();
    static Thread changeInfoUploaderThread = new Thread(new ThreadStart(ChangeInfoUploaderProc));
    static bool isStarted = false;
    static Project currentProject;

    public static void Initialize(Project curproject)
    {
        currentProject = curproject;
        isStarted = true;
        changeInfoUploaderThread.Start();
        ResumeData();
    }

    static void ChangeInfoUploaderProc()
    {
        while (isStarted)
        {
            if (currentProject != null)
            {
                ChangeInfo? addToDb = null;

             // I need to sort changeInfoQueue before dequeue
                lock (changeInfoQueue)
                {
                    if (changeInfoQueue.Count != 0)
                        addToDb = changeInfoQueue.Dequeue();
                }
            }
        }
        Logdata();
        changeInfoUploaderThread.Abort();
    }
}

here is the sample data of changeInfoQueue queue.
<Info TypeofChange="Add" ObjectType="Customer" ObjectId="0005" />
<Info TypeofChange="Add" ObjectType="Customer" ObjectId="0006" />
<Info TypeofChange="Add" ObjectType="Customer" ObjectId="0007" />
<Info TypeofChange="Add" ObjectType="Photo" ObjectId="01a243f5-4894-4d99-8238-9c4cd3" />

My Question :

*

*I need to sort out changeInfoQueue based on ObjectType. How can i do that?

My findings:

*

*I found OrderBy . Is it possible to use it? If so, how?

In addition to that I found priorityQueue. What is the best solution for me?
EDIT:
The values of this queue are added when relevant objects are created. (projects, borders etc.) and saves it in a local XML file. After that it needs to write to a database. This is accomplished by using a thread and when we save this data it must be saved in particular order to avoid foreign key violations. So this thread is used to call those relevant methods.
I used orderby as follows:
Queue<ChangeInfo> changeInfoQueue2 = changeInfoQueue.OrderBy(ChangeInfo => ChangeInfo.ObjectType);

then it throws following exception:
Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Generic.Queue'. An explicit conversion exists (are you missing a cast?)

A: Why would you want to order by the type of object in a queue? A queue, by its definition, it's not meant to be ordered in that way but intended to work as a first in first out kind of element.
Either use a List if you just want a collection capable of being ordered, and ordered list or create several queues for the different kind of objects that you have.
For example, if you go to the super market you have several queues, one for each different section... it wouldn't make any sense to put all people in the same queue and then "order" them based on whether they are in for the butcher or the bakery.
You have a queue when you need to "queue" things... if you don't use the appropriate construct, don't try to force it into a queue. ("if you have a hammer everything looks like a nail"... but it should not)

A: While everything that has been said about using queue and OrderBy is valid, you still might want to order elements in your queue.
You can build a new queue based on a IOrderedEnumerable:
Queue<string> queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
queue.Enqueue("third");
queue.Enqueue("fourth");

// Builds a new queue. Items are now alphabetically ordered
Queue<string> orderedQueue = new Queue<string>(queue.OrderBy(z => z));

A: The simplest way to achive it is:
Queue priorityQueue = new Queue<int>();
priorityQueue = new Queue<int>(priorityQueue.OrderBy(x => x))
I hope this will help you


text:
Q: Indicate when a user has unaccepted a massive number of answers to their questions We've recently gotten a flag on Stack Overflow indicating that a user has gone through and unaccepted every single one of their answers.
While this is perfectly OK and allowed by the system, it could be an indicator of vandalism, and right now, it's not something that's easily detectable.
That said, I'd like to see two things.  First, there should be a way to see that a user unaccepted an answer in their activity.  We can see accepts, but not unaccepts.
Note that we can look at the reputation and see the -2 applied for unaccepting an answer (and we can see a bunch of them in a row), but we have a specific tab in the activity section of our profiles to show our accepts, there's no reason we shouldn't have the same duplication of information for the unaccept case.
If a user unaccepts a number of answers in a short period of time, I'd like to see a flag in the moderator queue indicating that there were a number of unaccepts in a short period of time, just like we have for edits and deletes.
Finally, as per Sha Dow Wiz Ard's suggestion in the comments, there should be a rate limit on how many unaccepts you can do per day, as per the delete rate limit.


text:
Q: Convert Teradata SQL to BigQuery SQL How do I convert following sql to bigquery?
SELECT
MAX(var1)*2 as name1,
name1+11 as name2
FROM table

In bigquery I can't use name1 if I declare it in the line above.
I know i can do this, but when sql is big then a lot needs to be changed, there may be other simpler options.
SELECT
MAX(var1)*2 as name1,
MAX(var1)*2+11 as name2
FROM table

A: You can't reuse the alias in this way on BigQuery, you will have to repeat the full expression or subquery.  Assuming the former option:
SELECT MAX(var1)*2 AS name1,
       MAX(var1)*2 + 11 AS name2
FROM yourTable;

The only other option would be to subquery:
WITH cte AS (
    SELECT MAX(var1)*2 AS name1
    FROM yourTable
)

SELECT name1, name1 + 11 AS name2
FROM cte;

But from a performance point of view, there is an added cost which the subquery version has over the first version.  You should probably go with repeating the alias expression unless you really would need to repeat a lot of code.


text:
Q: Запуская кода с расширением .pyw программа работает безотказно, а запуская тот же файл с тем же расширением с рабочего стола перестает работать Пишу программу для WhatsApp-рассылки сообщений на python с использованием библиотеки PyQt5. Пишу в текстовом редакторе VSCode. Создал главное окно с менюбаром и парой функций, и, если запускать код из редактора, всё работает безотказно. Решил проверить работу программы, если запустить файл с рабочего стола. Поменял расширение главного файла с .py на .pyw, запустил программку, открылось главное меню, все работало как надо. Но, как только решил проверить работу основных функций, а именно работу рассылки и добавления людей в базу данных (папку с файлами, в которых хранится информация о клиентах), ничего не запустилось, а программа перестала работать. Опять же повторюсь, если запустить тот же самый файл из Visual Studio, такая проблема исчезает сразу и всё работает как часы.
Код файлов:
main.py
from main_window import *
import sys

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

main_window.py
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow

from functions import send_message, create_new_file

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setupUi()

    def setupUi(self):
        '''settings of window'''

        #settings of main window
        self.setWindowTitle("Расслыка")
        self.move(300, 300)
        self.resize(600, 500)

        #settings of menubar
        menuBar = self.menuBar()

        self.distAllMenu = menuBar.addMenu("&Рассылка")
        self.distAllMenu.addAction("Разослать всем", self.action_clicked)
        self.distAllMenu.addAction("Разослать выборочно", self.action_clicked)

        self.dataBaseMenu = menuBar.addMenu("&База данных")
        self.dataBaseMenu.addAction("Добавить клинта", self.action_clicked)
        self.dataBaseMenu.addAction("Удалить клиента", self.action_clicked)
        self.dataBaseMenu.addAction("Очистить всё", self.action_clicked)

        self.setupui_widgets_add_client()

    def setupui_widgets_add_client(self):
        '''This method incloods all elements to form "Add client".
           Function "hide_widgets" hides these elements from main_window'''

        #text field to input name
        self.txt_name = QtWidgets.QLineEdit(self)
        self.txt_name.resize(200, 50)
        self.txt_name.move(10, 50)
        self.txt_name.setText("Имя")
        self.txt_name.setStyleSheet('font-size:12pt; font-family: caption;')

        #text field to input second name
        self.txt_second_name = QtWidgets.QLineEdit(self)
        self.txt_second_name.resize(200, 50)
        self.txt_second_name.move(10, 110)
        self.txt_second_name.setText("Фамилия")
        self.txt_second_name.setStyleSheet('font-size:12pt; font-family: caption;')

        #text field to input father name
        self.txt_father_name = QtWidgets.QLineEdit(self)
        self.txt_father_name.resize(200, 50)
        self.txt_father_name.move(10, 170)
        self.txt_father_name.setText("Отчество")
        self.txt_father_name.setStyleSheet('font-size:12pt; font-family: caption;')

        #text field to input phone number
        self.txt_phone_number = QtWidgets.QLineEdit(self)
        self.txt_phone_number.resize(200, 50)
        self.txt_phone_number.move(390, 50)
        self.txt_phone_number.setText("+7")
        self.txt_phone_number.setStyleSheet('font-size:12pt; font-family: caption;')

        #combobox to choice seats type
        self.cm_seat = QtWidgets.QComboBox(self)
        self.cm_seat.resize(200, 50)
        self.cm_seat.move(390, 110)
        self.cm_seat.addItem("Диван")
        self.cm_seat.addItem("Кресло")
        self.cm_seat.addItem("Стул")
        self.cm_seat.setStyleSheet('font-size:12pt; font-family: caption;')

        #text field to input number of seat
        self.txt_seats_number = QtWidgets.QLineEdit(self)
        self.txt_seats_number.resize(200, 50)
        self.txt_seats_number.move(390, 170)
        self.txt_seats_number.setText("Номер места")
        self.txt_seats_number.setStyleSheet('font-size:12pt; font-family: caption;')

        #label, that informs about created file in DataBase
        self.lbl_clien_added = QtWidgets.QLabel(self)
        self.lbl_clien_added.setText("")
        self.lbl_clien_added.resize(300, 50)
        self.lbl_clien_added.move(170, 300)
        self.lbl_clien_added.setStyleSheet('font-size:10pt; font-family: caption;')

        #button to add client in DataBase
        self.btn_add_client = QtWidgets.QPushButton(self)
        self.btn_add_client.setText("Добавить клиента")
        self.btn_add_client.resize(200, 50)
        self.btn_add_client.move(10, 440)
        self.btn_add_client.clicked.connect(self.get_datas)

        #button to close all "add client" widgets
        self.btn_exit = QtWidgets.QPushButton(self)
        self.btn_exit.setText("Закрыть")
        self.btn_exit.resize(200, 50)
        self.btn_exit.move(390, 440)
        self.btn_exit.clicked.connect(self.hide_widgets)

        self.hide_widgets()

    def hide_widgets(self):
        '''This method incloods all elements from all menu actions
                          and hides them.'''

        self.txt_name.hide()
        self.txt_second_name.hide()
        self.txt_father_name.hide()
        self.txt_phone_number.hide()
        self.cm_seat.hide()
        self.txt_seats_number.hide()
        self.lbl_clien_added.hide()
        self.btn_add_client.hide()
        self.btn_exit.hide()

    def show_widgets_add_client(self):
        """This method incloods all elements from action "add client"
                          and shows them."""

        self.txt_name.show()
        self.txt_second_name.show()
        self.txt_father_name.show()
        self.txt_phone_number.show()
        self.cm_seat.show()
        self.txt_seats_number.show()
        self.lbl_clien_added.show()
        self.btn_add_client.show()
        self.btn_exit.show()

    def get_datas(self):
        '''The method gets datas from "add client form"'''

        name = self.txt_name.text()
        second_name = self.txt_second_name.text()
        father_name = self.txt_father_name.text()
        phone_no = self.txt_phone_number.text()
        type_seat = self.cm_seat.currentText()
        seat_num = self.txt_seats_number.text()

        create_new_file(name, second_name, father_name, phone_no, type_seat, seat_num)
        self.lbl_clien_added.setText(f"Файл \"{name} {father_name}.txt\" создан!")

    @QtCore.pyqtSlot()
    def action_clicked(self):
        '''performs actions from menuBar'''

        action = self.sender()

        if action.text() == "Разослать всем":
            send_message()
        elif action.text() == "Добавить клинта":
            self.show_widgets_add_client()

functions.py
import os
import time
import mouse

import webbrowser as web
from urllib.parse import quote
import pyautogui as pg

def create_new_file(name = str,
                    second_name = str,
                    father_name = str,
                    phone_number = str,
                    type_of_seats = str,
                    seats = str):
    """Function creating new file in DataBase"""

    file_name = second_name + ' ' + name    #name for new file

    #text in new file
    text = 'Имя: ' + name + '\n'
    text += 'Фамилия: ' + second_name + '\n'
    text += 'Отчество: ' + father_name + '\n'
    text += 'Номер телефона: ' + phone_number + '\n'
    text += 'Тип мест: ' + type_of_seats + '\n'
    text += 'Номера мест: ' + seats

    with open('DataBase\\' + file_name + '.txt', 'w', encoding = 'utf-8') as file:
            file.write(text)

def data_request():
    '''The function requests datas and call function
                "create_new_file" '''

    #form for datas
    name = input('\nИмя: ')
    second_name = input('Фамилия: ')
    father_name = input('Отчество: ')
    phone_number = input('Номер телефона: ')
    type_of_seats = input('Тип мест: ')
    seats = input('Номера мест: ')

    create_new_file(name, second_name, father_name, phone_number, type_of_seats, seats)

def close_brouser():
    '''The function closes brouser by mooving cursor'''

    #Coordinets of screen to click 'close'
    mouse_pos_close_x = 1900
    mouse_pos_close_y = 10

    #Coordinates of screen to agree close screen
    mouse_pos_close_yes_x = 765
    mouse_pos_close_yes_y = 175

    mouse.move(mouse_pos_close_x, mouse_pos_close_y, absolute = True, duration = 0.1)
    mouse.click('left')
    mouse.move(mouse_pos_close_yes_x, mouse_pos_close_yes_y, absolute = True, duration= 0.1)
    mouse.click('left')

def open_whatsapp_and_send_message(phone_number = str, message = str):
    '''This function opens whatsapp and sends message automatically'''

    web.open(f"https://web.whatsapp.com/send?phone={phone_number}&text={quote(message)}")
    time.sleep(8)
    pg.press("enter")

def send_message(date = 'завтра'):
    '''Main function for sending massege to client in whatsapp'''

    clients = parser() #[[имя, отчество, телефон], [], []...]

    for client in clients:
        text = 'Добрый вечер, ' + client[0] + ' ' + client[1] + '!\n'
        text += 'Мы рады сообщить, что уже ' + date + ' состоится наш концерт!\n'
        text += 'Будем счастливы видеть вас на нём!'

        open_whatsapp_and_send_message(client[2], text)
        time.sleep(1)
        close_brouser()
        time.sleep(2)

def pathes_to_files():
    '''Create pathes to files in DataBase'''

    #get all files names in DataBase
    all_files = os.listdir('DataBase')
    pathes = []

    #create path to every file and add it to "pathes"-arey
    for i in all_files:
        pathes.append('DataBase\\' + i)

    return pathes

def parser():
    '''Check every file in DataBase and get needed datas'''

    pathes = pathes_to_files()
    words_to_check = ('Имя: ', 'Отчество: ', 'Номер телефона: ')

    datas = [] #[[имя, отчество, телефон], [], []...]

    #open every file in DataBase
    for i in pathes:
        with open(i, 'r', encoding = 'utf-8') as file:

            needed_info = []

            for line in file:
                for word in words_to_check:
                    if word in line:
                        needed_info.append(line.replace(word, '').replace('\n', ''))

            datas.append(needed_info)

    return datas

Везде указаны относительные пути к папке "DataBase".
Буду очень признателен, если поможете, так как я сам пока что совсем только новичок в программировании и не понимаю, в чём проблема.

A: Нужно поменять рабочую директорию перед импортом. Проще всего создать ярлык 'py путь/файл.pyw' и указать её в ярлыке.


text:
Q: Find out Card height to modify I'm trying to make change to this template startbootstr app. For this original code:

Card title

...

            Find Out More!

Card title

...

            Find Out More!

Card title

...

            Find Out More!

I removed divs with class="card-footer" to get rid of "Find our more" buttons. This however, creates a "huge" blank space below "card-text". Using browser's style inspector, I couldn't locate which css class is responsible for the card's height. I do see "h-100" is applied to the Div, but making change to it doesn't change overall height. From where the height of above sample code/Card is controlled?   TIA

A: Here you go:
JSFIDDLE
This is your example without class="card-footer".
I think you have a problem with your CSS


text:
Q: How to specify the visible range of a SDL renderer window I am trying to make a SDL window, the problem is that I only need a specific range of the window to be generally visible, like from 50 to 100 in x direction and 70 to 150 in y. Imagine I want a window with width of 500 and height of 500, but I want to show the mentioned range of x and y (50 to 100 in x direction and 70 to 150 in y.) in this window:

How should I specify that in my code. :
> if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
>         std::cout << "Error initializing SDL: " << SDL_GetError() << std::endl;
>     }
>      SDL_Window* window = SDL_CreateWindow("window",
>       SDL_WINDOWPOS_CENTERED,
>       SDL_WINDOWPOS_CENTERED,
>       SCREEN_W, SCREEN_H, -----> here I specify the width and height
>       SDL_WINDOW_SHOWN);
>
>           SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
>           SDL_RenderPresent(renderer);


text:
Q: In quartz 2.2.1 there is any possibility to find a misfire jobs How can i identify the misfire jobs in quartz.If there is any new feature added in quartz 2.2.1.I have to find Misfire jobs which are all scheduled  and i have to store the misfire jobs into RAMJobstore

A: You can register a TriggerListener that provides the triggerMisfired method that will be invoked whenever a trigger has been misfired. You can easily store the misfire information somewhere in your application and use it for whatever purposes you wish (e.g. to look up misfired jobs and reschedule them etc.).


text:
Q: Ripple Effect on ipad I want to create a ripple effect on a UIImageView from the point where user touches on the screen. what is the best and simple method for doinf this.

A: Please look at this question.
Hope it helps

A: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSSet *allTouches = [event allTouches];
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint lastPoint = [touch locationInView:self.view];
    //animation code
}

Using above method you have set UIimageView center on lastPoint and play your animation code.
It will work that u want.


text:
Q: Python import doesn't import latest function I'm having problems with trying to get python to recognize the latest file.
Take this simple function for example
def printme( str ):
   "This prints a passed string into this function"
   print(str)
   return

I then navigate to the directory and did an
import printme

Ran printme printme.printme("Hello"). It works fine.
I then I updated the function to print Hi. I then remove the module using del printme
def printme( str ):
       "This prints a passed string into this function"
       print('Hi' + str)
       return

Why doesn't python print "Hi" in front of the string?

A: The contents of the module have already been loaded.
Modules aren't loaded again and again every time they are imported. (That would be quite wasteful.)
To load the module again, try
reload(printme)


text:
Q: Escape character from URL encoding URL encoding replaces reserved characters with %...
Is it possible to prevent URL encoding from changing a character? E.g. that & doesn't become a %26 but still is a & after the encoding?

A: You need to render the url as utf-8
This type of encoding doesn't fact anything. It just make problem read the url.


text:
Q: handlebars-js - more complex json api I hit the problem with displaying json data properly using handlebars.js template. My template currently looks like this:

Reaching first array with film titles and poster ids go fine but what I obviously need is to put urls in images src to display film posters.
JS is following:
    var $placeHolder = $("#films");
    var handlebarsTemplate = $("#handlebars-template").html();
    var templateCompile = Handlebars.compile(handlebarsTemplate);
    var data = {
    "films" : [
       {"id" : 17, "posterId" : 7039523, "title" : "Blues Brothers (1980)"},
       {"id" : 702, "posterId" : 6900923, "title" : "Seven (1995)"},
    ],
    "posters": [
        {"id" : 7039523, "url" : "http://1.fwcdn.pl/po/00/17/17/7581123.6.jpg"},
        {"id" : 6900923, "url" : "http://1.fwcdn.pl/po/07/02/702/6967799.6.jpg"},
     ],
   },

   $placeHolder.html(templateCompile(data));
},

So how can I reach two different data arrays in my template to display both film titles and posters based on url? Is it necessary to refer to posterID? Thanks in advance.

A: Massage the data into a form that is easier to handle.
For example (click "Run code snippet" below):

var filmTemplate = Handlebars.compile($("#films-template").html());

var rawData = {
    "films" : [
           {"id" : 17, "posterId" : 7039523, "title" : "Blues Brothers (1980)"},
           {"id" : 702, "posterId" : 6900923, "title" : "Seven (1995)"},
    ],
    "posters": [
            {"id" : 7039523, "url" : "http://1.fwcdn.pl/po/00/17/17/7581123.6.jpg"},
            {"id" : 6900923, "url" : "http://1.fwcdn.pl/po/07/02/702/6967799.6.jpg"},
        ],
    };

var films = rawData.films.map(function (filmInfo) {
    return $.extend({}, filmInfo, {
        poster: rawData.posters.find(function (p) {
            return p.id === filmInfo.posterId;
        })
    });
});

$("#films").html(filmTemplate(films));
$("#data").text(JSON.stringify(films, null, 2));


text:
Q: Does the Horned Rat appear in WarHammer 40k? The Horned Rat is the God of all Skavens in WarHammer Battle, and is a minor Chaos God compared to the 4 main Chaos God.
WarHammer Battle and WarHammer 40k are two separate universes, but they have a very similar mythology, with many gods in common. Though there is no "skavens in space", has the Horned Rat ever been mentioned as a minor Chaos God in 40k (in a Codex, or a novel, or any official material) ?

A: TL;DR:

*

*There are more than just 4 "Gods" in the 40k universe

*There is a reference to a minor God called Malice.

First, there are more than just four Chaos Gods. There are four Major Chaos Gods, but there are a number of Minor Gods that exist in the warp as well. A great many consider Daemons to be Gods, but Daemons are created from the Chaos Gods powers to do their bidding. Really the question comes down to what do you accept as canon, since both Games Workshop and the Warhammer fanbase battle both with each other and themselves as to what is and is not canon.
Now we know the two universes are linked through the warp; but I do not think we know for sure whether Fantasy comes before 40k or not. It might actually follow or be concurrent... The chaos gods are always susceptible to shifts, especially in the "minor arenas" but I have never heard of the Horned Rat in 40k. But the fact that some Gods are prominent in both universes is key that it is possible to be in both.
I found a post that referenced him in 40k as the Horned Prince, but even if that were true the site labeled him as a Daemon prince. To my knowledge no Daemon Prince has ever found a way to become a Chaos God, minor or otherwise... Though it is possible for a Chaos God to use all of its power as a God to create a Daemon and thus transform from a God to a Daemon.
It does seem however that there is mention of a Minor God named Malice, The Lost God. He is named in a short story called Labyrinth by Richard Ford. I mention this because in my research I found references to The Great Horned Rat as Malal or Malice and malice, blight, etc. are part of his repertoire. There is also a confirmed Space Marine Chapter that was excommunicated when they turned to Chaos and began to follow this Minor Chaos God.

A: Nope
As you point out in your question, there are no skaven in space.
A chaos god gets all of it's power from it's worshipers, and there are no skaven to worship it so the Horned Rat just couldn't exist in 40k. And to my knowledge, there has been absolutely no mention of it in any of the army books or fluff.
I've always assumed that the numberless tyranids were the 40k equivalent of skaven, since the burrowing rat men probably wouldn't translate to space very well.
In the fantasy universe at least, it's arguable that the Horned Rat is the most powerful of all the Chaos gods as it undoubtedly has the most followers, they're just to busy backstabbing each other to ever do anything. (Until the End Times anyway).

A: The 1989 compendium mentions that Ratlings sniper rifles have a skaven toxin available. The Skaven were also planned to be included in Warhammer 40k at some point, as mentionned by Jes Goodwin in "The Gothic and the Eldritch", which includes a few sketches of 40k skaven (They were mostly WWI-inspired apparently, with a lot of chemical warfare). This never went anywhere though, and there are no mentions of the Horned Rat anywhere in Warhammer 40k.

A: NO
There are 4 "Gods" in the W40k universe.
Khorne
Slaneesh
Tzeentch
Nurgle
There might me a minor daemon of Nurgle that could posses the same/similar characteristics as the "Horned god". Pestilence is the domain of Nurgle.


text:
Q: Inserting into a JavaScript object inside razor foreach? While I loop through a C# list in a partial view, I need to add to JavaScript object, I tried <text></text> and @: but they just render the plain JavaScript text, here's the full partial-view:
@using Resources;
<script>
    var resources = {};
@{
    Dictionary<string, string> resx = new Dictionary<string, string>();
    foreach (var item in typeof(AppResources).GetProperties().Where(p=>p.PropertyType==typeof(string)))
    {
        resx.Add(item.Name, item.GetValue(item).ToString());
        var key = item.Name;
        var value = item.GetValue(item).ToString();
        @:resources[@key] = @value;
    }
}
    console.log("resources_BEGIN");
    console.log(resources);
    console.log("resources_END");

</script>

this is being rendered in the HTML source:
<script>
    var resources = {};
    resources[lbAccountSettings] = Account settings;
    resources[lbActivate] = Activate;
    resources[lbArabicName] = Arabic Name;
    resources[lbAreas] = Areas;
    console.log("resources_BEGIN");
    console.log(resources);
    console.log("resources_END");
</script>

A: Try this: var jsvariable=@Html.Raw(Json.Encode(<your_charp_variable>))
Edited:
<script>
 var resources = {}
    @{
        Dictionary<string, string> resx = new Dictionary<string, string>();

        foreach (var item in typeof(AppResource).GetProperties().Where(p=>p.PropertyType==typeof(string)))
        {
            resx.Add(item.Key, item.Value);
        }
    }
    resources=@Html.Raw(Json.Encode(resx));
</script>


text:
Q: Can composite unique constraint have columns that are also unique constraints in postgres? I'm trying to figure out if it is a good practice or not to have a column in a table that is Unique as a separate single constraint and at the same time as a part of composite Unique constraint in combination with other columns. For example, let's say we create a table
CREATE TABLE "users" (
            "id" serial NOT NULL,
            "user_id" integer NOT NULL,
            "user_name" varchar(32) NOT NULL UNIQUE,
            "password" varchar(32) NOT NULL,
            CONSTRAINT "users_pkey" PRIMARY KEY (id),
            UNIQUE (user_id, user_name)
        );

As you can see, there is a column user_name that is unique and also it is a part of composite unique constraint. Is that ok? Does it affect on query performance somehow? Should I use such approach or is it better to use another one?


text:
Q: Entities vs. Services in domain driven design (DDD) I wanted to get some feedback on the design of a chat application I recently developed. The application is written in PHP, but the language probably isn't important here.
The main components are User, Conversation, and Message:
class User {
    public function getId(): int {}
    public function getUsername(): string {}
    public function getFirstName(): string {}
    public function getLastName(): string {}

    // token used with a 3rd party API for sending messages
    public function getToken(): ?string;

    // if a user doesn't have a token they can't be messaged
    public function isOnline(): bool {}

    public function __construct(int $id, string $username, ...) {}
}

class Conversation {
    public function getId(): int {}
    public function getUsers(): User[] {}

    public function __construct(int $id, array $users) {}
}

class Message {
    public function getId(): int {}
    public function getText(): string {}
    public function getConversation(): Conversation {}
    public function getAuthor(): User {}

    public function __construct(int $id, string $text, Conversation $conversation) {}
}

I also have some services:
class MessageSender implements MessageSenderInterface
{
    private LoggerInterface $logger;

    public function send(Message $message): void {
        foreach ($message->getConversation()->getUsers() as $user) {
            if (!$user->isOnline()) {
                $this->logger->warn('User is offline and cannot be messaged');
            }

            if ($user->equals($message->getAuthor())) {
                // continue; don't send messages to authors
            }

            $messageData = [
                'to' => $user->getToken(),
                'from' => $message->getAuthor()->getUsername(),
                'text' => $message->getText(),
            ];
            // send the message through some external API
        }
    }
}

Most of the work is done through the MessageSender, but I'm wondering if the domain might be better encapsulated with something like this:
class Message {
    public function getId(): int {}
    public function getText(): string {}

    public function __construct(int $id, string $text, Conversation $conversation) {}

    public function send(MessageSenderInterface $sender, LoggerInterface $logger) {
        ... send logic in here
    }
}

You can see that by moving the send functionality inside of the Message object we totally get rid of two exposed properties (getConversation and getAuthor are gone) and could effectively remove the service altogether. But as a result, the message object now knows about loggers and message senders, even if they are just interfaces.
What does DDD say about this? I tend to prefer exposing less data and like the encapsulation the second option provides.

A: Some DDD practitioners suggest that it is ok to inject technology layers dynamically into your domain model. Modeled that way, your domain code will not be directly dependent on technology components and only talk through abstract interfaces.
But I would suggest that you keep only the domain related code in the domain model layer and organize all technology interactions (DB, Message Brokers, Loggers) in your service layer. These are typically Application Services and Command Handlers in the DDD/CQRS lingo.
Here are some reasons why placing code that interacts with technology components in the domain model is probably a bad practice:

*

*You use DDD to reduce complexity, but injecting technology aspects into your domain model will obscure your vision of real business logic. It will get lost in translation when most of your code handles technology concerns like loading and persisting data or sending messages.

*Your domain model ends up having some knowledge about workflows in your technology components. It knows when to persist data, how to persist data, and when to send messages, among other stuff.

*You will need a different layer anyway to perform validations spanning the aggregate collection (checking for uniqueness of email address, for example).

*Your domain cannot be tested in isolation. You are always organizing technology components (or mocks) when you test domain logic.

Mapping this thought process to your example, the logic to decide whether to send the message would be in the domain layer. The code to format the event data and dispatch to the message broker would be in the service layer.
On a separate note, one wouldn't organize these three components (User, Conversation, and Message) in this way in a DDD application. You would think about transaction boundaries and create aggregates around data objects.
A User would be an aggregate, with its own enclosed objects and behavior. A Conversation would be another aggregate and enclose Message objects within it, and all message related interactions would be via the Conversation aggregate.
Because they are separate aggregates, you would not embed User objects into a Conversation aggregate. You would only have references (user identifiers). You would have a read model that tracks which users are online in a Conversation and use it to dispatch messages.
I suggest you go through the EventSourcery course for a good understanding of these concepts. The code for the course is actually in PHP.

Update 1:
Your Message object is reaching back to the Conversation object to gather users to do its work, so it makes sense to enclose it within the Conversation object.
I will talk about two concepts that may not be part of your architecture right now but would help: Application Services and Domain Events.
You would introduce an intermediate "Application Service" layer between your controller and the Domain Layer.
The App Service will be responsible for invoking the (injected) infrastructure services, calling the domain layer, and persisting/loading necessary data. The Controller's responsibility is only to gather the request params (gather user input in your case), ensure authentication (if needed), and then make the call to the Application Service method.
Application Services are the direct clients of the domain model and act as intermediaries to coordinate between the external world and the domain layer. They are responsible for handling infrastructure concerns like ID Generation, Transaction Management, Encryption, etc. Such responsibilities are not concerns of the Controller layer either.
Let's assume MessageSender is transformed into an Application Service. Here is an example control flow:

*

*API sends the request with conversation_id, user_id (author), and message.

*Application Service loads Conversation from the database. If the Conversation ID is valid, and the author can participate in this conversation (these are invariants), you invoke a send method on the Conversation object.

*The Conversation object adds the message to its own data, runs its business logic, and decides which users to send the message.

*The Conversation object raises events, to be dispatched into a message interface (these are collected in a temporary variable valid for that session) and returns. These events contain the entire data to reconstruct details of the message (timestamps, audit log, etc.), and don't just cater to what is pushed out to the receiver later.

*The Application Service persists the updated Conversation object and dispatches all events raised during the recent processing.

*A subscriber listening for the event gathers it, constructs the message in the right format (picking only the data it needs from the event), and performs the actual push to the receiver.

With this structure, you have a good implementation of the Open-Closed Principle.

*

*Your Conversation object changes only if you are changing business logic (like who should receive the message).

*Your Application service will seldom change because it simply loads and persists Conversation objects and publishes any raised events to the message broker.

*Your Subscriber logic changes only if you are pushing additional data to the receiver.

Update 2: Pseudocode
Application Service:
class MessageSender(ApplicationService):
    def send_message(request):
        // Deconstruct request object and call method
        conversation = ConversationRepo.find_by_id(request.id)

        // Call a method on the aggregate that generates events and updates the aggregates state
        conversation.send_message(request.from_user_id, request.content)

        // Application Service saves the aggregate
        ConversationRepo.save(conversation)

        // Any events raised are dispatched once the conversation has been successfully saved
        for event in conversation.events:
            message_interface.dispatch(event)

Domain Model:
class User(Aggregate):
    id: int
    username: str
    first_name: str
    last_name: str

    token: str
    is_online: bool

class Message(Entity):
    id: int
    author_id: int
    content: str
    sent_at: time

class Conversation(Aggregate):
    id: int
    users: list
    messages = list

    events = list // not persisted

    def send_message(from_user_id, content):
        for user in self.users:
            if not user.is_online:
                logger.warn("User is offline and cannot be messaged")

            if user.id == from_user_id:
                // continue; do not send messages to authors

            messages.append(Message(author_id=from_user_id, content=content, sent_at=datetime.utcnow()))
            self.events.add(SendMessageEvent(to=user.token, from=user.username, text=content))

A: Generally speaking (and this is true outside of DDD), you want to arrange dependencies so that code depends on things that are more stable then itself. Here stable means something that changes comparatively less often as the software evolves. (Initially, you'll have to go with an educated guess based on your understanding of the domain, but over time, as you work on the system, you can get a better sense of what tends to be stable, provided that you're looking).
So, while it's true that entities should generally encapsulate business logic, some of the objects in your domain will be better represented as simple data structures (so, just collections of fields, very little behavior - more or less what you have now). These objects will be those that don't have particularly interesting behavioral interactions with some other set of objects. E.g., they will not be members of (non trivial) aggregates that encapsulate important business rules; instead, they will mostly be manipulated or used by other code as data. That said, as the codebase evolves, if you actively seek opportunities to refactor and restructure parts of it, you may see more behavior rich objects emerge.
But for now, the concept of a message seems like a pretty stable thing. If that's the case, I'd rather have things depend on it, then vice versa. And, you're right, it feels wrong for the message, as conceptualized right now, to know about loggers and external message sending services.
I want to direct your attention to something else, though. Take a look at your MessageSender class, and its send method. There's some proper domain logic in it - it encapsulates rules that determine when a message can be sent, to whom, etc. But then it jumps to a different level of abstraction, transforming data into a format suitable for an external API to consume:
    class MessageSender implements MessageSenderInterface
    {
        private LoggerInterface $logger;

        public function send(Message $message): void {

            //////// --- this is domain logic --- ///////////////////////////
            /////////////////////////////////////////////////////////////////
            foreach ($message->getConversation()->getUsers() as $user) {
                if (!$user->isOnline()) {
                    $this->logger->warn('User is offline and cannot be messaged');
                }

                if ($user->equals($message->getAuthor())) {
                    // continue; don't send messages to authors
                }

                //////// --- this is infrastructure --- ////////////////////
                ////////////////////////////////////////////////////////////
                $messageData = [
                    'to' => $user->getToken(),
                    'from' => $message->getAuthor()->getUsername(),
                    'text' => $message->getText(),
                ];
                // send the message through some external API
            }
        }
    }

IMO, the more pertinent refactoring is to separate out the infrastructure-related (lower-level) parts (check your code for other places where this can be done). It would end up looking something like this:
    // Note that this class doesn't implement the interface now. It doesn't need to.
    // Instead, it has a reference to a MessageServiceInterface instance.
    class MessageSender
    {
        // these could be injected
        private LoggerInterface $logger;
        private MessageServiceInterface $messageService;   // <---

        public function send(Message $message): void {
            foreach ($message->getConversation()->getUsers() as $user) {

                if (!$user->isOnline()) {
                    $this->logger->warn('User is offline and cannot be messaged');
                    continue;
                }

                if ($user->equals($message->getAuthor())) {
                    continue;  // don't send messages to authors
                }

                $this->messageService->sendTo($user, $message);
            }
        }

        // other methods...
    }

Now it doesn't mix levels of abstraction, and when you read the code, it actually more closely expresses the business logic, without the extra clutter that was related to the logistics of sending the message (the logging messes up things a bit, but still). It's also separates responsibilities more clearly: this class handles the higher level business logic, while the $messageService object handles calling the external API (and associated data conversion). More importantly, the separation of responsibilities now means that there's a clear interface between the two components. In other parts of your codebase, the two aspects of the code may be more intermingled, implicitly coupled to each other in non-obvious ways - and if you leave them like that, they are only going to get more coupled over time.
This also enables proper dependency inversion - the MessageSender declares that it relies on an abstraction, the MessageServiceInterface (this interface should be in the same layer as MessageSender), and then a class in the infrastructure layer implements this interface, providing the actual message-sending capabilities.
Going back to your domain entities now, there are probably some things you can do to enrich them with behavior - and to make your code more expressive and readable. For example, in MessageSender, you're checking to see if the current user is the message author or not. That seems like a rule that can be expected to remain relatively stable. One thing you could do here is to enable either Message or Conversation to give you a list of users with the author excluded:
    foreach ($message->getConversation()->getUsers() as $user) {
        //...

        if ($user->equals($message->getAuthor())) {
            continue;  // don't send messages to authors
        }

        //...
    }

    // ----- vs --------------------------------

    foreach ($message->getRecipients() as $recipient) {
        //...
    }

You'll probably be able to find more opportunities like this, but don't go overboard - since other things depend on these entities, try to refactor them in a way that doesn't significantly impact their stability. If you introduce a method like this, and it has to be modified on nearly every change (resulting in cascading changes), than that method is not useful, design-wise; that code belongs somewhere else, where the impact of changes can be contained.
DDD being all about discovering domain concepts and reexamining your assumptions, you can explore this further. It's possible that the previous arrangement is not quite right. Should a message know who its recipients are? What if you want to forward it to different conversation? Furthermore, maybe your MessageSender is better described as something like a MessageBoard. Maybe the message board maintains a list of participants (what you currently call Conversation), and the message itself does not. Maybe the code from the previous example could be written like this:
    // in MessageBoard.send($message)

    $recipients = $this->participants->getRecipientsFor($message);
    foreach ($recipients as $recipient) {
        //...
    }

So now you've transformed a fairly generic idea of a "message sender" into an actual domain concept - it's now an explicit domain object, and a non-anemic one, too. Maybe that makes more sense, maybe not.
I'm not saying this is the way to go, I'm just trying to give you some ideas, to help you think out of the box.

A:
I tend to prefer exposing less data and like the encapsulation the second option provides.

Excellent. That is the way to go.
Now, is it a problem that "domain objects" know about "technology"? Of course not. Let's look at this way:
The people who tell you it's ok to have data structures and that "business logic" needs to be "pure" and "clean", also will tell you to expose tehnology in your application as public classes and methods. So your application now has a lot of technology-related stuff that knows your business and some data structures with "pure" logic, which have to be "synchronized" to backends somehow.
The alternative is to have real objects with real methods that model the business. The application is now only about the business, with "technology" only existing in the implementation of said business-related methods, i.e. hidden.
As our job as developers is to deliver functionality not technology, the second approach seems closer to what we actually want.
Also, here are my counterarguments to some points raised in other posts:

*

*Using technology will obscure the business things: The contrary is true. Having visible technology components will obscure the business. Having technology in the implementation of a method does not obscure anything. Visible parts are the classes and public methods. Those need to be technology-free.

*Your domain will have to know when to save data and when to send messages. Well, who else? Who knows when to save some data or communicate with some third party system if not the implementation of a business logic?

*You will need a different layer anyway to perform validations spanning the aggregate collection (checking for uniqueness of email address, for example). No, you don't. You don't need that if your methods are business-relevant.

*Your domain cannot be tested in isolation. FUD.


text:
Q: Is there any way to include the name of the interface when implementing the method Is there any way to include the name of the interface when implementing the method? If I have to implement 3 interfaces, then it would be hard to remind me where the implemented method comes from.
If I have 2 interface required to implement the same method name. How can I tell which method I am implementing?
public interface BarInt {
void method();
}
public interface GeeInt{
void method();
}
public class Foo implements BarInt, GeeInt{

@Override
public void method() {
    // TODO Auto-generated method stub

}
}

Thanks

A: Yes, you can just use a @see javadoc comment
public interface BarInt {
    void method();
}

public class Foo implements BarInt{

    /**
     * @see BarInt#method()
     */
    @Override
    public void method() {
        // TODO Auto-generated method stub
    }
}

A: Novaterata's answer in good, this is a similar approach with annotations.

You can always roll your own annotations.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Source {

    Class value();

}

Then you can use it like this:
@Source(List.class)
@Override
public boolean add(Object o) {
    return false;
}

With the retention policy of Source the annotation will not be part of the bytecode. It only serves as additional information for the reader, IDE and compiler.

A: Design wise name of method would reflect what the method does and you should be able to co-relate with the Interface the method belongs to.
De-bugging wise, most editor will take you the implemented Interface and method on few key strokes/clicks.


text:
Q: JQuery - how to call a function embedded inside an SVG I have an SVG file with a js function defined inside (performing some GreenSock animations).
The SVG simplified :
<svg baseProfile="tiny" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" >

<script type="text/javascript">
    var tl = new TimelineMax({paused: "true"});

    function hideShapes() {
      tl.reverse();
    }

    function animateJS(svg) {
      tl
        .to(svg, 1, {delay: 1, attr:{viewBox:"-120 -96 392 96"}} )
        .staggerTo(".symbol_copy", 1, {
          autoAlpha: true,
          svgOrigin: "8px 56px",
          cycle: {
            rotation: [-100,-75,-50,-25],
            rotationZ: 0.001,
            delay: function(index) { return 0.7-(0.15 * index); }
            }
          },
          0
        );
      tl.play();
    }
    </script>
</svg>

I am looking for a way to call the animateJS function from the JQuery code.

A: You might try injecting a <script> into your svg:

function callFn(n) {
  var s = document.createElement('script');
  s.innerText = 'this["' + n + '"]()';
  document.querySelector('svg').appendChild(s);
}
<button onclick="callFn('say')">CALL</button>

<svg baseProfile="tiny" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve">
<script type="text/javascript">
  function say() {
    alert('called!')
  }
</script>
</svg>

A: Eventually i found easier way to call the script defined inside the SVG.
In my JS I simply call window['my_function_name'] and it works !
Of course, it should be wrapped to check if it is defined ...


text:
Q: swipejs plugin - pagination bug I'm trying to implement swipejs slider to my site.
All is well, except that I need to set up pagination dots.
I've followed this exchange to get started add pagination navigation to swipejs carousel
My issue is that when you click the last pagination dot twice, all of my slide images show up at the same time. I figure this has to do with the index() javascript logic that ahs been implemented, but I am stumped as how to prevent this from happening.
html:

jquery:
 window.mySwipe = new Swipe(document.getElementById('swipeslider'), {
      startSlide: 1,
      speed: 400,
      auto: 3000,
      continuous: true,
      disableScroll: false,
    });

    var $navLi = $('#swipenav li');
    $navLi.on ('click', function () {
      window.mySwipe.slide($(this).index() + 1, 200);
        $(this).siblings().removeClass('selected');
        $(this).addClass('selected');
    });

CSS:
.swipe {
  overflow: hidden;
  visibility: hidden;
  position: relative;
}
.swipe-wrap {
  overflow: hidden;
  position: relative;
}
.swipe-wrap > div {
  float:left;
  width:100%;
  position: relative;
}

/* center slide images in slide-wrap div */
.swipe-wrap img {
  margin: 0 auto;
}

#swipenav {
  text-align: center;
}

#swipenav_container {
  margin-top: 20px;
}

#swipenav_container ul {
  margin: 0 auto;
  padding: 0;
}

#swipenav li {
  display: inline;
}

.dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #666;
  margin: 3px;
}

.dot:hover {
  background-color: #999;
}

.selected .dot {
  background-color: #fff;
}


text:
Q: Does $\sum_{k=1}^{\infty}k(p^{\frac{(k-1)k}{2}}-p^{\frac{(k+1)k}{2}})$ converge? Does the sum:
$$\sum_{k=1}^{\infty}k(p^{\frac{(k-1)k}{2}}-p^{\frac{(k+1)k}{2}})$$
$$ p\in\mathbb{R}|0{\leq}p<1$$
converse, and if so, to what function?

A: Let's simplify your expression to get Carl Najafi's expression :
\begin{align}
\sum_{k=1}^{\infty}k\left(p^{\frac{(k-1)k}{2}}-p^{\frac{(k+1)k}{2}}\right)&=\sum_{k=1}^{\infty}k\;p^{\frac{(k-1/2)^2}2-\frac 18}-\sum_{k=1}^{\infty}k\;p^{\frac{(k+1/2)^2}2-\frac 18}\\
&=\sum_{k=0}^{\infty}(k+1)\;p^{\frac{(k+1/2)^2}2-\frac 18}-\sum_{k=1}^{\infty}k\;p^{\frac{(k+1/2)^2}2-\frac 18}\\
&=\sum_{k=0}^{\infty}\;p^{\frac{(k+1/2)^2}2-\frac 18}\\
&=\sum_{k=0}^{\infty}\;p^{\frac{k(k+1)}2}\\
\end{align}
Proving Carl's claim.
After that you'll simply have to use the definition of the second theta function
$$\theta_2(0,\sqrt{p})=2\sum_{k=0}^{\infty}\;\sqrt{p}^{(k+1/2)^2}$$
to get the Alpha result  (since $\sqrt{p}^{1/4}=\sqrt[8]{p}$) :
$$\frac {\theta_2(0,\sqrt{p})}{2\;\sqrt[8]{p}}\quad\text{for}\ 0<p<1$$


text:
Q: Imagem do modelo não faz upload Olá, estou desenvolvendo uma app que precisa que o usuário faça upload de sua imagem de perfil, porém o mecanismo 'upload_to' do campo ft de CustomUser,aparentemente não está funcionando. A imagem simplesmente não vai para a pasta destinada, nem cria a pasta com o nome desejado, no caso 'fotos', que como deveria acontecer. Já tentei recriá-lo e nada.
models.py
#TODO: MODEL ADMIN E PAI DOS DEMAIS MODELS DE LOGIN
class CustomUser(AbstractBaseUser):
    email = models.EmailField(_('E-mail '), max_length=255, unique=True)
    username = models.CharField(_('Nome de usuário '), max_length=15, unique=True)
    choice = models.BooleanField(default=False)
    ft = models.ImageField(upload_to='fotos', null=True, blank=True, default='../media/site/user.png')
    date_joined = models.CharField(_('Data de início '), max_length=20, default=timezone.now())
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'choice']
    objects = UserManager()
    class Meta:
        verbose_name = _('Usuário')
        verbose_name_plural = _('Usuários')
    def __str__(self):
        return self.username
    def has_perm(self, perm, obj=None):
        return True
    def has_module_perms(self, app_label):
        return True
    @property
    def is_staff(self):
        return self.is_admin

forms.py
 class CustomCompanyCreationForm(UserCreationForm):
        class Meta(UserCreationForm.Meta):
            model = CustomCompany
            fields = ('name', 'departamento', 'cnpj', 'ft', 'telefone','cep', 'endereco', 'cidade', 'uf', 'username', 'email'
                  )

pag.html
{% load widget_tweaks %}

{% for hidden_field in form.hidden_fields %}
  {{ hidden_field }}
{% endfor %}

{% if form.non_field_errors %}

    {% for error in form.non_field_errors %}
      {{ error }}
    {% endfor %}

{% endif %}

{% for field in form.visible_fields %}

    {{ field.label_tag }}

    {% if form.is_bound %}
      {% if field.errors %}
        {% render_field field class="form-control is-invalid placeholder=form.text.label" %}
        {% for error in field.errors %}

            {{ error }}

        {% endfor %}
      {% else %}
        {% render_field field class="form-control is-valid placeholder=form.text.label" %}
      {% endif %}
    {% else %}
      {% render_field field class="form-control" placeholder=form.text.label %}
    {% endif %}

    {% if field.help_text %}
      {{ field.help_text|safe }}
    {% endif %}

{% endfor %}

Eu coloquei este código para alterar a foto com o cadastro já feito e o mecanismo para salvar a foto no cadastro parou.
views.py para alterar foto:
def fotoPerfil_change(request, id):
        customuser = get_object_or_404(CustomUser, pk=id)
        form = ChangePhoto(request.POST or None, request.FILES or None, instance=customuser)
        if form.is_valid():
            form.save()
            suc = "Foto de perfil atualizada com sucesso!"
            return render(request,'perfil/fotoperfil.html', {'form':form, 'suc': suc})
        return render(request, 'perfil/fotoperfil.html', {'form': form})

views.py do cadastro:
def register(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST or None, initial={
            'choice': True})
        if form.is_valid():
            user = form.save()
            user.choice = 0
            user.set_password(user.password)
            form.save()
            return render(request, 'register-sucess.html', {'user': user})
    else:
        form = CustomUserCreationForm()
    return render(request, 'register-f.html', {'form': form})


text:
Q: Using Transactions with GraphDB REST API to push a file into a repository i have the following requirement:
After selecting an ontology file i need to send it into my GraphDB-Repository. I´m programming with Angular 8.
I looked at the REST API Documentation and tried my best to understand what i need to do (i have like 3 months of experience with coding in angular [and overall actually], so all these concepts are still pretty new to me).
So i figured out i could start a new transaction, get the transaction-id and use it to submit my file. I dont know if this appraoch works, but anyway i´m not able to get the transaction-id, because it appears nowhere in the server response.
Recording to the documentation it should be in the header. But there is only the following content:
"cache-control": "no-store",
"content-language": "de",
"content-type": "text/plain;charset=UTF-8"
Thanks in advance!
var config_post: AxiosRequestConfig = {
    method: `POST`,
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/plain',
    },
    // responseType: 'text',
    // data: formData,
    url: "http://localhost:7200/repositories/testdb/transactions"
}
Axios(config_post).then(function (response) {
  console.log("Got a response from GraphDB ");
  console.log(response.headers);
})

A: As Damyan mentioned, you don't need to start a transaction to upload a file. You can do something like:
curl -X POST -H "Content-Type: application/x-trig" --data-binary '@test_data.trig' 'http://localhost:7200/repositories/test/statements'
or
curl -X POST -H "Content-Type: application/x-trig" -T test_data.trig 'http://localhost:7200/repositories/test/statements'


text:
Q: open differents threads using BackgroundWorker i build an application how take Pcap file (wireshark file) and play the packets, the play operation is with exe file who get file path and interface int.
private void btnStart_Click(object sender, EventArgs e)
{
    shouldContinue = true;
    btnStart.Enabled = false;
    btnStop.Enabled = true;
    groupBoxAdapter.Enabled = false;
    groupBoxRootDirectory.Enabled = false;
    string filePath = string.Empty;

    ThreadPool.QueueUserWorkItem(delegate
    {
        for (int i = 0; i < lvFiles.Items.Count && shouldContinue; i++)
        {
            this.Invoke((MethodInvoker)delegate { filePath = lvFiles.Items[i].Tag.ToString(); });
            pcapFile = new PcapFile();
            pcapFile.sendQueue(filePath, adapter);
        }

        this.Invoke((MethodInvoker)delegate
        {
            btnStart.Enabled = true;
            btnStop.Enabled = false;
            groupBoxAdapter.Enabled = true;
            groupBoxRootDirectory.Enabled = true;
        });
    });
}

the sendQueue code:
public void sendQueue(string filePath, int deviceNumber)
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo(@"D:\Downloads\SendQueue\sendQueue.exe");
            processStartInfo.Arguments = string.Format("{0} {2}{1}{2}", (deviceNumber).ToString(), filePath, "\"");
            processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.CreateNoWindow = true;
            processStartInfo.UseShellExecute = false;
            processStartInfo.ErrorDialog = false;

            using (Process process = Process.Start(processStartInfo))
            {
                process.WaitForExit();
            }
        }

A: Doen't look that you need Background worker.
     List<string> tags = new List<string>();
     foreach (object item in lvFiles.Items)
     {
        tags.Add(item.tag.ToString());
     }

     ThreadPool.QueueUserWorkItem(delegate
     {
       for (int i = 0; i < tags.Count && shouldContinue; i++)
       {
           sendQueue(tags[i], adapter);
       }

        //...
     }

A: Your UI thread is most likely blocked because the pcapFile.sendQueue is synchronous. This means even though your async loop queues the play files the UI thread is busy 99.99% of the time playing the file's content. This may or may not be the case since you haven't posted PcapFile's source.
The task to make your UI responsive is a bit more involving, you need to restructure PcapFile to load up a frame (audio? video?) at a time and let the UI thread run the rest of the time or even to work completely in the background.
The form design should also rely on events from PcapFile instead of trying to run it in a BackgroundWorker


text:
Q: Add *.jar file in folder named Android Dependencies I want to use library from openCV named "opencv library -2.4.3" , I install all what it needs , and now openCV tutorials work. So I need add the same openCV library to my project for use.
QUESTION
How to add opencv "library -2.4.3" from another project to mine's folder named Android Dependencies
Thanks in advance

A: Create a libs folder (/libs) in your project's root folder.
Copy the wanted jar to it.
It will be added to Android dependencies.

A: You have to click on on the project properties (Right Click -> Properties) and add it as dependency there.

A: I just did this with a project, using eclipse 4.2.1.  As with the other answerer, all I had to do was create a folder called "libs/" in my project, and it auto-updated the Android Dependencies list.  Are you copying and pasting inside of eclipse?
I moved the file to that folder using the file system, outside of eclipse.
This link describes how the libs folder gets added to Android Dependencies:
http://tools.android.com/recent/dealingwithdependenciesinandroidprojects

A: *

*Right click on project

*Select Properties

*Click on Android on left menu

*Click on Add

*Please select a Library Project

The jar will go into Android Dependencies.
If you add the jar directly to your project under libs or using build path, then it goes under Android Private Libraries.
Both methods works but referencing a library project can have benefits if you want to alter the code of the library during development.


text:
Q: Access raw file on GitHub Enterprise without user having to create token I have a repo with shell script and want to put single command to run it in readme file, like:
bash <(curl -L <path_to_raw_script_file>)

Raw file urls for GitHub Enterprise look like this: https://raw.github.ibm.com/<user>/<repo>/<branch>/<path_to_file>?token=<token>, where <token> is unique to the file and generated when accesing it via Raw button in repository or with ?raw=true suffix in url.
The problem is, tokens get invalidated after few days/when file is updated and I wouldn't like to update mentioned command each time token becomes invalid.  Is there a way to deal with it?
I know there is a way for user to create personal token and use it to login to github from machine he's runnning script from, but I wanted to keep it as simple as possible.
I was thinking of something like auto-generating that raw file url (since user reading the readme file on github surely does have access to the script located in the same repo), but I am not sure if that's possible.

A: No input, one-liner.
You can get this link by clicking the raw button in the GHE UI, just remove the token query param at the end.
curl -sfSO https://${USER}:${TOKEN}@${GHE_DOMAIN}/raw/${REPO_OWNER}/${REPO_NAME}/${REF}/${FILE}

A: I believe you'll always need the tokens - however if you'd like to automate the process you can dynamically request tokens associated with a github Oauth app and not associated with any user profile.
https://developer.github.com/enterprise/2.13/apps/building-oauth-apps/authorizing-oauth-apps/

A:
I know there is a way for user to create personal token and use it to login to GitHub from machine he's runnning script from, but I wanted to keep it as simple as possible.

Actually, using GCM (Git Credential Manager); the PAT will be provided when accessing the raw.xxx URL.
But only with GCM v2.0.692 which supports those URLs. See PR 599.

Fix GitHub Enterprise API URL for raw source code links
This is a simple fix of #598 for GitHub Enterprise instances that use a raw. hostname prefix for raw source code links.
I've verified this fix locally by swapping out the GitHub.dll that is used by Visual Studio.

So it now checks for 'raw.' in the hostname and remove it to get the correct GHE API URL.


text:
Q: Avoid "single positional indexer is out-of-bounds" error when searching for values in Pandas
*

*what I have

I have multiple dataframes stored as CSVs. The dataframes have 2 columns : Col1, Col2

*what I do

I read the CSVs files into separate dataframes, make list of the dataframes, and then search for the first occurrence of a value in "Col2" but only under condition that the value is there at least 10 consecutive rows. When it finds the value in "Col2" then I print corresponding value from the "Col1".

*where is problem

When I did it with 5 consecutive rows my script worked, however when I try it with (at least) 10 rows, this error occurrs: IndexError: single positional indexer is out-of-bounds. It happens because some dataframes doesn't meet the criteria and the value in "Col2" is not here 10 consecutive rows.

*how I want to solve it (I guess)

For the dataframes not meeting the criteria there would be the "Nan" printed instead of corresponding value from "Col1".
Code 1/2:
# current directory csv files
csvs = [x for x in os.listdir('.') if x.endswith('.csv')]
#read the csv files as separate dataframes
dfs = []
for file in csvs:
    df = pd.read_csv(file)
    dfs.append(df)

Code 2/2:
for dff1 in dfs:
    dff1[dff1['Col2'] == 0.000000].groupby((dff1['Col2'] != 0.000000).cumsum()).filter(lambda x: len(x) > 10)
    index = dff1[dff1['Col2'] == 0.000000].groupby((dff1['Col2'] != 0.000000).cumsum()).filter(lambda x: len(x) > 10).iloc[0][0] #this finds the corresponding value in Col1 if the Col2-value meets the criteria
    print(index) #this prints corresponding value from Col1

Then my code continues to make one dataframe of the printed values with assigned CSV names in a new column...
Maybe there is some trick with the "iloc" or "filter"?
desired output:
11
9
Nan
Nan
6
...

Now it just stops after second dataframe and print only "11,9" and then raises error because thirs dataframe doesn't meet the criteria.

A: Could be avoided with a simple if-statement
for dff1 in dfs:
    revised_df = dff1[dff1['Col2'] == 0.000000].groupby((dff1['Col2'] != 0.000000).cumsum()).filter(lambda x: len(x) > 10)
    if not revised_df.empty:
        index = dff1[dff1['Col2'] == 0.000000].groupby((dff1['Col2'] != 0.000000).cumsum()).filter(lambda x: len(x) > 10).iloc[0][0]
        print(index)
    else:
        print(np.nan)


text:
Q: Convertng labled images (EPS) to interactive web page using ImageMagick, OCR, JavaScript Business Insight:
We are in education domain and we have a requirement to automate the conversion of labeled images (EPS), into interactive exercises
(using HTML/SVG/JavaScript), used by students.
Technical Insight:
Layered EPS files is what we get from the pubishers. The EPS files should be converted into two PNG files: [1.png] Which has label texts only [2.png] Everything else but label texts.
Then [1.png] should be run through some advanced OCR (?) program that should output the label texts along with their positions (X,Y coords) in the image. Then HTML/JavaScript could be used to overlay the label texts over the [2.png] along with some interactions like Drag'n'drop using JavaScript.
Tried so far:
Manually converted the EPS into PNG and used ImageMagick and Tessaract OCR to get the label text alone.
Question:
How far the above requirements of image processing (EPS->PNG+text labels with coords) could be automated and what are the best tools that could be used? Appreciate the help in advance.
PS: I'm an UI developer and could handle the HTML/JavaScript part, if just the coords are provided for the labels.


text:
Q: run command where specific user login I have made a script that I want to run only where the user kyle logs in. I don't want it to be run on all users like a start-up app. I only want it to run when the user kyle logs in

A: To setup tasks to run on login, use gnome-session-properties. This means you can add programs to run when you login to the user account on your machine.

You can configure it like this - just add the command you want to run in the command box:

Very long answer on that here


text:
Q: MongoMapper getting data from a query I'm trying to return a User with MongoMapper:
Here's the user
1.9.3-p194 :004 > User.where(:email => 'redacted@gmail.com').all.count
=> 1

1.9.3-p194 :005 > User.where(:email => 'redacted@gmail.com').first.class
=> User

Looks good up to here...
1.9.3-p194 :005 > u = User.where(:email => 'redacted@gmail.com').first.class
=> User

1.9.3-p194 :007 > u.email
    NoMethodError: undefined method `email' for User:Class
    from /home/zensavona/.rvm/gems/ruby-1.9.3-p194/gems/mongo_mapper-0.12.0/lib/mongo_mapper/plugins/dynamic_querying.rb:39:in `method_missing'
    from (irb):7
    from /home/zensavona/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'

My understanding is that u holds an instance of User, but if this is so, why can't I access u's properties?

A: You are assigning the class User to the variable u instead of the instance of User which actually holds the data.
Try this instead:
u = User.where(:email => 'redacted@gmail.com').first


text:
Q: С++. Алгоритм Евклида(Нахождение НОД(Найбольшего общего делителя)), вроде алгоритм правильный, а выдает самое первое введенное #include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;

int NSD (int a, int b);

int main()
{
    int n, a, b, i;
    int c=0;
    cout<<"Vvedite kakoe budet kol-vo chisel:";
    cin>>n;
    cout<<"Vvedite chislo nomer #1: ";
    cin>>a;
    for (i=0; i<n-1; i++)
    {
        cout<<"Vvedite chislo nomer #"<<i+2<<": ";
        cin>>b;
        int NSD (int a, int b);
    }
    cout<<"NSD="<<a;
}

int NSD (int a, int b)
{
while (a!=b)
if (a>b) a-=b;
else b-=a;
return a;
}

Суть работы программы:
Введите с клавиатуры N целых чисел. Найти самый общий делитель этих чисел. Для вычисления наибольшего общего делителя двух чисел НОД(a,b) по алгоритму Евклида создайте функцию. Функция должна иметь 2 параметра – два целых числа и возвращать целое число – самый общий делитель этих чисел.

A: Начнем с несущественной мелочи — наибольший общий делитель обычно называют по-английски greatest common divisor, а стандартная функция в С++ для его вычисления — gcd. Я бы еще понял NOD, но NSD? просто запутывающее название.
Далее,
int NSD (int a, int b);

просто объявление ("где-то будет определена такая функция"), но никак не ее вызов. Понимаете разницу? Вы уже сделали объявление перед функцией main, больше таковое не nребуется. А вызов должен иметь вид
a = NSD(a,b);

А последнее — сама ваша функция реализована плохо. Представьте, что вам дали ряд из чисел
3 5 1000000000 1000000000 1000000000 ...

Что получится? При первом вызове вы получите 1, а потом начнете каждый раз выполнять по миллиарду вычитаний. Никакого смысла в этом нет, следует использовать получение остатка от деления, например, так:
int NSD(int a, int b)
{
    while(a && b) if (a < b) b %= a; else a %= b;
    return a + b;
}

A: cin>>a;
for (i=0; i<n-1; i++)
{
    cout<<"Vvedite chislo nomer #"<<i+2<<": ";
    cin>>b;
    int NSD (int a, int b);
}
cout<<"NSD="<<a;

а где у вас результат функции то, который вы выводить будете?
int res = NSD(a, b);
cout<<"NSD="<<a;


text:
Q: how to capitalize first character of sub array keys Array
(
[Carriers] => Array
    (
        [Carrier] => Array
            (
                [0] => Array
                    (
                        [carriersid] => a2e01423-2e8f-4458-8c13-2bfd08591d75
                        [phonenumber] => 1234567890
                        [network] => CELLCO PARTNERSHIP DBA VERIZON WIRELESS - CA
                        [wireless] => True
                        [zipcode] => 92675
                        [city] => Capistrano Valley
                        [price] => 3.0000
                        [createddate] => 2016-02-19 06:18:56
                    )

I want to capitalize [carriersid] to Carriersid.
I know array_change_key_case function is there but it only make keys either UPPERCASE or LOWERCASE.
Anyhelp is much appreciated. :)

A: Try this one it will make a first letter capital
<?php
    $arr = ['asd'=> '123', 'sdf' => '444'];
    $data = [];
    foreach ($arr as $key => $val) {
       $data[ucfirst($key)] = $val;
    }
    print_r($data);
?>

A: Here is the possible solution also if you want like this CarrieSid then use following otherwise use the code posted by Rahul -
$carrier_arr = $arr['Carriers']['Carrier'];

$final_arr = array();

for($i=0;$i<count($carrier_arr);$i++){

$final_arr[$i]['Carriersid'] =  $carrier_arr[$i]['carriersid'];
$final_arr[$i]['Phonenumber'] =  $carrier_arr[$i]['phonenumber'];
$final_arr[$i]['Network'] =  $carrier_arr[$i]['network'];
$final_arr[$i]['Wireless'] =  $carrier_arr[$i]['wireless'];
$final_arr[$i]['Zipcode'] =  $carrier_arr[$i]['zipcode'];
$final_arr[$i]['City'] =  $arr[$i]['city'];
$final_arr[$i]['Price'] =  $carrier_arr[$i]['price'];
$final_arr[$i]['Createddate'] =  $carrier_arr[$i]['createddate'];

}

A: This help you to change key of an array first letter capital
<?php
    foreach ($arr as $key => &$val) {
        $val = ucfirst($val);
    }
    ?>


text:
Q: Session not persisting on shared hosting - Laravel 4.2.17 I have a problem with the sessions on the shared hosting.
I developed an app on a local server (XAMPP) and it works great (sessions, auth etc). The problems have appeared when I moved the app on a shared hosting.
I realized that the sessions are not persisting from a page to another or from AJAX files to another page and the Authentication does not work either .
The only session that persists is the _token which has a different value after every refresh of the page.
I have the following configuration in the session.php file:
 'driver' => 'database',
 'lifetime' => 120,
 'expire_on_close' => false,
 'lottery' => array(2, 100),
 'path' => '/',
 'domain' => null

First, I used file driver and I had the same problem, and now I used the database.
Both file and database work on the local server but on the shared hosting they do not.
I tried all the solutions found on the forum but still I have the same problem.
I think the problem is at the session domain setting because when I change the value from null to other string on my local server, I have the same problem that I have encountered online.
Can you help me, please!
Thanks, Mirel

A: I fixed the problem. In my case the error because I have added a php closed tag ?> in the end of the included files. So removing  this tag will bring the application back to normal behavior.


text:
Q: Acumatica Custom DAC not triggering Business events Good day
Here is some background:
First created a View to group all a customer's Balances over branches:
CREATE VIEW CustomerBalance AS
select CustomerID,  sum(CurrentBal) AS 'CurrentBal'
from ARBalances
group by CustomerID;

Thereafter I pulled in the View into a Customization and Acumatica made me this DAC:
using System;
using PX.Data;

namespace JVDCustomerCreditLimit
{
  [Serializable]
  [PXCacheName("CustomerBalance")]
  public class CustomerBalance : IBqlTable
  {
    #region CustomerID
    [PXDBInt(IsKey = true)] // Added IsKey not sure if i should have...
    [PXUIField(DisplayName = "Customer ID")]
    public virtual int? CustomerID { get; set; }
    public abstract class customerID : PX.Data.BQL.BqlInt.Field<customerID> { }
    #endregion

    #region CurrentBal
    [PXDBDecimal()]
    [PXUIField(DisplayName = "Current Bal")]
    public virtual Decimal? CurrentBal { get; set; }
    public abstract class currentBal : PX.Data.BQL.BqlDecimal.Field<currentBal> { }
    #endregion
  }
}

With the above, I made a GI that links in the customer master for the credit limit
Here is the issue:
I made a Business event that looks for changes on the GI.
The Business event fires when I update the Credit limit(BAccount) but not if CurrentBalDAC(View) changed.
What did I miss on the DAC's code so that the business event will fire if there is a change?

A: I suspect the issue is that you are using a SQL view to drive data into the GI. Changes are not going to be detected as it will be other entities that are receiving the actual change.


text:
Q: Copy range from column A and write to column B I have a range in column A and I want to write for each element of range A something in Cell B. I am using this code but it doesn't seem to work:
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
    Set rng2 = Range("A:A" & LastRow).Select

    For Each Cell In rng2
        Cell.Offset(1, 0).FormulaR1C1 = "=isOK"
    Next Cell

What I want to write in column B. The last cell in A is 1887:

Can anyone assist please?

A: Set rng2 = Range("A:A" & LastRow).Select
this should be Set rng2 = Range("A1:A" & LastRow)
and your offset is the cell underneath, should be (0,1)

A: I corrected your code, give it a try :
Dim Cell as Range, LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set rng2 = Range("A2:A" & LastRow)

For Each Cell In rng2
    If Cell.Value <> vbNullString Then Cell.Offset(0, 1) = "isOK"
Next Cell

A: Avoid using Select as much as you can, it is a source of trouble. In this code, you dont need to use it.
I suppose that isOK is a user-defined function (UDF):
    LastRow = Cells(Rows.Count, "A").End(xlUp).Row
    Set rng2 = Range("A2:A" & LastRow)
    For Each Cell In rng2
        If not IsEmtpy(Cell) Then Cell.Offset(1, 0).Formula = "=isOK()"
    Next Cell

A: Try that better with normal excel formulas:
=if(lookup(A1;C1:Z20)=0;"isOK";"notOK")

copy that into every cell in column B and you will get your expected result ;)