text:
Q: Am I writing my unit tests correctly? NUnit + NSubstitute I recently started learning how to write unit tests, and what part of the unit to test for functionality and what to mock out. I'm using NSubstitute as my mocking framework. My example basically calls a repo class, which then makes an WEB API web call to an external service, ie: AddCreditCard, which then returns a result. I created 2 unit tests for AddCreditCard, one for Success, and one for Fail. I'm still not 100% sure I'm doing all of this correctly. The unit tests are passing, but im not sure if my Asserts are done on the correct data... All help and suggestions welcome!
public interface IApiResponse<T>
{
    HttpStatusCode StatusCode { get; set; }
    T Result { get; set; }
    string ErrorMessage { get; }
    bool HasErrors { get; }
}

public interface ISignedRequest
{
    void ConfigureSettings(SignedRequestSettings settings);

    IApiResponse Post(string jsonData, Dictionary<string, string> parameters = null,
        IOptionalHeaders optionalHeaders = null);
}

public class PaymentRepository
{
    private readonly SignedRequestSettings _settings;
    private readonly ISignedRequest _signedRequest;

    public PaymentRepository(ISignedRequest signedRequest = null)
    {
        if (signedRequest == null)
            _signedRequest = new SignedRequest();
        else
            _signedRequest = signedRequest;
    }

    public IApiResponse AddCreditCard(CreditCard request)
    {
        var jsonData =
            JsonConvert.SerializeObject(request);

        string action = string.Format("customers/{0}/paymentmethods", request.ConnectId);
        _settings.Url = string.Format("{0}{1}", String.Empty, action);
        _signedRequest.ConfigureSettings(_settings);

        return _signedRequest.Post(jsonData);
    }
 }

    [Test]
    public void AddCreditCard_GivenValidCreditCard_ReturnsCreatedResult()
    {
        //Given
        var apiResponse = Substitute.For<IApiResponse>();
        apiResponse.StatusCode = HttpStatusCode.Created;

        var signedRequest = Substitute.For<ISignedRequest>();
        signedRequest.Post(Arg.Any<String>()).Returns(apiResponse);

        var creditCard = Substitute.For<CreditCard>();
        creditCard.ConnectId = Guid.Parse("1fc1ad83-cd4e-4b68-bce6-e03ee8f47fb6");

        var repo = new PaymentRepository(signedRequest);

        //When
        var addCreditCardResponse = repo.AddCreditCard(creditCard);

        //Then
        signedRequest.Received(1).ConfigureSettings(Arg.Any<SignedRequestSettings>());
        signedRequest.Received(1).Post(Arg.Any<String>());

        Assert.AreEqual(HttpStatusCode.Created, addCreditCardResponse.StatusCode);
    }

[Test]
    public void AddCreditCard_GivenInvalidCreditCard_ReturnsHasErrorsResult()
    {
        //Given
        var apiResponse = Substitute.For<IApiResponse>();
        apiResponse.HasErrors.Returns(true);
        apiResponse.ErrorMessage.Returns("Add credit card error message");

        var signedRequest = Substitute.For<ISignedRequest>();
        signedRequest.Post(Arg.Any<String>()).Returns(apiResponse);

        var creditCard = Substitute.For<CreditCard>();
        creditCard.ConnectId = Guid.Parse("1fc1ad83-cd4e-4b68-bce6-e03ee8f47fb6");

        var repo = new PaymentRepository(signedRequest);

        //When
        var addCreditCardResponse = repo.AddCreditCard(creditCard);

        //Then
        signedRequest.Received(1).ConfigureSettings(Arg.Any<SignedRequestSettings>());
        signedRequest.Received(1).Post(Arg.Any<String>());

        Assert.AreEqual(apiResponse.HasErrors, addCreditCardResponse.HasErrors);
        Assert.AreEqual(apiResponse.ErrorMessage, addCreditCardResponse.ErrorMessage);
    }

A: I think your tests are mostly OK, but there are some bits I would question.  Both of your tests have these lines at the bottom:
signedRequest.Received(1).ConfigureSettings(Arg.Any<SignedRequestSettings>());
signedRequest.Received(1).Post(Arg.Any<String>());

Is it really important to those tests that these methods have been called on your signedRequest substitute?  I'd suggest that it probably isn't. If these calls weren't made I'd argue that your test would have failed anyway (although this is to some extent a stylistic decision).
The second thing I'd say is that you're missing one or more tests (again the number is a bit stylistic).  As it stands, you're not validating the information that's being supplied to the ConfigureSettings or Post calls on your signedRequest substitute.  Your repository code could simply be doing _signedRequest.Post("some random string"); and your test would still pass.  I'd add another test that validates these calls to ensure that the request is actually sent correctly.  This is where the Received validation would make sense.  Something like:
signedRequest.Received(1).ConfigureSettings(Arg.Is<SignedRequestSettings>(x=>x.Url == someHardCodedUrl));
signedRequest.Received(1).Post(someHardCodedJsonString);


text:
Q: Negative feedback op-amp In a non-inverting op-amp, the negative feedback input (V1) is calculated by (R2/Rf+R2)*Vout because it is a potential divider. However, why do we calculate the voltage across R2 and not for example Rf (i.e Rf/(R2+Rf))?

A:
However, why do we calculate the voltage across R2 ...

Because the amplifier output becomes stable when \$ V- = V+ \$.
\$ A \$ is a very large number. Any difference in the input voltages, \$ V_+ - V_- \$ is multiplied by \$ A \$ and appears on the output.
The essence of the negative feedback (not just in op-amps) is to correct the output and reduce the difference between the setpoint (\$ V_+ \$ in this case) and the feedback (\$ V_- \$) as close to zero as the gain allows.

A: Because that's what a voltage divider does.  In this case, we calculate the voltage across R2 since that's the voltage we want to know.  The voltage across R2 is the voltage being applied to the opamp negative input.
For a simple explanation and derivation of negative feedback, see my answer https://electronics.stackexchange.com/a/50472/4512.

A: You're using a formula you memorized rather than just finding the answer with Ohm's law. The current through Rf and R2 is Vout/(Rf + R2). So the voltage at the inverting input is Vout/(Rf+R2) * R1. If you wanted to, you could also figure it as Vout - (Vout/(Rf+R2))*Rf, which simplifies to the same formula.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to animate logo image from right to left infinite horizontal? I have more than 10 logo images. On page load, I have to display only 6 logos and remaining logos will slide from right to left side infinite horizontally.
Would you help me out in keyframes and CSS?
I found the example
https://codepen.io/mdashikar/pen/VWPvgE
but not 100% for me. If you notice that image is a slide from right to left side and wait for few seconds and again slider. I need image should slide continue without stop.

.logo_slider {}
.logo_slider ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

.logo_slider ul li {
  display: inline-block;
  border: 1px solid #ccc;
  margin: 20px;
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.logo_slider ul li a img {
  width: 100%;
  -webkit-animation: mymove 5s infinite; /* Safari 4.0 - 8.0 */
  animation: mymove 5s infinite;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove {
  from { right: 0px;  }
  to   { left: 200px; }
}

/* Standard syntax */
@keyframes mymove {
  from { right:0px;   }
  to   { left: 200px; }
}

A: Is this what you are looking for?
.logo_slider {
  overflow: hidden;
}

.logo_slider ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

.logo_slider ul li {
  display: inline-block;
  border: 1px solid #ccc;
  margin: 20px;
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.logo_slider ul li a img {
  position: relative;
  width: 100%;
  position: relative;
}

.logo_slider ul li:nth-child(1n+7) a img {
  -webkit-animation: mymove 5s infinite;
  /* Safari 4.0 - 8.0 */
  animation: mymove 5s infinite;
}

/* Safari 4.0 - 8.0 */

@-webkit-keyframes mymove {
  from {
    left: 100vw;
  }
  to {
    left: 0;
  }
}

/* Standard syntax */

@keyframes mymove {
  from {
    left: 100vw;
  }
  to {
    left: 0;
  }
}

Also look at my codepen: https://codepen.io/zothynine/pen/VQyzQZ

A: Try this it should work
// Fetch variables
var scrollTop = $(document).scrollTop();
var windowHeight = $(window).height();
var bodyHeight = $(document).height() - windowHeight;
var scrollPercentage = (scrollTop / bodyHeight);

// if the scroll is more than 90% from the top, load more content.
if(scrollPercentage > 0.9) {
    // Load content
}


text:
Q: C++ templates with derived classes I'm writing a library, and in it I have a class BaseClass.  Anyone using the library will be creating their own classes that inherit from BaseClass.  I have another class, lets call it Manager, which holds a vector of BaseClass pointers, which can hold any object derived from BaseClass.
The Manager class MUST handle the creation and destruction of any object added to its BaseClass vector.  This is because any object in the vector can be deleted at any time, and the Manager itself can also be deleted.  Because of this, the user of the library cannot add an object to the Manager's baseClass vector by passing it a pointer to an already existing object derived from BaseClass.  Well actually, I could allow the user to do that.  But that would involve copying a dummy object, which I'd rather not do.
To solve this, I'm trying to use a template function.  The user should pass the type of the object derived from BaseClass when trying to add it to the Manager's vector.  This is what I currently have.
//Manager.h
#include <vector>
#include "BaseClass.h"
#include <typeinfo>

class Manager {
    //Vector holding pointers to any objects inherited from BaseClass
    vector<BaseClass*> baseClasses;

    //Template function that needs to add NEW object to baseClass vector
    //This I'm having problems with
    template<class T>
    BaseClass* Add() {
        BaseClass* baseClass = new T();
        baseClasses.push_back(baseClass);
        return baseClass;
    }

    //Template function that gets object from baseClass vector
    //This works fine
    template<class T>
    BaseClass* Get() {
        for (int i = 0; i < baseClasses.size(); i++) {
            if (typeid(*baseClasses[i]) == typeid(T)) {
                return baseClasses[i];
            }
        }
        return NULL;
    }
};

For example, the user should do this when adding to or getting an object from the Manager's baseClass vector.  DerivedClass derives from BaseClass
Manager manager;
//Add a new DerivedClass object to Manager's vector
manager.Add<DerivedClass>();
//Get a pointer to the DerivedClass object that was just added
DerivedClass* derivedClass = (DerivedClass*)manager.Get<DerivedClass>();

My Get() function works fine.  What I need to know is, how can I get my Add() function to work?  Help would be greatly appreciated.

A: There are quite a few things unclear about your design, but if the question is whether you can enforce that the type T in the member function templa Add can be enforced to derive from BaseClass, the options are simple:

*

*do nothing, the compiler will gladly complain on the line BaseClass* baseClass = new T();

*add a static assert to make this more obvious

*use fancy SFINAE tricks to remove the function from the set of overloads

I would go for either one of the first two. The static assert could be spelled as:
static_assert(std::is_base_of<BaseClass,T>::value);

The SFINAE trick, I'd really avoid it, as it it going to make the code more confusing, but could be implemented as:
template <class T>
typename std::enable_if<std::is_base_of<BaseClass,T>::value,T*>::type
Add() {
   baseClasses.push_back(new T());
   return baseClasses.back();
}

(Note that I changed the return type to be T*, the object is a T, why return a BaseClass*? The same applies to the Get function there is no point in returning a BaseClass*, when you know that the object is really a T)
Now the actual problem is far more complicated, since your design is actively avoiding considerations of ownership, which you should not. Think about ownership of the objects and make sure that there is a clear owner (or that the resource is shared). Once you know who owns the objects, create a protocol for the rest of the code to notify the owner when an object needs to be deleted. If you allow any code to delete the pointers you hold, you are going to run into undefined behavior very soon.
Other lesser concerns could include the fact that you are enforcing that all components have a default constructor, which might or not be appropriate. You could simplify this restriction by having a non-templated Add that takes a pointer, and letting the caller create the objects in the way they please.
The use of typeid is usually a code-smell and I don't think this is the exception, maybe you would be better off by designing a type hierarchy that you can ask what the object is, rather than running typeid. If you are really determined to make the interface based on types, then consider whether dynamic_cast could be better. It will be more innefficient, but if you have multiple levels of inheritance, it will let you return the most derived objects as intermediate objects


text:
Q: How method chaining works in this case in JQuery method chaining requires every method to return the jquery object but,
when we use:
$("div").click(function(){ //some code }).css("backgroundColor","blue").
how does the css method get executed without clicking the div? how does it know the jquery object without click event gets triggered.

A: Here chaining will work like $("div").css("backgroundColor","blue").click(function(){ //some code });
Below is the working code snippet for the same.

$(document).ready(function() {
    $("div")
    .css("background", "blue")
    .click(function() {
        alert('Clicked');
    });
});

Click Here


text:
Q: Regex to find any string surrounded by a string I was struggling hard with this one for some time. I'm working with the MediaWiki API and I'm trying to find the headers of the articles with the regex (like I'm doing for every other styling). The syntax goes as follows:
 === some text in here === for h1,
 == some text in here == for h2
etc,. you get the idea.

I've been experimenting and testing in regex101 editor to find out the correct pattern but nothing works 100% for me.
Here you can see my test case, a text very similar to the ones I have to work with
As you can see, for the first couple occurrences he finds the match, but fails in the second paragraph.
Based on some stuff I read online I've tried ===.+?(?====) but it obviously doesn't work.


text:
Q: Read notify value from connected Bluetooth device when it is updated I am trying to read the updates to the notify value after writing to a Bluetooth device. This question is similar, but has no answers. I have tested the device using the nRF Connect app to write to it and watched the notify value change, but when I try to do it using the Flutter_Blue_Plus package (including their example app) the notify value is always empty. When I use the nRF Connect app, the notify value is never empty.
How can I read the updated notify value?
Code for connecting to the device and discovering services:
List<ScanResult> result = [];
try {
  result = await FlutterBluePlus.instance.startScan(timeout: Duration(seconds: 5)) as List<ScanResult>;

  resultIndex = getResultIndex(result, event.dataTrac.sensor.dtId.getOrCrash());
}
  catch (ex){
     log("Scan failed because another scan was already in progress.");
}

try {
  if (resultIndex == -1){
      for (int i = 0; i < 5; i++){
        result = await FlutterBluePlus.instance.startScan(timeout: Duration(seconds: 5)) as List<ScanResult>;
        resultIndex = getResultIndex(result, event.dataTrac.sensor.dtId.getOrCrash());
        if (resultIndex > -1){
          break;
        }
      }
   }
}
catch (ex){
   log("Exception while scanning: $ex");
}

if (resultIndex > -1 && result.isNotEmpty){
  final ScanResult r = result.elementAt(resultIndex);
  //Make sure we aren't already connected to the device
  if (!(await FlutterBluePlus.instance.connectedDevices).contains(r.device)) {
    //log("Had not connected to device; connecting now");
    await r.device.connect(autoConnect: false);
    await r.device.mtu.first;
    final int response = await r.device.requestMtu(165);
    log("New Mtu: $response");
    final List<BluetoothService> serviceList = await r.device.discoverServices();
}

Code for interacting with the device:
for (final s in serviceList) {
  //log("Service UUID: ${s.uuid}", name: "programming_status_bloc.dart");
  if (s.uuid.toString() ==
      "6e400001-b5a3-f393-e0a9-e50e24dcca9e") {
    serviceFound = true;
    final actualTxChar = s.characteristics.firstWhere((element) => element.uuid.toString() == txChar);
    final success = await actualTxChar.setNotifyValue(true);
    if (success){
      log("Set notify value.");
    }
    else {
      log("**Failed to set notify value.**");
    }

    final actualRxChar = s.characteristics.firstWhere((element) => element.uuid.toString() == rxChar);
    //log("Char UUID: ${char.uuid}");
    if (continueWriting) {
      continueWriting = false;
      //TODO: change CID for production
      final List<int> payload = createPayload(event.dataTrac, event.changedValuesMap, 151);
      //final payload = [12, 12, 12, 12, 12, 0, 70];
      add(ProgrammingStatusEvent.updated(true));

      await actualRxChar.write(payload);
      log("Wrote to device.");

      // final readResult = await actualRxChar.read();
      // log("Read result: $readResult");
    }
    //r.device.disconnect();
    bool readYet = false;

    final txCharSubscription = actualTxChar.value.listen((value){
      log("Notify value: $value");
    });

    await Future.delayed(Duration(seconds: 4));
    await txCharSubscription.cancel();
    await r.device.disconnect();
    await FlutterBluePlus.instance.stopScan();
  }
}
if (!serviceFound){
  r.device.disconnect();
  await FlutterBluePlus.instance.stopScan();
}

A: The problem was actually that Flutter Blue Plus (or possibly the cellphone Bluetooth) takes several seconds (longer than 4 when I tested it) to pick up on the notify value. The PC app picked it up right away. If I increased the delay before canceling the subscription to 10 seconds, the notify values came through just fine.


text:
Q: string split with expand=True. Can anyone explain what is the meaning? all_data['Title']= all_data['Name'].str.split(', ', expand=True)[1].str.split('.', expand=True)[0]

Can anyone explain what is the meaning of this line of code? Especially with the expand=True and [1] [0].

A: If you are using Pandas it is likely that you know also Jupyter Notebooks.
So, for simplicity and readability let's complete the code you've posted
with some additional information in a Notebook-like format:
(this markdown is here to override an error in the answer window interpreter)

```lang-python
    import pandas as pd

    raw_name = ['Bob, Mr. Ross', 'Alice, Mrs. Algae', 'Larry, Mr. lemon', 'John, Mr. Johnson']
    all_data = pd.DataFrame({'Name': raw_name})

    # This the OP's line
    all_data['Title'] = all_data['Name'].str.split(', ', expand=True)[1].str.split('.', expand=True)[0]

    all_data

Name
Title

0
Bob, Mr. Ross
Mr

1
Alice, Mrs. Algae
Mrs

2
Larry, Mr. Lemon
Mr

3
John, Mr. Johnson
Mr

Where the expand=True renders a set of columns of strings. Therefore, after the first split, you may apply again another str.split method since the first split has rendered dataframe of strings as columns. This would have been a little more complicated with a regular split (or expand=False) which renders a series of lists.
Better explained with code examples:
    all_data['Name'].str.split(', ', expand=False) # or no expand at all

0

0
[Bob, Mr. Ross]

1
[Alice, Mrs. Algae]

2
[Larry, Mr. Lemon]

3
[John, Mr. Johnson]

    all_data['Name'].str.split(', ', expand=True)

0
1

0
Bob
Mr. Ross

1
Alice
Mrs. Algae

2
Larry
Mr. Lemon

3
John
Mr. Johnson

    all_data['Name'].str.split(', ', expand=True)[1].str.split('.', expand=False)

0

0
[Mr,  Ross]

1
[Mrs,  Algae]

2
[Mr,  Lemon]

3
[Mr,  Johnson]

    all_data['Name'].str.split(', ', expand=True)[1].str.split('.', expand=True)

0
1

0
Mr
Ross

1
Mrs
Algae

2
Mr
Lemon

3
Mr
Johnson

Reference: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html

A: Take a look here: pandas.Series.str.split

Expand the split strings into separate columns.
If True, return DataFrame/MultiIndex expanding dimensionality.
If False, return Series/Index, containing lists of strings.

s = pd.Series(
    [
        "this is a regular sentence",
    ]
)
s.str.split(expand=True)

0      1     2        3         4
this    is     a        regular  sentence


text:
Q: добавление обновление удаление в источнике //Program.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Updates
{
    class Program
    {
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();

            Application.Run(new MainForm());
        }

    }
}

//CustomersUpdate.cs
//В этом блоке описаны основные ф-ии. InsertCustomers, ChangeCustomers, DeleteCustomers (изменяющие источник) при этом для DeleteCustomers не требуется форма, тк и сохранят в таблицу приложения ничего не надо.
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Updates.Commands
{
    static class CustomersUpdates
    {
        public static void InsertCustomers(DataRow customersRow)
        {
            string connectionString = @"Data Source=WIN-9VNS32J8479\IVAN;Initial Catalog=ShopDB;Integrated Security=True";
            string commandString = "INSERT Customers " +
                                   "VALUES (@FName, @LName, @MName, @Address1, @Address2, @City, @Phone, @DateInSystem) SELECT CustomerNo FROM Customers WHERE CustomerNo = @@IDENTITY";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                SqlCommand cmd = new SqlCommand(commandString, connection);
                cmd.Parameters.AddWithValue("FName", customersRow[1]);
                cmd.Parameters.AddWithValue("LName", customersRow[2]);
                cmd.Parameters.AddWithValue("MName", customersRow[3]);
                cmd.Parameters.AddWithValue("Address1", customersRow[4]);
                cmd.Parameters.AddWithValue("Address2", customersRow[5]);
                cmd.Parameters.AddWithValue("City", customersRow[6]);
                cmd.Parameters.AddWithValue("Phone", customersRow[7]);
                cmd.Parameters.AddWithValue("DateInSystem", customersRow[8]);

                try
                {
                    customersRow.Table.Columns[0].ReadOnly = false;
                    customersRow.SetField<int>(0, (int)cmd.ExecuteScalar()); //как я понимаю cmd возвращает новую введеную в источник строку и каким по образом преобразует ее в int?
                    //а затем записывается в 0-ю ячейку строки customersRow?? Непонятно что делает cmd.ExecuteScalar()?
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    customersRow.Table.Columns[0].ReadOnly = true;
                }

                customersRow.AcceptChanges();
            }
        }

        public static void ChangeCustomers(DataRow customersRow)
        {
            string connectionString = @"Data Source=WIN-9VNS32J8479\IVAN;Initial Catalog=ShopDB;Integrated Security=True";

            StringBuilder builder = new StringBuilder();

            string commandString = "UPDATE Customers " +
                                   "SET FName = @FName," +
                                   "LName = @LName," +
                                   "MName= @Mname," +
                                   "Address1 = @Address1," +
                                   "Address2 = @Address2," +
                                   "City = @City," +
                                   "Phone = @Phone," +
                                   "DateInSystem = @DateInSystem " +
                                   "WHERE CustomerNo = @CustomerNo";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                SqlCommand cmd = new SqlCommand(commandString, connection);
                cmd.Parameters.AddWithValue("CustomerNo", customersRow[0]);
                cmd.Parameters.AddWithValue("FName", customersRow[1]);
                cmd.Parameters.AddWithValue("LName", customersRow[2]);
                cmd.Parameters.AddWithValue("MName", customersRow[3]);
                cmd.Parameters.AddWithValue("Address1", customersRow[4]);
                cmd.Parameters.AddWithValue("Address2", customersRow[5]);
                cmd.Parameters.AddWithValue("City", customersRow[6]);
                cmd.Parameters.AddWithValue("Phone", customersRow[7]);
                cmd.Parameters.AddWithValue("DateInSystem", customersRow[8]);

                cmd.ExecuteNonQuery();
            }
            customersRow.AcceptChanges();
        }

        public static void DeleteCustomers(DataRow customersRow)
        {
            string connectionString = @"Data Source=WIN-9VNS32J8479\IVAN;Initial Catalog=ShopDB;Integrated Security=True";

            StringBuilder builder = new StringBuilder();

            string commandString = "DELETE Customers " +
                                   "WHERE CustomerNo = @CustomerNo";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                SqlCommand cmd = new SqlCommand(commandString, connection);
                cmd.Parameters.AddWithValue("CustomerNo", customersRow[0, DataRowVersion.Original]);

                cmd.ExecuteNonQuery();
            }
        }

        public static void Update(DataTable customers)
        {
            foreach (DataRow customer in customers.Rows)
            {
                if (customer.RowState == DataRowState.Deleted)
                    DeleteCustomers(customer);
                if (customer.RowState == DataRowState.Added)
                    InsertCustomers(customer);
                if (customer.RowState == DataRowState.Modified)
                    ChangeCustomers(customer);
            }
            customers.AcceptChanges();
        }
    }
}

//Main Form.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Updates.Commands;

namespace Updates
{
    public partial class MainForm : Form
    {
        string connectionString = @"Data Source=WIN-9VNS32J8479\IVAN;Initial Catalog=ShopDB;Integrated Security=True";
        string commandString = "SELECT * FROM Customers";

        DataTable customers = new DataTable("Customers");

        public MainForm()
        {
            InitializeComponent();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            SqlDataAdapter adapter = new SqlDataAdapter(commandString, connectionString);
            adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
            adapter.Fill(customers);

            dataGridView1.ReadOnly = true;
            dataGridView1.DataSource = customers; //первая форма отображается в GridView
        }

        private void addButton_Click(object sender, EventArgs e) //?? как понимаю обработчик для кнопки Add (ввод новой записи)
        {
            System.Windows.Forms.DialogResult result = new AddCustomerDialog(customers).ShowDialog();
        }

        private void modifyButton_Click(object sender, EventArgs e) //это видимо обработчик кнопки Update (обновление выбранной записи)
        {
            var editDialog = new EditCustomerDialog(customers, (dataGridView1.CurrentRow.DataBoundItem as DataRowView).Row); //возвращаем в переменную editDialog объект типа EditCustomerDialog

            editDialog.ShowDialog();

        }

        private void deleteButton_Click(object sender, EventArgs e) //обработчик Ok Cancel
        {
            DialogResult res = MessageBox.Show("Вы уверены что хотите удалить этого клиента?", "DeleteDialog", MessageBoxButtons.OKCancel);

            if (res == System.Windows.Forms.DialogResult.OK)
            {
                var rowToDelete = (dataGridView1.CurrentRow.DataBoundItem as DataRowView).Row;
                rowToDelete.Delete();

                CustomersUpdates.DeleteCustomers(rowToDelete);
            }
        }

    }
}

//Addcustomerdialog
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Updates.Commands;

namespace Updates
{
    public partial class AddCustomerDialog : Form
    {

        DataTable table;

        public AddCustomerDialog(DataTable table)
        {
            this.table = table;

            InitializeComponent();
        }

        private void AddCustomerDialog_Load(object sender, EventArgs e)
        {
            CenterToScreen();
        }

        private void button1_Click(object sender, EventArgs e) // подтверждение ок button для insert
        {
            DataRow newRow = table.NewRow();
            newRow["FName"] = textBox1.Text.Count() == 0 ? null : textBox1.Text; //как я понимаю считаем есть ли символы в текстбоксе. Если нет оставляем null, иначе берем содержимое текстбокса.
            newRow["LName"] = textBox2.Text.Count() == 0 ? null : textBox2.Text;
            newRow["Address1"] = textBox3.Text.Count() == 0 ? null : textBox3.Text;
            newRow["City"] = textBox4.Text.Count() == 0 ? null : textBox4.Text;
            newRow["Phone"] = textBox5.Text.Count() == 0 ? null : textBox5.Text;

            try
            {
                table.Rows.Add(newRow);

                DialogResult = System.Windows.Forms.DialogResult.OK;

                CustomersUpdates.InsertCustomers(newRow);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Close();
            }

        }

        private void button2_Click(object sender, EventArgs e) // cancel button for insert in Customers
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
    }
}

//EditCustomersDialog.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Updates.Commands;

namespace Updates
{
    public partial class EditCustomerDialog : Form
    {
        DataTable table; //во втором проекте этой строки не было
        DataRow rowToEdit;

        public EditCustomerDialog(DataTable table,  DataRow rowToEdit) //это конструктор EditCustomerDialog //таблицу во втором проекте не подавали
        {
            InitializeComponent();

            this.rowToEdit = rowToEdit;
            this.table = table; //эта строка была закомитена во 2-м проекте

            CenterToScreen();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                rowToEdit["FName"] = textBox1.Text; //здесь мы изменяем конкретные ячейки строки. значения берем из текстбоксов которые заполняет клиент в воторой форме(после нажатия Update)
                rowToEdit["Address1"] = textBox3.Text;
                rowToEdit["City"] = textBox4.Text;
                rowToEdit["Phone"] = textBox5.Text;

                CustomersUpdates.ChangeCustomers(rowToEdit); //??во втором update проекте  было rowToEdit.Тable
                //то есть мы передавали всегда Table, где происходила проверка на Modify, каждой строки, а здесь получается передаем одну строку, а как же другие строки?

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            this.Close();

        }

        private void EditCustomerDialog_Load(object sender, EventArgs e)
        {
            textBox1.Text = rowToEdit["FName"].ToString(); //текстбоксам присваиваются значения которые пользователь подтвердил нажав ок после воода во второй форме (стороки кода№30-48)
            textBox2.Text = rowToEdit["LName"].ToString();
            textBox3.Text = rowToEdit["Address1"].ToString();
            textBox4.Text = rowToEdit["City"].ToString();
            textBox5.Text = rowToEdit["Phone"].ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}

Пример начала выполнения (первая форма)
ответьте, пожалуйста, на вопросы
1)(Форма EditCustomerDialog.cs) В строке CustomersUpdates.ChangeCustomers(rowToEdit); //во втором Update проекте  было rowToEdit.Тable
то есть мы передавали всегда Table, где происходила проверка на Modify, каждой строки, а здесь получается передаем одну строку, а как же другие строки?
2)(Файл CustomerUpdate.cs)                 try
                customersRow.SetField<int>(0, (int)cmd.ExecuteScalar()); //как я понимаю cmd возвращает новую введеную в источник строку и каким по образом преобразует ее в int?!

А затем записывается в customersRow.
2.1) Непонятно что делает cmd.ExecuteScalar()?
2.2) Также читал сдесь https://docs.microsoft.com/ru-ru/dotnet/api/system.data.datarowextensions.setfield?view=netframework-4.8

Но в коде передается только два значения, а не три. Не ясно 0 это номер столбца или строки?
            }

*

A: *

*Форма EditCustomerDialog.cs) В строке CustomersUpdates.ChangeCustomers(rowToEdit); //во втором Update проекте было rowToEdit.Тable то есть мы передавали всегда Table, где происходила проверка на Modify, каждой строки, а здесь получается передаем одну строку, а как же другие строки? - Другие строки успешно, перебираются и в зависимости customer.RowState удаляются, обновляются либо добавляются.

*Непонятно что делает cmd.ExecuteScalar() - (Executes the query, and returns the first column of the first row in the result set returned by the query.) - выполняет запрос и возвращает значение первую колонку первой записи в результата возвращаемого запросом.


text:
Q: How to get id of an image of a clicked cardview from view element In my layout applications I have a card view where each card contains a representations of an application.
In each card there are: the name of an applications, a description and his icon.
@Override
    public void onBindViewHolder(@NonNull final AdapterForCard.ViewHolder holder, final int position) {

        holder.iv.setImageDrawable(myCards.get(position).getIcon());
        holder.titleView.setText(myCards.get(position).getTitle());
        holder.descView.setText(myCards.get(position).getInfo());

        holder.cv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(holder.cv.getContext(), "Cliccked card: "+(holder.titleView.getText()), Toast.LENGTH_SHORT).show();
                Context context = v.getContext();

                Intent i = new Intent(context,DetailsAppActivity.class);
                //First Convert Image into Byte Array
                // and then pass into Intent and in next activity
                // get byte array from Bundle and Convert into Image(Bitmap) and set into ImageView
                // holder.iv.getId_ 2131296339 v.getId_ 2131296348.
                //
                int id1 = holder.iv.getId();
                int id2 = v.getId();
                int id3 = R.id.iconView;
                System.out.println("id1_ "+id1);
                System.out.println("id2_ "+id2);
                System.out.println("id3_ "+id3);

                Bitmap btm = BitmapFactory.decodeResource(v.getResources(),id1);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                System.out.println("bitmap is null ? "+(btm==null));
                btm.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();

                i.putExtra("title", ""+holder.titleView.getText());
                i.putExtra("title", ""+holder.titleView.getText());
                i.putExtra("icon",byteArray);

                context.startActivity(i);

            }
        });
    }

I want pass the three date to my DetailsActivity, but i have the follow error:
    id1_ 2131296339
    id2_ 2131296348
    id3_ 2131296339
    bitmap is null ? true
E/AndroidRuntime: FATAL EXCEPTION: main
                      Process: com.salvatorefiorilla.systemmonitor, PID: 6151
                      java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
                          at com.salvatorefiorilla.systemmonitor.AdapterForCard$1.onClick(AdapterForCard.java:90)
                          at android.view.View.performClick(View.java:4785)
                          at android.view.View$PerformClick.run(View.java:19858)
                          at android.os.Handler.handleCallback(Handler.java:739)
                          at android.os.Handler.dispatchMessage(Handler.java:95)
                          at android.os.Looper.loop(Looper.java:155)
                          at android.app.ActivityThread.main(ActivityThread.java:5696)
                          at java.lang.reflect.Method.invoke(Native Method)
                          at java.lang.reflect.Method.invoke(Method.java:372)
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

How to set id correctly?

A: Update 2
As you told that you don't have resource id. You have application package, and have to get application icon, so you can pass package name of that app. And in next activity just get application icon.
Important Edit
I did not notice that you are using Drawable object instead of using an int id. There is no need to store drawable objects in List. So do the following.

*

*First change type of icon as int (Resource id).

list.setIconId(R.drawable.ic_launcher)
BitmapFactory.decodeResource(getResources(), myCards.get(position).getIconId());

*

*set ImageView image by below method.

*Old solution is also edited for same.

holder.iv.setImageResource(myCards.get(position).getIconId());
Solution
Just change holder.iv.getId(); with myCards.get(position).getIconId()
Bitmap btm = BitmapFactory.decodeResource(v.getResources(),myCards.get(position).getIconId());

Reason of crash
Because holder.iv.getId() returns you ImageView id NOT drawable resource id.
Suggestion (must use)
Pass resource id instead of passing bitmap array. There is no need to pass byte array of bitmap.
i.putExtra("icon",myCards.get(position).getIconId());

in next activity
imageView.setImageResource(getIntent().getIntExtra("icon",0));

Isn't it simple :)

A: well your stream is null because you are giving id instead of  position. use this one
mCard.get(position).getIcon()


text:
Q: What is the difference among these sentences? What is the difference among these sentences:
Question:

Why were you so tired yesterday?

Answer:

*

*Because I jog all morning.

*Because I was jogged all morning.

*Because I had been jogging all morning.

*Because I had been jogged all morning.

A: Consider the following definitions:

Jog verb
  1 [no object] Run at a steady gentle pace, especially on a regular basis as a form of physical exercise
  2 [with object] Nudge or knock slightly: a hand jogged his elbow
- ODO

Your #1 and #3 use definition 1. If you meant that you meant that you were tired due to all the exercise, then #3 works because the past perfect indicates a completed action - in this case, the action leading to your tiredness the day before. However, the present tense of #1 ("Because I jog all morning.") indicates a recurring activity - you habitually use your mornings for jogging. It doesn't directly answer why you were so tired on a specific day (yesterday).
Your #2 and #4 use definition 2.
If you meant that you were tired from being pushed around all morning (and presumably having to work to maintain your balance), then both #2 and #4 work (both indicate completed actions, in this case performed on you).


text:
Q: How do I restart the Switch? My Nintendo Switch can't connect to the internet. Other devices are connected fine and the Switch is connected to my WiFi, however the Switch won't connect to the internet. Nintendo's network status page says all services are up.
I'd like to restart my Switch, but can't find anyway to do it.
How do I restart my Switch?

A: Use the power button on the top. The Home button is only used to put the Switch into sleep mode.

A: Holding the power button (located on the top of the Switch) opens a menu that gives you the option to power the system off entirely.
To answer the problem, rather than the question though: I had a similar issue with my wi-fi not long ago.  Rather than powering the system off and on again, I found it was enough to cycle the network adapter by putting the system in Airplane mode and then taking it out, which is in the same home button menu as the sleep option.


text:
Q: Shading with squared falloff always makes everything black I have recently tried to change the current way I calculate diffuse lighting in my RayTracer. It used to be calculated like this:
 float lambert = (light_ray_dir * normal) * coef;
 red += lambert * current.color.red * mat.kd.red;
 green += lambert * current.color.green * mat.kd.green;
blue += lambert * current.color.blue * mat.kd.blue;

where coef is an attenuation coefficient that starts at 1 for each pixel and is then attenuated for each reflected ray that is generated by this line:
coef *= mat.reflection;

This worked well.
But I decided to try something more realistic and implemented this:
float squared_attenuation = LIGHT_FALLOFF * lenght;
light_intensity.setX ((current.color.red /*INTENSITY*/)/ squared_attenuation);
light_intensity.setY ((current.color.green  /*INTENSITY*/)/ squared_attenuation);
light_intensity.setZ ((current.color.blue  /*INTENSITY*/)/ squared_attenuation);
red   += ALBEDO * light_intensity.getX() * lambert * mat.kd.red;
green += ALBEDO * light_intensity.getY() * lambert * mat.kd.green;
blue  += ALBEDO * light_intensity.getZ() * lambert * mat.kd.blue;

where LIGHT_FALLOFF it is a constant value:
#define LIGHT_FALLOFF M_PI * 4

and length it is the length of the vector that goes from the point light center to the intersect point:
inline float normalize_return_lenght ()  {
     float lenght = sqrtf (x*x + y*y + z*z);
     float inv_length = 1/lenght;
     x = x * inv_length, y = y * inv_length, z = z * inv_length;
     return lenght;
  }

float lenght = light_ray_dir.normalize_return_lenght ();

The problem is that all this is generating nothing more than a black screen! The main culprit is the length that goes as the divisor in the light_intensity.set. It makes the final color values being some value ^ -5. However, even if I replace it by one (ruining my goal of a realistic light attenuation), I still get color values to close to zero still, hence a black image.
I tried to add another light_sources closer to the objects, however the fact that the models that shall be shaded are made of multiple polygons with different coordinates, make hard to determine a goodl ocation for them.
So I ask. It seems normal to you that this is happening or it seems a bug? For me theory, does not seems strange for me, since the attenuation is quadratic.
Is does not seem, there is a some hint as to where to place the light sources, or to anything as can get an image that is not all black?
Thanks for reading all this!
P.S: Intensity is commented out because on the example that I used to do my code, it was one

A: So you are assuming that the light has a luminosity of "1" ?
How far away is your light?
If your light is - say - 10 units away, then they contribution from the light will be 1/10, or a very small number. This is probably why your image is dark.
You need to have quite large numbers for your light intensity if you are going to do this. In one of my scenes, I have a light that is about 1000 units away (pretending to be the Sun) and the intensity is 380000!!
Another thing ... to simulate reality, you should be using 1 / length^2. The light intensity falls off with the square of distance, not just with distance.
Good luck!


text:
Q: What does this phrase apply to?
User A is playing this game on XX defeated 5% of all gamers.

I read this from an app, and XX refers to a platform. Does the bold part apply to "this game"? Which means:

User A is playing this game on XX, and this game has defeated 5% of
  all gamers.


text:
Q: error when I try to create a new repository in git on mac os sierra I tried to create a new git repository after:
git init
this result's:
enter image description here
-bash: test: on: integer expression expected
-bash: test: master: integer expression expected
-bash: test: _NO_REMOTE_TRACKING_: integer expression expected
-bash: test: ^: integer expression expected

A: It looks to me like your repository creation worked just fine.  Whatever script(s) you are using that are intended to set your bash prompt based on your current Git repository, however, are hopelessly broken in the rare case that you are ever in a new, empty repository.
The brokenness is likely to go away once you create the first commit in that repository.  You could also try finding better bash scripts for setting prompts.

A: I had the same problem. I used an old version of https://github.com/magicmonty/bash-git-prompt (included inside my $HOME/.bashrc). After updating the gi-prompt the problem was gone.


text:
Q: Passing multiple values for same variable in stored procedure I have a variable that passes multiple values to stored procedure.
When I see through fidler I see values being passed correctly like
    arg1=331
    arg1=222
    arg1=876
    arg1=932

In my stored procedure I am reading as
    procedure mainValues
     @Arg1List     nvarchar(3000)
    as begin
  --Temp table to store split values
  declare @tmp_values table (
  value nvarchar(255) not null);

   --function splitting values
   insert into @tmp_values
   select * from f_split(@Arg1List, ',');

  --inserting in table value column is int.
  insert into t_values (
   value
  )
  select
  b.value
  from @tmp_values b;

When I test it, it doesn't add any values in t_values table. I checked the function etc. are all working fine. The problem is @Arg1List. It looks like stored procedure has no values in it. Please let me know how to declare @Arg1List properly so it takes multiple values as it seems to be the problem.

A: You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.
Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....
TABLE TYPE
CREATE TYPE dbo.TYPENAME AS TABLE
 (
    arg int
  )
 GO

Stored Procedure to Accept That Type Param
 CREATE PROCEDURE mainValues
 @TableParam TYPENAME READONLY
 AS
   BEGIN
    SET NOCOUNT ON;
  --Temp table to store split values
  declare @tmp_values table (
  value nvarchar(255) not null);

   --function splitting values
   INSERT INTO @tmp_values (value)
   SELECT arg FROM @TableParam

   SELECT * FROM @tmp_values  --<-- For testing purpose
END

EXECUTE PROC
Declare a variable of that type and populate it with your values.
 DECLARE @Table TYPENAME     --<-- Variable of this TYPE

 INSERT INTO @Table                --<-- Populating the variable
 VALUES (331),(222),(876),(932)

EXECUTE mainValues @Table   --<-- Stored Procedure Executed

Result
╔═══════╗
║ value ║
╠═══════╣
║   331 ║
║   222 ║
║   876 ║
║   932 ║
╚═══════╝

A: Your stored procedure is designed to accept a single parameter, Arg1List.  You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

A: Well, without a bigger view of your exact setup, how this is being called and what is happening in f_split it can be hard to debug the situation as I am basically just guessing. I can, however, offer an alternative solution that doesn't involve UDFs but rather relies on SQL Server's build in mechanisms... XML.
The below proc declaration accepts an XML type parameter called @parmsXML. This would replace your @Arg1List parameter. When you EXEC dbo.mainValues, you supply the @parmsXML parameter as a string of XML nodes rather than a comma separated list (I assume this is what you are doing but from your question it is not exactly clear):
<parms>
    <parm>331</parm>
    <parm>222</parm>
    <parm>876</parm>
    <parm>932</parm>
</parms>

The stored proc does this:

*

*Just selects the values from from the @parmsXML variable directly

*SELECTs the values from the @parmsXML variable into a temp #t_values table

*SELECTs from the #t_values table

In your own implementation, you could get rid of the first step (Just select....), then change the SELECT INTO into a INSERT INTO SELECT.
I have the below script setup so that it will DROP IF EXISTS then CREATE the proc and then EXECUTE it with the @parmsXML setup as above.
--========================================================================================================================
/* DROP AND RECREATE PROC                                                                                */
--========================================================================================================================

IF EXISTS (
  SELECT *
    FROM INFORMATION_SCHEMA.ROUTINES
   WHERE SPECIFIC_SCHEMA = N'dbo'
     AND SPECIFIC_NAME = N'mainValues'
)
   DROP PROCEDURE dbo.mainValues
GO

CREATE PROCEDURE dbo.mainValues
    @parmsXML XML
AS

--========================================================================================================================
/* INTERPRETER DIRECTIVES                                                                                */
--========================================================================================================================

SET NOCOUNT ON;    -- Turn off "(N row(s) affected)" messages
SET XACT_ABORT ON; -- Auto ROLLBACK on exception

--========================================================================================================================
/* PARMS PROCESSING                                                                                */
--========================================================================================================================

-- select from @parmsXML

RAISERROR('Selecting values directly from @parmsXML', 0, 1);

SELECT Parm = n.x.value('.[1]', 'INT')
FROM @parmsXML.nodes('/parms[1]/parm') n(x)
;

-- insert into

RAISERROR('Inserting @parmsXML values into #t_values', 0, 1);

SELECT Parm = n.x.value('.[1]', 'INT')
INTO #t_values
FROM @parmsXML.nodes('/parms[1]/parm') n(x)
;

-- select from #t_values

RAISERROR('Selecting from #t_values', 0, 1);

SELECT *
FROM #t_values
;

GO

--========================================================================================================================
/* Example EXEC code runs stored proc with @parmsXML supplied                                                           */
--========================================================================================================================

EXECUTE dbo.mainValues @parmsXML = '
    <parms>
        <parm>331</parm>
        <parm>222</parm>
        <parm>876</parm>
        <parm>932</parm>
    </parms>
    '
GO


text:
Q: Eclipse is not starting Eclipse starts from terminal but when i try to start it from gui then it says java runtime environment don't found.
Environment variables are:
JAVA_HOME="/opt/jdk1.6.0_20"
PATH=$PATH:"/opt/jdk1.6.0_20/bin"
And one more thing so far i normally copy jre folder from jdk to eclipse directory, which works fine but what is actual way. i mean this won't be standard way to do that.
Thanks in advance

A:
And one more thing so far i normally
  copy jre folder from jdk to eclipse
  directory, which works fine

No, this is not necessary or desirable.  You should not have to do any such thing.
If you open up a command shell and type "java -version", what comes back?

A: Edit eclipse.ini (from the Eclipse folder) and add the following at the beginning:
-vm
C:/Java/jdk1.6.0_22/bin

where C:/Java/jdk1.6.0_22/bin should be your path to the java bin directory.
Keep it on two lines.

A: Well the reason eclipse won't start from GUI despite of the fact that environment variables are set, is:
You have set the variable in bashrc or bash_profile, these two are for the specific logged in user, but you also need to set in etc/profile which is for all the users.
So once you set the PATH and JAVA_HOME in etc/profile it will launch from GUI.
Worked for me! ;)

A: Faced the same problem and the suggestion addressed my problem!
After setting /etc/profile as indicated in the link below, I logged out and logged back in for GUI based Eclipse to work.
http://www.cyberciti.biz/faq/linux-unix-set-java_home-path-variable/


text:
Q: Django: Access given field's choices tuple I would like to get the named values of a choices field for a choice that is not currently selected. Is this possible?
For instance: models.py
FILE_STATUS_CHOICES = (
    ('P', 'Pending'),
    ('A', 'Approved'),
    ('R', 'Rejected'),
)

class File(models.Model):
    status = models.CharField(max_length=1, default='P', choices=FILE_STATUS_CHOICES)

views.py
f = File()
f.status = 'P'
f.save()

old_value = f.status

print f.get_status_display()
> Pending

f.status = 'A'
f.save()

new_value = f.status

print f.get_status_display()
> Approved

How can I get the old display value from the 'P' to 'Pending?' I may be able to do so by creating a form in the view and accessing its dictionary of values/labels. Is this the best/only approach?

A: This is pretty much ok to import your choice mapping FILE_STATUS_CHOICES from models and use it to get Pending by P:
from my_app.models import FILE_STATUS_CHOICES

print dict(FILE_STATUS_CHOICES).get('P')

get_FIELD_display() method on your model is doing essentially the same thing:
def _get_FIELD_display(self, field):
    value = getattr(self, field.attname)
    return force_text(dict(field.flatchoices).get(value, value), strings_only=True)

And, since there is a flatchoices field on the model field, you can use it with the help of _meta and get_field_by_name() method:
choices = f._meta.get_field_by_name('name')[0].flatchoices
print dict(choices).get('P')

where f is your model instance.
Also see:

*

*Django get display name choices

A: I recommend using Choice from django-model-utils: https://django-model-utils.readthedocs.io/en/latest/utilities.html#choices.
I use it in every my models if I need choice field. See examples, it has excellent options.


text:
Q: How to make highlighting work in beamer with overlays I'm trying to use the soul package to get highlighting via \hl{some text}.  I'd like to do this in overlays in beamer.  I'm trying to follow the guidelines in section 9.6.1 of the beamer manual to make the \hl command overlay aware.  What i'm using is
\renewcommand<>{\hl}[1]{\only#2{\beameroriginal{\hl}}{#1}}
That setup sorta/kinda works, but not exactly.

*

*The \hl command is overlay-aware in xelatex, but not in pdflatex or lualatex.  I generally use lualatex, so that would be my preference. (Peter Grill has addressed this part in the first half of his answer)

*The overlays tend to reflow the text a bit, in a way that makes the highlighted text jump around from slide to slide in an awkward manner.  You'll see that if you run the example below through xelatex. (Actually, you'll see it in all the engines, but only with the highlights in xelatex). (Peter addressed this in the TikZ part of his answer)

I've attached an MWE of the problem, which I'm sure is some simple ignorance on my part, but I can't seem to resolve.
\documentclass[presentation]{beamer}

\usepackage{xcolor,soul}
\definecolor{lightblue}{rgb}{.90,.95,1}
\sethlcolor{lightblue}
\renewcommand<>{\hl}[1]{\only#2{\beameroriginal{\hl}}{#1}}

\begin{document}
\begin{frame} {Some possibly highlighted text}

This is some normal text

\hl<2>{I'd like this text to appear on both slides, but only be
  highlighted from the second slide}

\hl<3>{I'd like this text to appear on both slides, but only be
  highlighted from the second slide.  This is a long one, so it should
be more than one line}

This is some normal text
\end{frame}
\end{document}

A: Using soul package:
Looks like the problem is that beamer redefines things.  Using the patch from Why is it that coloring in soul in beamer is not visible seems to work:

Using tikz package:
As Andrew Stacey mentioned int he comments, there is a tikzmark solution as well. Using the code from How to "highlight" text/formulas with tikz?, we get:

Notes:

*

*Using this solution, the text is identical across the frames.

*This required a slight tweak from the code at How to "highlight" text/formulas with tikz?.  The highlighter width was increased form 12pt:
  highlighter width/.initial=14pt

Without this there was additional spacing in between the highlighted lines of the second paragraph.

*This does require two runs. First one to determine the locations, and the second to do the drawing.

*The \tikzmark is from Adding a large brace next to a body of text.
Further Enhancements:

*

*Another thing to look into would be adapting solutions from Cool Text Highlighting in LaTeX.

Code (soul):
\documentclass[presentation]{beamer}

\usepackage{xcolor,soul}
\definecolor{lightblue}{rgb}{.90,.95,1}
\sethlcolor{lightblue}
\renewcommand<>{\hl}[1]{\only#2{\beameroriginal{\hl}}{#1}}

% https://tex.stackexchange.com/questions/41683/why-is-it-that-coloring-in-soul-in-beamer-is-not-visible
\makeatletter
\newcommand\SoulColor{%
  \let\set@color\beamerorig@set@color
  \let\reset@color\beamerorig@reset@color}
\makeatother
\SoulColor

\begin{document}
\begin{frame} {Some possibly highlighted text}

This is some normal text

\hl<2>{I'd like this text to appear on both slides, but only be
  highlighted from the second slide}

\hl<3>{I'd like this text to appear on both slides, but only be
  highlighted from the second slide.  This is a long one, so it should
be more than one line}

This is some normal text
\end{frame}
\end{document}

Code (tikz):
\documentclass[presentation]{beamer}
\usepackage{xcolor}

%  https://tex.stackexchange.com/questions/46434/how-to-highlight-text-formals-with-tikz
\usepackage{tikz}
\makeatletter
%
% Highlighter code
%

\tikzset{%
  remember picture with id/.style={%
    remember picture,
    overlay,
    save picture id=#1,
  },
  save picture id/.code={%
    \edef\pgf@temp{#1}%
    \immediate\write\pgfutil@auxout{%
      \noexpand\savepointas{\pgf@temp}{\pgfpictureid}}%
  }
}

\def\savepointas#1#2{%
  \expandafter\gdef\csname save@pt@#1\endcsname{#2}%
}

\tikzdeclarecoordinatesystem{pic}{%
  \@ifundefined{save@pt@#1}{%
    \pgfpointorigin
  }{%
  \pgfsys@getposition{\csname save@pt@#1\endcsname}\save@orig@pic%
  \pgfsys@getposition{\pgfpictureid}\save@this@pic%
  \pgf@process{\pgfpointorigin\save@this@pic}%
  \pgf@xa=\pgf@x
  \pgf@ya=\pgf@y
  \pgf@process{\pgfpointorigin\save@orig@pic}%
  \advance\pgf@x by -\pgf@xa
  \advance\pgf@y by -\pgf@ya
  }%
}

\newcounter{highlight}
\newcommand{\hlstart}{\tikz[remember picture with id=hlstart\the\value{highlight},baseline=-0.7ex];\hl@start}
\newcommand{\hlend}{\tikz[remember picture with id=hlend\the\value{highlight},baseline=-0.7ex];\hl@end\stepcounter{highlight}}
\newcommand{\fdstart}{\tikz[remember picture with id=hlstart\the\value{highlight},baseline=-0.7ex];\fd@start}
\newcommand{\fdend}{\tikz[remember picture with id=hlend\the\value{highlight},baseline=-0.7ex];\fd@end\stepcounter{highlight}}
\newcommand{\vlstart}{\tikz[remember picture with id=hlstart\the\value{highlight},baseline=-1em];\vl@start}
\newcommand{\vlend}{\tikz[remember picture with id=hlend\the\value{highlight},baseline=0.3ex];\vl@end\stepcounter{highlight}}

\newcommand{\hl@start}[1][]{%
  \hl@draw{highlighter}{#1}{\the\value{highlight}}}

\newcommand{\hl@end}{}

\newcommand{\fd@start}[1][]{%
  \def\fd@args{#1}}

\newcommand{\fd@end}{\def\@tempa{\hl@draw{fader}}\expandafter\@tempa\expandafter{\fd@args}{\the\value{highlight}}\def\fd@args{}}

\newcommand{\vl@start}[1][]{%
  \vl@draw{highlighter}{#1}{\the\value{highlight}}}

\newcommand{\vl@end}{}

\def\hl@sets{%
  \edef\hl@sx{\the\pgf@x}%
  \edef\hl@sy{\the\pgf@y}%
}
\def\hl@sete{%
  \edef\hl@ex{\the\pgf@x}%
  \edef\hl@ey{\the\pgf@y}%
}

\@ifclassloaded{beamer}{

\def\page@node{
  \path (current page.south east)
      ++(-\beamer@rightmargin,\footheight)
  node[
    minimum width=\textwidth,
    minimum height=\textheight,
    anchor=south east
  ] (page) {};
}

}{

  \def\page@node{
    \path (current page.north west)
    ++(\hoffset + 1in + \oddsidemargin + \leftskip,\voffset + 1in + \topmargin + \headheight + \headsep)
    node[
      minimum width=\textwidth - \leftskip - \rightskip,
      minimum height=\textheight,
      anchor=north west
    ] (page) {};
  }

}

\newcommand{\hl@draw}[3]{%
  \begin{tikzpicture}[remember picture,overlay]%
  \page@node
  \tikzset{#2,highlight=#1,every path/.append style={highlight=#1}}%
  \pgfmathsetlengthmacro{\hl@width}{\the\pgflinewidth - 1pt}%
  \coordinate (hlstart) at (pic cs:hlstart#3);
  \coordinate (hlend) at (pic cs:hlend#3);
  \tikz@scan@one@point\hl@sets(pic cs:hlstart#3)
  \tikz@scan@one@point\hl@sete(pic cs:hlend#3)
  \ifdim\hl@sy=\hl@ey\relax
  \draw (hlstart) -- (hlend);
  \else
  \draw (hlstart) -- (hlstart -| page.east);
  \pgfmathsetlengthmacro{\hl@sy}{\hl@sy -\hl@width}%
  \pgfmathsetlengthmacro{\hl@ey}{\hl@ey +\hl@width}%
  \loop\ifdim\hl@sy>\hl@ey\relax
  \draw (0,\hl@sy -| page.west) -- (0,\hl@sy -| page.east);
  \pgfmathsetlengthmacro{\hl@sy}{\hl@sy -\hl@width}%
  \repeat
  \draw (hlend -| page.west) -- (hlend);
  \fi
  \end{tikzpicture}%
}

\newcommand{\vl@draw}[3]{%
  \begin{tikzpicture}[remember picture,overlay]%
  \page@node
  \tikzset{#2,highlight=#1,every path/.append style={highlight=#1}}%
  \pgfmathsetlengthmacro{\hl@width}{\the\pgflinewidth - 1pt}%
  \coordinate (hlstart) at (pic cs:hlstart#3);
  \coordinate (hlend) at (pic cs:hlend#3);
  \tikz@scan@one@point\hl@sets(pic cs:hlstart#3)
  \tikz@scan@one@point\hl@sete(pic cs:hlend#3)
  \ifdim\hl@sx=\hl@ex\relax
  \draw (hlstart) -- (hlend);
  \else
  \draw (hlstart) -- (hlstart |- page.south);
  \pgfmathsetlengthmacro{\hl@sx}{\hl@sx -\hl@width}%
  \pgfmathsetlengthmacro{\hl@ex}{\hl@ex +\hl@width}%
  \loop\ifdim\hl@sx>\hl@ex\relax
  \draw (\hl@sx,0 |- page.north) -- (\hl@sx,0 |- page.south);
  \pgfmathsetlengthmacro{\hl@sx}{\hl@sx -\hl@width}%
  \repeat
  \draw (hlend |- page.north) -- (hlend);
  \fi
  \end{tikzpicture}%
}

\tikzset{%
  highlight/.default=highlighter,
  highlight/.style={
    color=\pgfkeysvalueof{/tikz/#1 colour},
    line width=\pgfkeysvalueof{/tikz/#1 width},
    line cap=\pgfkeysvalueof{/tikz/#1 cap},
    opacity=\pgfkeysvalueof{/tikz/#1 opacity},
  },
  highlighter colour/.initial=yellow,
  highlighter width/.initial=14pt,% <-- Tweak (was 12pt)
  highlighter cap/.initial=butt,
  highlighter opacity/.initial=1,
  fader colour/.initial=gray,
  fader width/.initial=12pt,
  fader cap/.initial=butt,
  fader opacity/.initial=.5,
}

\@ifclassloaded{beamer}{

%% Beamer variants

\setbeamercolor{highlighted text}{bg=yellow}
\setbeamercolor{faded text}{fg=gray}

\newcommand<>{\highlight}[2][]{%
  \only#3{\hlstart[#1]}#2\only#3{\hlend}}

\newcommand<>{\fade}[2][]{%
  \only#3{\fdstart[#1]}#2\only#3{\fdend}}

\newcommand<>{\vhighlight}[2][]{%
  \only#3{\vlstart[#1]}#2\only#3{\vlend}}

}{

\newcommand{\highlight}[2][]{%
\hlstart[#1]#2\hlend}

\newcommand{\fade}[2][]{%
\fdstart[#1]#2\fdend}

\newcommand{\vhighlight}[2][]{%
\vlstart[#1]#2\vlend}

}

\begin{document}
\begin{frame} {Some possibly highlighted text}

This is some normal text

\highlight<2>{I'd like this text to appear on both slides, but only be
  highlighted from the second slide}

\highlight<3>{I'd like this text to appear on both slides, but only be
  highlighted from the second slide.  This is a long one, so it should
be more than one line}

This is some normal text
\end{frame}
\end{document}


text:
Q: 415, ReasonPhrase: 'Unsupported Media Type' All,
I am getting the following exception when I try call my web api (.net 6) end point using postman (I tried content type: form-data/application/x-www-form-urlencoded and I did include user, pwd parameters in the body, post url: http://localhost:5000/api/auth):
  {StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Date: Thu, 17 Mar 2022 18:12:40 GMT
  Server: Kestrel
  Transfer-Encoding: chunked
  Content-Type: application/problem+json; charset=utf-8
}}

Here's my web api controller:
[ApiController]
    [Route("/api/[controller]")]
    public class AuthController : ControllerBase
    {

        private readonly ILogger<AuthController> _logger;

        public AuthController(ILogger<AuthController> logger)
        {
            _logger = logger;
        }

        [HttpPost()]
        public string GetToken([FromBody] AuthCredentials cred)
        {
            _logger.LogInformation($"{nameof(AuthController)} => Received user: {cred.User}");
            _logger.LogInformation($"{nameof(AuthController)} => Received pwd: {cred.Pwd}");
            return "token:12345";
        }
    }

It worked before, when I was passing user/pwd as separate fields, the minute I put [FromBody] it stopped working and I started getting this exception.
public class AuthCredentials
    {
        public string User { get; set; }
        public string Pwd { get; set; }
    }

I do use SignalR + Webapis, here's my Startup.cs
public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(); // only for web api controllers

            services.AddSignalR()
                .AddHubOptions<ServerHub>(options =>
                {
                    options.EnableDetailedErrors = true;
                    options.MaximumReceiveMessageSize = null; // null is unlimited
                })
                // add message pack, requires nuget: Microsoft.AspNetCore.SignalR.Protocols.MessagePack (you must be on .net6 to use this nuget)
                .AddMessagePackProtocol();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Running SignalR hub, at url: /server");
                });

                endpoints.MapHub<ServerHub>("/server", options =>
                {
                    options.Transports = HttpTransportType.WebSockets;

                });

                endpoints.MapControllers(); // only for api controllers

            });
        }
    }

**

*

*UPDATE: Fixed the Unsupported Media Type

**
I was able to fix the Unsupported Media Type exception by changing this line and adding form data content-type:
services
                .AddControllers(options =>
                {
                    var jsonInputFormatter = options.InputFormatters
                        .OfType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>()
                        .Single();
                    jsonInputFormatter.SupportedMediaTypes
                        .Add("application/x-www-form-urlencoded");
                });

But now, when I run post man I get 400, bad request exception:
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-46970e65eec389a5d6d355d960823e57-dd8db1776ac7f90c-00",
    "errors": {
        "$": [
            "The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."
        ]
    }
}

Q:
How can I pass in using form Data (user, pwd), and populate AuthCredentials object on the server?

A: if you trying to call this action from postman
 [HttpPost()]
public string GetToken([FromBody] AuthCredentials cred)

 _logger.LogInformation($"{nameof(AuthController)} => Received user: {cred.User}");
 _logger.LogInformation($"{nameof(AuthController)} => Received pwd: {cred.Pwd}");
 return "token:12345";
}

you need to select body=>raw=>json options in postmant and add your data as
{
  "user": "user",
  "pwd" : "pwd"
}

and  remove all extra code you added to AddController config. It is only confusing and probably will cause more problems in the future

A: The reason why it's doesn't work, is that you are trying to retrieve parameter from the URL, but you are using [FromBody] which is supposed to use the body of your request to send parameters .
Try to send your parameters as shown below


text:
Q: C# SqlDataAdapter DateTime Format datatable invalid json \Date() [Solved] So it was a stupid issue and i figured it by tracking the variable changes throughout the call stack and fixed it as follows:
(Reason and solution mentioned in step 5)
ref: https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
1- Database column:

2- Database stored procedure:

3- C# call that stored procedure:

4- C# parse the date (it is returned as a string )

5- Casting that string to datetime (My issue started here, I should not convert the datetime-string back to a datetime object when i need to pass it to a Json() to use it for DataTable plugin for example. Only Razor can handle DateTime objects ..., So the solution was to just skip this step, if you are using a model-model or a view-model, you need to include a string property to store the string version of the datetime or just use another currently-not-in-use property, I used IBAN property to store the datetime-string-version instated of creating a new model or modifying the domain model i was using):

Thanks

A: On server side,
convert(datetime, 'Dec 30 2006 12:38AM', 109)

On client side,
DateTime.ParseExact("Dec 30 2006 12:38AM", "MMM dd yyyy h:mmtt", System.Globalization.CultureInfo.InvariantCulture)

A: Why don't you use DateTime.Parse()?
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var dateString = "Dec 30 2006 12:38AM";
            var date = DateTime.Parse(dateString);
            Console.WriteLine(date);
            // results is 30/12/2006 00:38:00 (according to my DateTime format settings)
            Console.ReadLine();
        }
    }
}


text:
Q: Could not load file or assembly The system cannot find the file specified I am building a dll, which references a second dll.  I have added the second dll as a reference in the first dll's project by going to Properties > Common Properties > Framework and References > Add New Reference > Browse
I compiled the second dll from a third party's source code.  Both projects are C++/CLI.
Whenever my main application tries to call a function in the first dll which contains a call to the second dll, I get the following error:

An unhandled exception of type 'System.IO.FileNotFoundException'
  occurred in Unknown Module.
Additional information: Could not load file or assembly 'NBIS,
  Version=1.0.5156.29834, Culture=neutral, PublicKeyToken=null' or one
  of its dependencies. The system cannot find the file specified.

I have a copy of the second dll in the same directory as my main exe, and I've even tried keeping a copy next to the first dll as well, to no avail.
The second dll references several static libraries, but the only Assembly References it contains are

System
System.Data
System.Drawing
System.XML

All of which I have added as assembly references in the first dll.
What can I do to get my application to find and load the second dll?

A: Right click on the project you created the dll and the new referencing project, then select properties.
Under Application, check the target framework and verify that both have the same framework, some dll projects tend to select 'client profile' version of the framework by default, which tend to give the error you are having now..
Let me know if this is not the issue..

A: As pointed out in the comments, SysInternals' Process Monitor is a valuable tool to diagnose DLL resolution problems.  Tells you when a 3rd party DLL has a dependency you don't know about, also tells you when Windows is looking in the wrong corner of your hard drive for the file or finds the wrong one.
Loader snaps is the built-in diagnostic tool for Windows.  But Process Monitor is far more convenient.
It does generate rather a lot of information, start from the bottom of the trace or enable tracing at just the right time.  You often need to use its filtering tools to turn the firehose in a relevant trickle.  Worth the hour of your time to figure it out, this tool belongs on any programmer's black belt.

A: My PowerShell ISE wasn't running as an Administrator. This seemed to be the problem for me.

A: Please Change your application pool setting.
Keep the steps:

*

*IIS manager open

*Click 'Application pools' (Application pools list)

*Select your application pool

*Right click your application pool and select 'Advanced settings '

*Change 'Enable 32-bit application' from false to true. (When you create application pool Enable 32-bit application default assign false)

A: For the alert error ("The system cannot find the file specified.")

*

*Right click on [Solution Program name] then select Build Dependencies> & left click on Build Customizations... then true-checkbox {MASM} then click OK button.

*Right click on [Solution Program name] then left click on Properties, left click on "Linker" form "Linker" choose "Debugging" left click on "Debugging" from "Debugging" choose "Debugging Assembly" & convert the value of  "Debugging Assembly" to "Yes (/ASSEMBLYDEBUG)", form "Linker" choose "System" left click on "System" from "System" choose "SubSystem" & convert the value of  "SubSystem" to "Windows (/SUBSYSTEM:WINDOWS)",, left click on OK button.

*Right click on [Solution Program name] then Add> new item, "C++ File(.cpp)" change the name or rename "new item" to "Main.asm" then left click on Add button, Right click on [Main.asm] then left click on Properties select "General" from "General" choose "Item Type" and convert the value of  "Item Type" to "Microsoft Macro Assembler" press left click on OK button, then then then Write your assembly code in "Main.asm" file then [[[Debug]]] it using 'step over === F10' from "Debug" tool-bar on top-screen program, all this about how to using assembly code in "Visual Studio 2017".


text:
Q: Create right floating image in PhpWord I want an image on the right, text on the left floating around the image. The other way round works pretty good, there also is an example for that on the Recipies section in the documentation. However, I did not get this working with images floating on the right. What I tried:
addImage('myimage.png',
   array(
       'width'=>320,
       'height'=>240,
       'align'=>'right',
       'wrappingStyle'=>'square',
       'positioning' => 'absolute'
   )
);

or
addImage('myimage.png',
   array(
       'width'=>320,
       'height'=>240,
       'align'=>'right',
       'wrappingStyle'=>'square',
       'positioning' => 'absolute',
       'posHorizontalRel' => 'margin',
       'posVerticalRel' => 'line'
   )
);

I also experimented with negative image widths etc., but that did not work neither. Unfortunately, documentation on the whole project is really poor, at least at phpword.readthedocs.org.

A: I had the same problem too, and there's no answer on the internet to this date. So here's what I came up with:
$section->addImage('image.png', array(
    'width' => 40,
    'height' => 40,
    'wrappingStyle' => 'square',
    'positioning' => 'absolute',
    'posHorizontal'    => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_RIGHT,
    'posHorizontalRel' => 'margin',
    'posVerticalRel' => 'line',
));


text:
Q: Use IScroll in Angular 2 / Typescript i want to use a Javascript Libary called iscroll.
So far i got the iscroll.d.ts and now i want to use it, but iam new at typescript and dont know how to do that.
My iscroll.d.ts looks like this:
// Generated by typings
// Source: https://raw.githubusercontent.com/types/typed-iscroll/8524f7c88e521c16462553173c9ea99e9e3d477c/iscroll.d.ts
declare module 'iscroll' {
class IScroll {
  version: string;

  constructor(element: string | HTMLElement, options?: IScroll.IScrollOptions);

  destroy(): void;
  resetPosition(time: number): boolean;
  disable(): void;
  enable(): void;
  refresh(): void;
  scrollTo(x: number, y: number, time?: number, easing?: IScroll.IScrollEaseOption): void;
  scrollBy(x: number, y: number, time?: number, easing?: IScroll.IScrollEaseOption): void;
  scrollToElement(el: HTMLElement | string, time?: number, offsetX?: number, offsetY?: number, easing?: IScroll.IScrollEaseOption): void;
  goToPage(x: number, y: number, time?: number, easing?: IScroll.IScrollEaseOption): void;
  prev(): void;
  next(): void;
  zoom(scale: number, x: number, y: number, time?: number): void;
  refresh(): void;
  destroy(): void;

  utils: IScroll.IScrollUtils;

  // Events
  on(type: 'beforeScrollStart' |
    'scrollCancel' |
    'scrollStart' |
    'scrollEnd' |
    'flick' |
    'zoomStart' |
    'zoomEnd', fn: (evt?: any) => void): void;
  off(type: string, fn?: (evt?: any) => void): void;

}

namespace IScroll {
  export interface IScrollIndicatorOptions {
    el?: HTMLElement | string;
    fade?: boolean;
    ignoreBoundaries?: boolean;
    interactive?: boolean;
    listenX?: boolean;
    listenY?: boolean;
    resize?: boolean;
    shrink?: boolean;
    speedRatioX?: number;
    speedRatioY?: number;
  }

  export interface IScrollKeyBindings {
    pageUp?: number | string,
    pageDown: number | string;
    end: number | string;
    home: number | string;
    left: number | string;
    up: number | string;
    right: number | string;
    down: number | string;
  }

  export interface IScrollOptions {

    indicators?: IScrollIndicatorOptions;

    // Scrollbar
    scrollbars?: boolean | string;
    fadeScrollbars?: boolean;
    interactiveScrollbars?: boolean;
    resizeScrollbars?: boolean;
    shrinkScrollbars?: boolean;

    // Zoom
    zoom?: boolean;
    zoomMin?: number;
    zoomMax?: number;
    startZoom?: number;
    wheelAction?: string;

    snap?: boolean | string;

    bindToWrapper?: boolean;
    bounceEasing?: string | IScrollEaseOption;
    bounceTime?: number;
    deceleration?: number;
    mouseWheelSpeed?: number;
    preventDefaultException?: any;
    resizePolling?: number;
    probeType?: number;
    keyBindings?: boolean | IScrollKeyBindings;

    useTransform?: boolean;
    useTransition?: boolean;
    HWCompositing?: boolean;
    bounce?: boolean;
    click?: boolean;
    disableMouse?: boolean;
    disablePointer?: boolean;
    disableTouch?: boolean;
    eventPassthrough?: boolean;
    freeScroll?: boolean;
    invertWheelDirection?: boolean;
    momentum?: boolean;
    mouseWheel?: boolean;
    preventDefault?: boolean;
    tap?: boolean | string;

    scrollX?: number;
    scrollY?: number;
    startX?: number;
    startY?: number;

    // Infinite options
    infiniteElements: HTMLElement | 'string';
    cacheSize: number;
    dataset: (start: number, count: number) => Object[];
  }

  export interface IScrollEaseOption {
    style: 'string';
    fn: Function;
  }
  export interface IScrollEaseOptions {
    quadratic: IScrollEaseOption;
    circular: IScrollEaseOption;
    back: IScrollEaseOption;
    bounce: IScrollEaseOption;
    elastic: IScrollEaseOption;
  }

  export interface IScrollUtils {
    ease: IScrollEaseOptions;
  }
}

export = IScroll;
}

And my Angular 2 page.ts looks like this:
import {NavController} from "ionic-angular";
import {AngularFire, AuthProviders, AuthMethods } from "angularfire2";
import {OnInit, Inject, Component} from "@angular/core";
import {UserService} from '../../../services/UserService';
import {AuthPage} from "../home/home";
import { IScroll } from "iscroll"

@Component({
    templateUrl: "build/pages/auth/onboarding/onboarding.html",
    providers: [UserService]
})

export class OnboardingPage {

    iScroll: IScroll;

    onboardingStep: number = 1;

The Import works fine so far, i think but i dont know how to init and use iscroll.
Hope some of you got any tips how to bring that to life :)

A: You use it just like you'd use it in plain old javascript, with the difference that you can also include types.
For example, javascript:
let myScroll = new IScroll("#CONTAINER_ID");

typescript:
let myScroll: IScroll = new IScroll("#CONTAINER_ID");

(notice that the : IScroll isn't needed, the compiler can infer the type, but I added it to make a point)
In your case:
export class OnboardingPage {
    iScroll: IScroll;

    constructor() {
        this.iScroll = new IScroll("#CONTAINER_ID");
    }
}

This code is based on their documentation (https://github.com/cubiq/iscroll) but according to the .d.ts file you posted it requires to use the iscroll namespace:
let myScroll = new iscroll.IScroll("#CONTAINER_ID");

Hope this helps.


text:
Q: How can I reset a state without declare a initialState? I have a state and I wan't to reset this state without necessity of create the same state twice
initialState: {
        id: '',
        name: '',
        index: ''
      },
state: {
        id: '',
        name: '',
        index: ''
      }

When I want to reset the state I do that
resetForm () {
      this.state = this.initialState
    }

How can I do that without a initialState declaration

A: define an initialState object and then spread over it:
const initialState = {
  id: '',
  name: '',
  index: ''
}
...

state: {
  ...initialState
}

...

resetForm() {
  this.state = { ...initialState }
}


text:
Q: Rendering point symbols on top of diagrams? I've got some data where I have categorized symbology for point data with different colors showing different categories. I would also like to display some data using the pie charts function. I would like to have the different colored point on top of the pie charts to get a symbol that looks something like the mock-up below.

I can't find a way to get the points on top of the charts. Any suggestion?

A: Another approach would be recurring to symbology only: the main advantage is that the result will be customizable with practically infinite combinations of parameters.
The following procedure will use a custom function and it will work independently from the number of categories you will use.
Assuming you are working on a projected CRS (instead, if you are using a Geographic Coordinate System, see the note at the end of the answer), I want to underline that I will focus the attention on the explanation of the minimal things to do for reproducing the desired result: this means that some other minor parameters (like sizes, widths and so on) should be easily adjusted by you for better fitting your needs.
You will discover that reading the following solution will require more time than applying it directly (since the custom function will automatically do the most of the job).

Context
Let assume to start from this point vector layer:

which stores several categories that we want to display:

Solution
Assuming we want to categorize the "cat_1", "cat_2" and "cat_3" fields,
we will render the point at the center (the yellow point in your original question) with one Geometry generator symbol layer. Then, we will render the several categories using a number of Geometry generator symbol layers which is equal to the number of categories themselves. So, for this case, we will use three Geometry generator symbol layers:

In the further explanation, the colors of the squares in the above image will help you to understand which geometry we are creating.
1) Geometry Generator No. 1
Add a new symbol layer and select the Geometry generator and the Polygon / MultiPolygon types:

Insert this expression in the Expression field:
buffer($geometry,10)

We have just defined a circle which has a radius of 10 meters.
2) Geometry Generator No. 2
From the Style dialog, add a new Geometry generator symbol layer having Polygon / MultiPolygon as geometry type. Then click on the Function Editor tab:

Then, click on New file and type piechart as the name of the new function:

You will see that a new function has been created and it is listed on the left side of the dialog. Now, click on the name of the function and replace the default @qgsfunction with the following code (don't delete the libraries imported by default and remember to add the import math line):
from qgis.core import *
from qgis.gui import *
import math

@qgsfunction(args=-1, group='Custom')
def piechart(in_list, feature, parent):
    to_show =in_list[-1] - 1
    fields =in_list[:-2]
    len_fields = len(in_list)
    sum_val = sum([feature[k] for k in fields])
    geom = feature.geometry()
    radius = in_list[-2]
    buffered = geom.buffer(radius, -1)
    first = True
    slices = []
    for field in fields:
        point_1 = geom.asPoint()
        points = [point_1]
        perim = buffered.length()
        percent = float(feature[field])/(sum_val)
        l = percent * perim
        azimuth = l/radius
        if first:
            start = 0
            end = azimuth
            first = False
        else:
            start = end
            end += azimuth
        if abs(math.degrees(start - end)) <= 180:
            dist_x, dist_y = (2 * radius * math.cos(math.radians(90) - start), 2 *radius* math.sin(math.radians(90) - start))
            point_2 = QgsPoint(point_1[0] + dist_x, point_1[1] + dist_y)
            dist_x, dist_y = (2 * radius * math.cos(math.radians(90) - (start + end)/2), 2 *radius* math.sin(math.radians(90) - (start + end)/2))
            point_3 = QgsPoint(point_1[0] + dist_x, point_1[1] + dist_y)
            dist_x, dist_y = (2 * radius * math.cos(math.radians(90) - end), 2 *radius* math.sin(math.radians(90) - end))
            point_4 = QgsPoint(point_1[0] + dist_x, point_1[1] + dist_y)
        else:
            dist_x, dist_y = (2 * radius * math.cos(math.radians(90) - start), 2 *radius* math.sin(math.radians(90) - start))
            point_2 = QgsPoint(point_1[0] + dist_x, point_1[1] + dist_y)
            dist_x, dist_y = (2 * radius * math.cos(math.radians(90) - (start + end)/2), 2 *radius* math.sin(math.radians(90) - (start + end)/2))
            point_3 = QgsPoint(point_1[0] - dist_x, point_1[1] - dist_y)
            dist_x, dist_y = (2 * radius * math.cos(math.radians(90) - end), 2 *radius* math.sin(math.radians(90) - end))
            point_4 = QgsPoint(point_1[0] + dist_x, point_1[1] + dist_y)
        points.append(point_2)
        points.append(point_3)
        points.append(point_4)
        trGeom = QgsGeometry().fromPolygon([points])
        if  math.degrees(azimuth) <= 180:
            if start >= end:
                slice = buffered.difference(trGeom)
            else:
                slice = buffered.intersection(trGeom)
        else:
            if start >= end:
                slice = buffered.intersection(trGeom)
            else:
                slice = buffered.difference(trGeom)
        slices.append(slice)
    return slices[to_show]

Once you have done this, click on the Load button and you will be able to see the function from the Custom Menu of the Expression dialog.
Now, type this expression (see the image below as reference):
piechart('cat_1', 'cat_2', 'cat_3', 20, 1)

We have just defined the first sector of the pie chart by entering the names of the fields to categorize ('cat_1', 'cat_2', 'cat_3'), the radius of the pie chart (20) and a number which indicates the category (starting from 1) to display: for this case, we will render the first category from the list, so we need to set 1 as value. As you will see in the following steps, this number will be the unique value to change.
3) Geometry Generator No. 3
From the Style dialog, add a new Geometry generator symbol layer having Polygon / MultiPolygon as geometry type. Then click on the Function Editor tab:

Then, type this expression in the Expression field:
piechart('cat_1', 'cat_2', 'cat_3', 20, 2)

We have just defined the second sector of the pie chart. The unique difference with the previous step is that we set 2 as the last parameter: this because we want to render the second category field (i.e. "cat_2").
4) Geometry Generator No. 4
From the Style dialog, add a new Geometry generator symbol layer having Polygon / MultiPolygon as geometry type. Then click on the Function Editor tab:

Then, type this expression in the Expression field:
piechart('cat_1', 'cat_2', 'cat_3', 20, 3)

We have just defined the third sector of the pie chart. The unique difference with the previous step is that we set 3 as the last parameter: this because we want to render the third category field (i.e. "cat_3").
Final result
Click on the Apply button for applying the renderer: we have finished. If you correctly performed the previous tasks, you should be able to get something like this:

Final notes
If you are using a Geographic Coordinate System, i.e. if you are dealing with degrees and not with distances, it should be enough using the proper value for the fourth parameter of the piechart function: this means that you need to replace it with other arbitrary values expressed in degrees (for example, 0.0002, 0.002 and so on).
Please note that my example will work fon any number of fields to categorize, assuming that you will create the proper number of geometry generators and set the correct values for the fourth parameter in the piechart function.

A: I think this is a bug. I have the same issue, and I tested on both QGIS 2.14.10 and QGIS 2.18.2, and there is no way show the point simple style above the graphs, although the point shapefile is located above the graph, as you can see below:

Here is the point shapefile without the graphs:

The only I can show the point is by setting the layer transparency for the pie chart appearance:

You can report this bug here.


text:
Q: Get a substring after a certain word The string looks as follows:
Event Id: 971
Time    : Fri Mar 28 03:50:03 2014
Type    : INFO
User    : ehwe
Message :
        Oracle_Connector_1,0: Number of rows fetched on the current node: 0.

I need to get the sub string that follows the Message :. So I in this case I need this
Oracle_Connector_1,0: Number of rows fetched on the current node: 0.
I've tried using  b=${a%'Message :'*} format but that didn't help.
Little help, please?
Update:
Some log entries might look like the next one:
Event Id: 970
Time    : Fri Mar 28 03:50:03 2014
Type    : FATAL
User    : ehwe
Message :
    Oracle_Connector_1,0: [IIS-CONN-ORA-001003] The OCI function OCIStmtExecute returned status -1. Error code: 6,550, Error message: ORA-06550: line 2, column 14:
    PLS-00201: identifier 'IT' must be declared
    ORA-06550: line 2, column 14:
    PL/SQL: Item ignored
    ORA-06550: line 5, column 5:
    PLS-00320: the declaration of the type of this expression is incomplete or malformed
    ORA-06550: line 5, column 5:
    PL/SQL: Statement ignored
    ORA-06550: line 8, column 26:
    PLS-00320: the declaration of the type of this expression is incomplete or malformed
    ORA-06550: line 8, column 7:
    PL/SQL: Statement ignored. (CC_OraStatement::executePlSql, file CC_OraStatement.cpp, line 2,746)

A: You can use this:
awk 'f; /Message/ {f=1}' file

*

*If the flag f is set, condition is true so awk prints the line.

*Whenever the text Message appears, the flag f is set to 1.

Update
If you want to print exactly the line after Message occurs, you can do:
$ awk 'f {print; exit} /Message/ {f=1}' file
    Oracle_Connector_1,0: [IIS-CONN-ORA-001003] The OCI function OCIStmtExecute returned status -1. Error code: 6,550, Error message: ORA-06550: line 2, column 14:

It is the same as above, just that after printing for the first time, it stops reading the file and exits.
To use a variable as input instead of a file, use:
awk 'f {print; exit} /Message/ {f=1}' <<< "$var"

See an example:
$ echo "$var"
hello
how are you

$ awk '1' <<< "$var"
hello
how are you

A: grep -A1 Message | tail -1 should do the trick. -A1 tells grep the write one more line to the output (after 1) when a match is found.

A: I expect ${a%'Message :'*} to return the first four lines.  If $a contains the entire message above, reverse the match:
a="Event Id: 971
Time    : Fri Mar 28 03:50:03 2014
Type    : INFO
User    : ehwe
Message :
        Oracle_Connector_1,0: Number of rows fetched on the current node: 0."

echo "${a#*Message :[$IFS]}"

Outputs:
        Oracle_Connector_1,0: Number of rows fetched on the current node: 0.

Note:
Using [$IFS] because I'm too lazy to figure out an explicit match with the newline character.  That can be improved.
Tested in bash and ksh93


text:
Q: Form a sequence of values from strings I need to iterate through each element in a matrix like structure. For example,
SeatingType Model Back  Mech
1              6   120   58
               7   121   59
               8

In java values will be coming as parameters as string in comma seperated values  Eg SeatingTpe (1), Model (6,7,8) etc.
I need to get the result as
1,6,120,58
1,6,120,59
1,6,121,58
1,6,121,59
1,7,120,58
1,7,120,59
1,7,121,58
1,7,121,59
1,8,120,58
1,8,120,59
1,8,121,58
1,8,121,59

Please note that Model, Back and Mech could be null.So in case Model values is null, then output should be 1,6,58 and 1,6,59 so on. Any help plz
As a headstart, I tried by looping through from last element (in this case 'Mech')> But that is very tedious. Any other approach ? I have provided only 4 atributes over here. But the reqmnt is for 11 attributes. I was hoping if I could get solution for 4 atributes, that could be applied for rest 7

A: Iterate through 4 loops:
List<String> seatTypeValues = ...
List<String> modelValues = ...
List<String> backValues = ...
List<String> mechValues = ...

if (seatTypeValues.isEmpty()) { seatTypeValues.add(null); }
... // all 4 lists

for(String seatType : seatTypeValues) {
  for(String model : modelValues) {
    for(String back : backValues) {
      for(String mech : mechValues) {
        // print the CSV
        if (seatType != null) {
          writer.write(seatType);
        }
        if (model != null) {
          writer.write(',');
          writer.write(model);
        }
        if (back != null) {
          writer.write(',');
          writer.write(back);
        }
        if (mech != null) {
          writer.write(',');
          writer.write(mech);
        }
        writer.write("\r\n");
      }
    }
  }
}


text:
Q: Почему не работает background-image? Проект написан на ларавель resources/views/welcome.blade.php:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="bootstrap-3/css/bootstrap.css" rel="stylesheet" type="text/css"/>
    <link href="bootstrap-3/css/header_style.css" rel="stylesheet" type="text/css"/>

gggg

Файл bootstrap-3/css/header_style.css:
.ggg {
background-image: url("images/earth.png");   // пробовал еще и так  url(images/earth.png)  url('images/earth.png')
height: 200px;
}

Картинка earth.png из свойства background-image не срабатывает... в то время, как от тега img она работает...В чем может быть причина?
П.С.: файл header_style.css подключен верно и работает (решил не засорять код примерами его работы)

A: images/earth.png - это относительный путь.
То есть если у тебя css файл лежит скажем в
www/bootstrap-3/css/header_style.css

а картинка
www/images/earth.png

то для подклчения в css нужен путь ../../images/earth.png (2 каталога вверх по иерархии - до корня сайта)
Либо используй абсолютный путь вида /images/earth.png

A: Действительно, попробуйте полный путь. Ведь  фоновый рисунок запрашивается после загрузки сайта. Если у Вас есть редирректы или ЧПУ, то запрос рисунка фона будет URL+image/earth.png. Проверьте, нет ли тут конфликта...

A:  или - как в CSS - image/earth.png - есть небольшая разница в названиях директорий: images и image.
По всей видимости, причина в этом. (ответ на первую версию вопроса).
Ответ на вторую версию вопроса: (в любом случае где-то указан неверный путь к картинке из CSS файла).
Если прописать полный путь к картинке в CSS (с http://) - должно работать. Где-то путь неверный, в этом все дело.
Обычно для устранения проблемы достаточно посмотреть через Инспектор кода, какой адрес отдается для картинки из CSS, и понять, где затык.

A: Советую открыть консоль разработчика в Chrome F12, открыть вкладку network и посмотреть URL по которому подгружается изображение и найти проблему.
Что касается пути, попробуйте такой вариант /images/earth.png

A: CSS хранится в своей папке, и при обращении к картинке он пытается в своей папке найти папку images и в ней уже картинку.
Попробуйте поиграть с путем файла посредством ("../") в начале пути. Это поднимает ссылку по каталогам на один уровень вверх.

background-image: url("../images/earth.png");