text:
Q: Pyqtgraph - how add axis Datetime? The example uses the file 'QtChart.ui' (this is important) the widget for Pyqtgraph is embedded in it (this is also important).
PROBLEM:
The graph is displayed, but the seconds since the beginning of the epoch are displayed instead of the date-time axis.
I set the variable axis = pg.DateAxisItem(orientation='bottom')
Following the example, it should be added to such a line pw = pg.PlotWidget(viewBox=vb, axisItems={'bottom': axis}), but I do not have such a line in my code.
How to set the date-time axis instead of seconds from the beginning of the epoch?
CODE:
import random
import sys
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import QMainWindow
import time
import pyqtgraph as pg

x = []
y = []

class draw_interface(QMainWindow):
    def __init__(self):
        super(draw_interface, self).__init__()
        uic.loadUi('QtChart.ui', self)

        self.timer_update_events = QTimer()
        self.timer_update_events.timeout.connect(self.update_chart)
        self.timer_update_events.start(1000)

        axis = pg.DateAxisItem(orientation='bottom')

        self.line = pg.PlotCurveItem(clear=True, pen="g")
        self.widget.addItem(self.line)

        self.show()

    def update_chart(self):
        global x, y

        x.append(time.time())
        y.append(random.uniform(0, 1))
        self.line.setData(x, y)

my_app = QtWidgets.QApplication([])
my_main_window = draw_interface()
sys.exit(my_app.exec_())

AND CODE 'QtChart.ui':
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1319</width>
    <height>1091</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QHBoxLayout" name="horizontalLayout">
    <item>
     <layout class="QGridLayout" name="gridLayout">
      <property name="leftMargin">
       <number>10</number>
      </property>
      <property name="topMargin">
       <number>10</number>
      </property>
      <property name="rightMargin">
       <number>10</number>
      </property>
      <property name="bottomMargin">
       <number>10</number>
      </property>
      <item row="0" column="0">
       <widget class="QFrame" name="frame_2">
        <property name="sizePolicy">
         <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
          <horstretch>0</horstretch>
          <verstretch>0</verstretch>
         </sizepolicy>
        </property>
        <property name="maximumSize">
         <size>
          <width>200</width>
          <height>16777215</height>
         </size>
        </property>
        <property name="frameShape">
         <enum>QFrame::StyledPanel</enum>
        </property>
        <property name="frameShadow">
         <enum>QFrame::Raised</enum>
        </property>
       </widget>
      </item>
      <item row="0" column="1">
       <widget class="PlotWidget" name="widget" native="true"/>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>1319</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <customwidgets>
  <customwidget>
   <class>PlotWidget</class>
   <extends>QWidget</extends>
   <header location="global">pyqtgraph</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>

A: You have to use the setAxisItems() method:
# ...
axis = pg.DateAxisItem(orientation='bottom')
self.line = pg.PlotCurveItem(clear=True, pen="g")
self.widget.addItem(self.line)
self.widget.setAxisItems({"bottom": axis})
# ...


text:
Q: Отправка post запроса Помогите отправить post запрос на c#, ниже скрин снифера с запросом.!

A: Реализация POST-запроса через RestSharp.
public void DoPOSTRequest(CookieContainer cookies, string subUrl)
        {
            RestClient client = new RestClient("// адрес хоста //")
            {
                UserAgent = @"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1",
                FollowRedirects = true,
                CookieContainer = cookies
            };

            RestRequest request = new RestRequest("// подадрес //", Method.POST);

            Parameter param = new Parameter // создаем параметр
            {
                Type = ParameterType.GetOrPost, // тип параметра
                Name = name, //имя параметра
                Value = value //значение параметра
            };

            request.AddParameter(param); //добавлени параметра в запрос

            IRestResponse response = client.Execute(request); // отправка запроса
        }

A: Посмотрите эту ссылу. Кстаи первая в поиске гугла.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails Generates Blank Record Even Input Data I am learning to use CRUD, and setup a page to add a record, however it only generated blank record? Can you take a look my code?
thanks!
here is the Page controller:
class PagesController < ApplicationController
   def index
    @test = Page.all
  end

  def new
    @test = Page.new
  end

  def create
    @test = Page.new(params.permit(:subject_id,:name,:position,:visible,:permalink))
    if @test.save
      flash[:notice] = "Page created successfully!"
      redirect_to(:action => 'index')
    else
      render('new')
    end
  end

end

here is the new.html.erb
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>

Create Subject

  <%= form_for(:Page, :url => {:action => 'create'}) do |f| %>

        Subject_ID
        <%= f.text_field(:subject_id) %>

        Name
        <%= f.text_field(:name) %>

        Position
        <%= f.text_field(:position) %>

        Visible
        <%= f.text_field(:visible) %>

        Permalink
        <%= f.text_field(:permalink) %>

      <%= submit_tag("Create Subject") %>

  <% end %>

Here is index.html.erb

Pages

 # <%= link_to("Add New Page", {:action => 'new'}, :class => 'action new') %>

      Position
      Page Name
      Visible
      Pages
      Actions

    <% @test.each do |f| %>

      <%= f.position %>
      <%= f.name %>
      <%= f.visible %>
      <%= f.permalink %>

        <%= link_to("Show", {:action => 'show', :id => f.id}, :class => 'action show') %>
        <%= link_to("Edit", {:action => 'edit', :id => f.id}, :class => 'action edit') %>
        <%= link_to("Delete", {:action => 'delete', :id => f.id}, :class => 'action delete') %>

    <% end %>

Thanks so much!

A: Strong parameters
Rails sends form parameters in nested hashes.
{ page: { subject_id: 1, name: 'Hello World.' } }

So to whitelist the parameters you would do.
class PagesController < ApplicationController
   def index
    @test = Page.all
  end

  def new
    @test = Page.new
  end

  def create
    @test = Page.new(page_params)
    if @test.save
      flash[:notice] = "Page created successfully!"
      redirect_to(:action => 'index')
    else
      render('new')
    end
  end

  private

  def page_parameters
    params.require(:page)
          .permit(:subject_id,:name,:position,:visible,:permalink)
  end
end

which is like doing:
params[:page].slice(:subject_id,:name,:position,:visible,:permalink)

form_for and models
Also your form should read:
 <%= form_for(:page, :url => {:action => 'create'}) do |f| %>

Or:
 <%= form_for(@page, :url => {:action => 'create'}) do |f| %>

:Page will give you the wrong key in your parameters and prevent rails from binding the form to your @page object. (The values posted will disappear from the form when it's invalid).


text:
Q: Use Select and Select many Together in Linq I am trying to get the company id in the following query.
List<int> companyIds=new List<int> {4, 5, 6, 7};
   var result = reservationRepository.Where(r => companyIds.Contains(r.CompanyId))
                .SelectMany(t =>  t.Transactions)
                .Where(x => x.DateCreated >= options.PaymentFromDate)
                .Where(x => x.DateCreated < endDate)
                .Select(x => new
                {
                    Method = x.Method,
                    Amount = x.Amount,
                    VatAmount = x.VatAmount
                });

Since I am using select many I am not able to get companyId. Please suggest a way to return company id also along with the result.
The reservation table contains CompanyId. Transaction doesnot contain Company Id
public class Reservation{
  public int CompanyId { get; set; }
  public virtual ICollection<Transaction> Transactions { get; set; }
}

public class Transaction{
  public string Method{ get; set; }
  public decimal Amount{ get; set; }
  public decimal VatAmount{ get; set; }

}

I have to start the query with the Reservation table because I am getting the corresponding transactions from it. I can't change the model.  Is there any way we can get both transaction details and CompanyID through the query?

A: You didn't post the code for GetAll() or the Reservation and Transaction classes, so one can only guess.
SelectMany returns Transaction objects only. The next calls only see Transaction objects, not Reservation. If Transaction has a Reservation property, one could use x.Reservation.CompanyId to return that value, eg :
.Select(x => new
{
    CompanyID = x.Transaction.CompanyId,
    Method = x.Method,
    Amount = x.Amount,
    VatAmount = x.VatAmount
});

In that case though, you shouldn't even start querying from Reservation. It would be better to query Transactions, eg :
var transactions = db.Transactions
                     .Where(x=>companyIds.Contains(x.Reservation.CompanyId) &&
                               x.DateCreated >= options.PaymentFromDate &&
                                x.DateCreated < endDate)
                     .Select(x => new
                     {
                         CompanyId = x.Reservation.Id
                         Method = x.Method,
                         Amount = x.Amount,
                         VatAmount = x.VatAmount
                     });

Missing Reservation property
Add it. The data model is meant to facilitate the queries, and you obviously need that relation.
The relational model doesn't specify any kind of graph or hierarchy, that's its main benefit over other data models. Since you want Transactions, you should query transations. In SQL you'd only need to add a JOIN or WHERE IN clause to filter by Transaction and CompanyID.
The Repository antipattern
This exposes the next, far more serious problem. It looks like you're using the "generic" Repository antipattern - a low-level Repository interface imposed over a higher-level ORM like EF Core. The problems with this are well known, check eg No need for repositories and unit of work with Entity Framework Core or Repository is the new Singleton from 2009.
A DbSet is already a repository. A DbContext already implements Unit-of-Work and disconnected operations, combining multiple entity repositories.
There's no need for anemic repositories to hide data access details, that's what the ORM is for. What would make sense is a specialized, multi-entity repository serving a specific use case, hiding the details of combining entities, validation checks, adding methods that implement common queries, for all the entities involved.
That specialized repository could have a GetTransactionsByCompany(int) method for example, that would encapsulate the entire query and really hiding the details.
Using an anemic repository for Reservations makes changing the query harder, without offering any benefits. The query's details are still exposed to the callers.

A: To do not make transparent classes, better to use query syntax and everything is availaible.
var result =
  from r in reservationRepository
  where companyIds.Contains(r.CompanyId)
  from t in t.Transactions
  where t.DateCreated >= options.PaymentFromDate
    && t.DateCreated < endDate
  select new
  {
      CompanyId = r.CompanyId,
      Method = t.Method,
      Amount = t.Amount,
      VatAmount = t.VatAmount
  };


text:
Q: Declare a retain property in class, will the compiler add [property release] to -dealloc by default?
Possible Duplicate:
Is releasing memory of Objective-c 2.0 properties required?

For example:
@interface DataMode : NSObject {
    NSString * name;
}

@property (nonatomic, retain) NSString * name;

@end

Will the compiler automatically add [name release] to -dealloc?
- (void) dealloc
{
   [name release];    // if we  don't add it , will the compiler add "[name release]"???
   [super release];

}

A: It depends on which memory management scheme you're using:

*

*With garbage collection, you don't need to release the instance variable that backs the declared property — the garbage collector automatically does that. In fact, you wouldn't be defining a -dealloc method at all even if you need to do other tasks upon deallocation: the garbage collector sends -finalize instead of -dealloc;

*With automatic reference counting (ARC), you wouldn't define that -dealloc method. ARC will automatically release the instance variable that backs the declared property. You can define a -dealloc method to do other housekeeping tasks if needed but you won't send [super dealloc];

*With manual memory management, you need to manually release the instance variable that backs the declared property and then send [super dealloc].

A: Since you are adding or rather creating name its your responsibility to release it. So you need to add [name release] in dealloc and also in ViewDidUnLoad use name = nil.
ObjectiveC has garbage collection but in iOS garbage collection part has been stripped out. So allocation, deallocation, retain etc. you need to be aware of...


text:
Q: Php input verification Is this how I would check if the input values have been filled out correctly? This isn't the beginning of this file.
<?php
if ($fname == "" || $lname == "" || $pass == "" || ($email == "" && $phone == ""))
{
    $error = "Not all fields were entered.<br />";
}
else
{ // Additional code
?>

Users can enter a phone or email, or both, but not neither.  Do I need to post more of my code? Thanks.

A: Yes this is correct for your usecase! :)
I have a Suggestion for you - you could use a libary like GUMP (https://github.com/Wixel/GUMP) since it greatly simplifies input validation :)


text:
Q: Convert rectangle to polygon with addRectangle How do I use the following method to convert a rectangle into a polygon?
public void addRectangle(int xPos, int yPos, int dX, int dY)

I have already tried:
/** * Converts the rectangle supplied into a polygon by making a new polygon
and adding each of the rectangle's corners as points. */

public static Polygon RectangleToPolygon(Rectangle rect) {
   Polygon result = new Polygon();
   result.addPoint(rect.x, rect.y);
   result.addPoint(rect.x + rect.width, rect.y);
   result.addPoint(rect.x + rect.width, rect.y + rect.height);
   result.addPoint(rect.x, rect.y + rect.height);
   return result;
}

A: Better use the constructor with all data.
public static Polygon RectangleToPolygon(Rectangle rect) {
    int[] xpoints = {rect.x, rect.x + rect.width, rect.x + rect.width, rect.x}:
    int[] ypoints = {rect.y, rect.y, rect.y + rect.height, rect.y + rect.height};
    return new Polygon(xpoints, ypoints, 4);
}

Or substitute rect's x, y, widht, height with
int xPos, int yPos, int dX, int dY


text:
Q: Rails: How to raise an error in a before_update method to the user I have searched a lot for this issue with no luck...
I have a model with a before_update method, I can't replace it with a validator because the actual method checks the existance of many things and update many others. My question is, How can I raise an error if a process from the before_update method fails? Something like:
def update_status
    if !(many verifications and updates)
       self.errors[:base] << "Could not update if ...."
    end
end

With the abobe code I get the update notice from the controller after the page loads, but I want to show the error from the before_update method. How can I show the error to the user?
Thanks a lot!!

A: def update_status
    if !(many verifications and updates)
       raise "Could not update if ...."
    end
end

Now do show the error message on the controller you could do something like this:
begin
  @myObject.update_status
rescue => ex
  flash[:notice] = ex.message
end


text:
Q: Correct way to use static methods in Web application I have a web application with the repository layer and the WebUI layer.
Basically i fill some grids with data that i get from this repository dll. Actually im doing like this:
private DemoRepository _demoRepository;

public DemoController()
{
    _demoRepository = new DemoRepository();
}

public ActionResult Demonstration()
{
     return View(_demoRepository.GetAll());
}

My question is, actually i dont need to create an object everytime so i could make the DemoRepository static and call directly in the ActionResult method:
public ActionResult Demonstration()
{
     return View(DemoRepository.GetAll());
}

But otherwise i know that its not a good practice to use static variables in web application, but in this case that im executing a method to get some data, is it correct?

A: A static method won't hurt as long as that static method receives all dependencies in the method call as parameters and isn't changing anything globally for the repository inside the method call.
If you're going to violate one of these two things (ie: DI via properties or some magic with connection strings), then I would stick with instantiating the repository and calling its GetAll() method.


text:
Q: Edit Post Counter Stays Hard Coded on Magento.SE Most of the time I can see on Magento.SE that some users always keep editing posts whether it's going to be helpful or not. (That's not my concern).
I did that same thing today (For checking editing counter) I've edited exactly 8 posts on that site, but still the counter didn't increase.
Check below Screen:

A: Tag edits don't count. It says that in the badge description. Only two of your five suggested edits on Magento were approved and all they changed were the tags. This is behaving as designed.


text:
Q: Unable to enter in the 'commenter' field of my database after executing my sql query, all the other fields are set except the said field I have a database having this schema
CREATE TABLE IF NOT EXISTS `comment`
(
`comment_id` int(11) NOT NULL auto_increment,
`commenter` varchar(100) NOT NULL,
`comment` varchar(255) NOT NULL,
`time` varchar(100) NOT NULL,
`date` varchar(100) NOT NULL,
PRIMARY KEY  (`comment_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ;

and i have a following code snippet in PHP
$comment=$_POST['comment'];
$dbNmee = $_SESSION['user'];
$time=date("h:i:sA",strtotime("+0 minute"));
$date=date("d-m-y",strtotime("+0 minute"));
$sql="INSERT INTO comment (commenter , comment , time , date) VALUES    ('$dbNmee','$comment','$time','$date')";

but am unable to enter in the commenter field of my database.


text:
Q: How to make "barstate.isfirst" work for double loop "for"? I am trying to make double loop work in Pine Editor code, inside a expression if.
I would appreciate if someone could help.
When compiling it seems that code only recognize second loop for, making invalid the first one.
I tried a bunch of differents things but any of them worked.
Thanks in advance.
    if barstate.isfirst
       for i = 0 to 499 by 1
           array.push(ln, line.new(na,na,na,na))

       for i = 0 to length/k-1
           array.push(upper,line.new(na,na,na,na))
           array.push(lower,line.new(na,na,na,na))

A: There is a limit of 500 drawing objects, lines/labels/boxes. It seems you are exceeding those limits.


text:
Q: Disable auto build/sync when a new activity is created in Android Studio? Whenever I create a new activity the Android Studio keeps syncing and building it. I have configured my builds to a remote server as I am running out of resources on the work machine. Hence I don't want Android Studio to compile code on creation of an activity, How do I disable this feature of Android Studio?

A: Don't create activity directly from android studio menu. Create the activity java class, layout separately, therefore, it will not build it again. If you follow this way then you need to manually mention your activity java class file name in the Manifest file.


text:
Q: ESXi 5.5 on unlisted AMD A10 6800K possible? I've done some initial googling..  and found AMD's A10 6800K supports virtualization via AMD-V. I'd like to install ESXI 5.5 on a USB thumbdrive to drive two+ VM's running Lubuntu.
Has anyone seen the AMD A10 APU line used for baremetal hosting?
AMD A10 APU 6800K
8GB DDR3 non ECC RAM
350GB HDD old spin drive (Sata I?III? unknown)

I want to get started but afraid I'll wipe my current linux instance if it goes bad.

A: The AMD APU based system is currently humming along.  Now I need to research how to add more drives.
Consumer grade HW required me to do some tweaking of the VMware install .iso .. See here :
http://www.bussink.ch/?p=1228

The ESXi 5.5.0 Build 1331820  that came out yesterday, did not include
  any Realtek R8168 or R8169 driver in it. So if your homelab ESXi host
  only has these Realtek 8168 network cards, you need to build a custom
  ISO.
The most simple tool to use is Andreas Peetz's (@VFrontDE)  ESXi
  Customizer 2.7.1 tool. The ESXi Customizer tool allows you to select
  the ESXi 5.5.0 ISO file and include into it a new Driver in .vib
  format.
You can then download and extract the VMware Bookbank NET-R8168 driver
  from vSphere 5.1 ISO or download it from the following link for your
  convenience.

http://www.v-front.de/p/esxi-customizer.html


text:
Q: Postal address auto-complete on profile page Is it possible to have an address auto-complete function (Where you enter your house number and post code and it automatically populates the address fields for you) within the Wordpress user profile page?
I'm more than happy to use a plugin if needs be (In fact I'd probably prefer it, this project is already well over budget)


text:
Q: Setting default value for DATE type column to current date without time part? NOTE: The question is about DATE type, not Datetime nor Timestamp
How to alter column of date data type to use current date by default?
I saw a lot of examples for datetime (with time part), but not for date. I have tried:
ALTER TABLE `accounting` ALTER `accounting_date`
  SET DEFAULT CURRENT_DATE;
ALTER TABLE `accounting` CHANGE `accounting_date`
  `accounting_date` DATE NOT NULL DEFAULT CURRENT_DATE;

I also tried with CURDATE(), NOW(), CURRENT_DATE() ...

A: MySQL 8.0+:
CREATE TABLE foo (
    `creation_time`     DATE DEFAULT (DATE_FORMAT(NOW(), '%Y-%m-%d'))
)

A: I use version 8.0.26, this is working:
datecolumn date DEFAULT (CURDATE())

It does not work, if you don't use the brackets!

A: Probably you cannot set default value for 'date' data type in mysql. You need to change the type to timestamp or datetime.
You may have a look at this similar question.
Invalid default value for 'Date'
EDIT:
In version 5.6.5, it is possible to set a default value on a datetime column, and even make a column that will update when the row is updated. The type definition:
CREATE TABLE foo (
    `creation_time`     DATETIME DEFAULT CURRENT_TIMESTAMP,
    `modification_time` DATETIME ON UPDATE CURRENT_TIMESTAMP
)

Reference: http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html

A: As noted in this question Invalid default value for 'create_date' timestamp field, this error may happen when MySQL is in strict mode (which is default behavior, I believe).
If you want to override it, just disable all these checks when creating your table:
SET SQL_MODE='ALLOW_INVALID_DATES';

The warning will be still generated, however it will allow to create the table.

A: It seems to work in sqlite:
"date" DATE NOT NULL DEFAULT (DATE(CURRENT_TIMESTAMP))

A: No, you cannot. The documentation is pretty clear on this:
This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for TIMESTAMP and DATETIME columns.


text:
Q: In VSCode turn off the following warning Accessors are only available when targeting ECMAScript 5 and higher The type script code I am writing compiles just fine. The issue is in visual studio code I see the following warning.

There is a similar question on SO to this but that is for compiling tyepscript which works . I just see the above warning and I cannot figure out how to turn it off.
I read update your tsconfig.json but as far as I can tell mine is correct.
My tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

A: If you create an application via the angular cli, ng new project, it will create two tsconfig.json one in the root folder of the project and one in the src folder. Web pack when calling ng serve uses the tsconfig.json in the root of the project while vscode uses the one in the src folder.
|-tsconfig.json
|-src
  |-tsconfig.json

To resolve: update the compiler options for the tsconfig.json in the src folder as follows
add "target": "es2017"
{
    "compilerOptions": {
        "experimentalDecorators": true,
        "allowJs": true,
        "target": "es2017"
    }
}


text:
Q: Ageing Database for age estimation Does anyone have a working link to the FG-NET ageing database or any other ageing database ? Edit
I have been trying to find on a online source for FG-Net aguing database , MOPRH database and YGA database. I can't seem to find none of them available to download . Does anyone know any other ageing database that i can use? Thankyou. I need an ageing database for a my school thesis as I am building a face recognition system and classifying the faces by age . It would be very helpful.

A: I expect these links could be useful to you as ageing database, they are all available to download :
FG-NET ageing database
DATA-VISION-imdb-wiki


text:
Q: How to install or use common build tools on agent I use the YUICompressor to compress files during my TeamCity builds.  I'd like to know the best way and common practice on getting the yuicompressor-2.4.7.jar file to my TeamCity agents and where to put the file.
I am not sure if the common practice is to manually put the file on the agent machine or to somehow make the file a part of another build and use that build's artifacts.
Is there an automated way via TeamCity to push files like this to agents?

A: TeamCity supports automatic distribution of tools to agents using the .tools folder.  Here are details: http://confluence.jetbrains.com/display/TCD8/Installing+Agent+Tools

A: Just keep it in repository. It is CI best practice.


text:
Q: Associative bilinear form that is unital I encountered a vector space with an associative bilinear map that is also unital... And I feel like this implies that this vector space is actually an algebra over the underlying field. Am I right?
Associative is the condition $u(u(x,y),z)=u(x,u(y,z))$ and unital is the condition that there exists $e\in V$ the underlying vector space $V$ such that $u(x,e)=u(e,x)=x$ for all $x\in V$.
Thank you. Have a nice day!

A: This is actually a definition of an algebra (which makes it apparent how to define a coalgebra).
Def 1: Let $K$ be a field. An (associative unital) $K$-algebra is a triple of data $(A, \mu, \eta)$ such that $A$ is a $K$-vector space, $\mu: A\times A\to A$ is a bilinear map called multiplication map, and $\eta: K\to A$ a linear map called unit. Such that

*

*Associativity: For all $x,y,z\in A$, one has $\mu(\mu(x,y), z)=\mu(x, \mu(y,z))$.

*Unital: For all $x\in A$ and $\alpha\in K$, $\mu(\eta(\alpha),x)=\alpha x=\mu(x, \eta(\alpha))$.

with this definition the element $e\in A$ that you mentioned is $e=\eta(1)$. Sometimes, using universal property of tensor product people instead define $\mu: A\otimes A\to A$ (linear) instead. The latter comes in handy actually.
Def 2: Let $K$ be a field, $A$ a ring equipped with a homomorphism $f: K\to A$. Then $A$ is called a $K$-algebra.
To see the equivalence of these definitions, say we start from def 2: Define $\eta$ as the underlying $K$-linear map of $f$. Also since $A$ is a ring, it already comes equipped with a associative bilinear map $\mu: A\times A\to A$. Moreover $A$ is obviously a $K$-vector space with scalar product $\alpha x=\mu(f(\alpha),x)=\mu(x, f(\alpha))=x\alpha$. So done.
Conversely, say we start with def 1: Then together $(A,\mu)$ is a ring. Now consider the map $\eta: K\to A$. Note that if $\alpha, \beta\in K$, then
$$
\eta(\alpha\beta)=\alpha \eta(\beta)=\mu(\eta(\alpha), \eta(\beta))
$$
Hence $\eta$ is actually a ring homomorphism, not just a $K$-linear map.


text:
Q: Decrease latency on camera view I read Ip camera but 500ms latency occurred on camera view. How can I decrease this value?
import cv2
cap = cv2.VideoCapture("rtsp:admin:admin@192.168.1.108/mpeg4 ")
while(True):
    ret, frame = cap.read()
    cv2.imshow("frame",frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
       break

       cap.release()
       cv2.destroyAllWindows()

A: The reason why you got that latency and the solution for that can be found here: https://www.pyimagesearch.com/2017/02/06/faster-video-file-fps-with-cv2-videocapture-and-opencv/


text:
Q: Mopub is not working with Admob any more? I've been using Ludei to compile my app, and I am trying to integrate Mopub ads on my app.
The first time that I executed my app, an ad with Mopub welcome message was shown, and suddenly anything else was shown any more.
I don't know what is happening because when I started using Ludei, one of my concerns was to test the Mopub plugin, to make sure that I would have a viable way to monetize my app, and at that time, it worked fine, but now I can't manage to make it works anymore.
Any suggestion will be appreciated.

A: MoPub is a great way to help you monetize your applications. It is an ad mediation company which Ludei has bundled into their SDK offering for the ad serving solution part.
You would need to register at mopub.com first and associate ad networks to your mobile applications within MoPub.  Those ad networks you add to the mopub dashboard would need respective credentials which you will receive when you create ad network accounts, example over at admob.com
MoPub side:
1-Register an account at mopub.com
2-Determine the ad unit id size you wish to have
3-Add ad networks and associate them with your ad unit id
4-consult more here:  http://help.mopub.com/
AdNetwork side:
1-register and create an account on the ad network of interest
2-input that ad network credential back to your mopub account


text:
Q: Unable to install node couchbase The couchbase builderror.log file is completely empty. Everything installs fine with npm install, no errors on screen or in the log.
Relevant details:
$ echo $PATH
/Users/david_fells/.nvm/v0.10.40/bin:/usr/bin:/Applications/MAMP/Library/bin:/Users/david_fells/.node_modules_global/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
$ node -v
v0.10.40
$ python -V
Python 2.7.6

Starting the app (node index.js  or  npm start):
[2015-09-30T15:26:23] [ERROR] [Error: Module did not self-register.]
[2015-09-30T15:26:23] [ERROR] { [Error: Cannot find module './build/default/DTraceProviderBindings'] code: 'MODULE_NOT_FOUND' }
[2015-09-30T15:26:23] [ERROR] { [Error: Cannot find module './build/Debug/DTraceProviderBindings'] code: 'MODULE_NOT_FOUND' }
/Users/david_fells/projects/inmarCDM/node_modules/couchbase/lib/binding.js:152
  throw new Error('Failed to locate couchnode native binding' +
  ^

Error: Failed to locate couchnode native binding (maybe check builderror.log!)
    at Object.<anonymous> (/Users/david_fells/projects/inmarCDM/node_modules/couchbase/lib/binding.js:152:9)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.cls_wrapMethod [as _load] (/Users/david_fells/projects/inmarCDM/node_modules/newrelic/lib/shimmer.js:230:38)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/david_fells/projects/inmarCDM/node_modules/couchbase/lib/couchbase.js:3:15)
    at Module._compile (module.js:434:26)

Process finished with exit code 1

NPM log has this:
0 info it worked if it ends with ok
1 verbose cli [ '/Users/david_fells/.nvm/v0.10.40/bin/node',
1 verbose cli   '/Users/david_fells/.nvm/v0.10.40/bin/npm',
1 verbose cli   'start' ]
2 info using npm@1.4.28
3 info using node@v0.10.40
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info prestart inmarCDM@0.0.5
6 info start inmarCDM@0.0.5
7 verbose unsafe-perm in lifecycle true
8 info inmarCDM@0.0.5 Failed to exec start script
9 error inmarCDM@0.0.5 start: `node index.js`
9 error Exit status 255
10 error Failed at the inmarCDM@0.0.5 start script.
10 error This is most likely a problem with the inmarCDM package,
10 error not with npm itself.
10 error Tell the author that this fails on your system:
10 error     node index.js
10 error You can get their info via:
10 error     npm owner ls inmarCDM
10 error There is likely additional logging output above.
11 error System Darwin 14.4.0
12 error command "/Users/david_fells/.nvm/v0.10.40/bin/node" "/Users/david_fells/.nvm/v0.10.40/bin/npm" "start"
13 error cwd /Users/david_fells/projects/inmarCDM
14 error node -v v0.10.40
15 error npm -v 1.4.28
16 error code ELIFECYCLE
17 verbose exit [ 1, true ]

Here's the full output from an npm silly: https://dl.dropboxusercontent.com/u/34647212/npm.log

A: Check this thread from couchbase forum.
It seems that your environment is lacking some prerequisites of node-gyp
Then check node-gyp's official readme.
May the odds be ever in your favor


text:
Q: How do I return a space from Microsoft T-SQL? I want SQL to return either "*" or " " (to get even spacing further down the line). It returns "*" or "" when told to return " ".
From other questions and my own attempts this looks like there is no workaround. Do you have a solution?
CREATE FUNCTION [dbo].[fn_nettAsStar]
    (@isNett bit)
RETURNS char(1)
AS
BEGIN
    /* set space */
    DECLARE @nett char(1)
    SET @nett = ' '

    IF @isNett = 1
    BEGIN
        SET @nett = '*'
    END

    RETURN @nett

A: I agree with @Martin

If you are using LEN to come to the conclusion that it is an empty string not a space then that doesn't count trailing spaces so will return zero

when you put value 'abc' in a field/variable of type CHAR(5), the value will become 'abc  ', but the LEN function will still "correctly" return 3 in that case. but if you use DATALENGTH instead of LEN, you will see that it is actually 5 characters long. If you define your variable with VARCHAR(5) then using LEN again will give you 0 length, however DATALENGTH will give you 1
NOTE that: VARCHAR is Variable Length Character
to conclude
@nett varchar(1) = ''  => LEN = 0, DATALENGTH = 0
@nett varchar(1) = ' '  => LEN = 0, DATALENGTH = 1
@nett    char(1) = ''  => LEN = 0, DATALENGTH = 1
@nett    char(1) = ' '  => LEN = 0, DATALENGTH = 1

A: thanks for the answers. I was using the function to build a report line which comes out 1 character shorter when the "space" is returned.
As suggested I used LEN() to check that I was getting an empty string.
My solution is to use procedural code rather than SQL to format the string.


text:
Q: Why object property undefined in another method from the same object but not undefined in other? Ok, so I've been struggling with something I think it's pretty simple. Not sure if it's the Babel compiler or what. So I've got this class:
export default class animateFormClass {

    constructor(formSelector, buttonElement = null, currentCard = null, prevCard = null, nextCard = null) {
        this.form = document.querySelector(formSelector);
        this.direction = 'forward';
        this.progressBar = document.getElementById('progressbar');
        this.opacity = this.opacityLeft = 0;
        this.buttonElement = buttonElement;
        this.currentCard = currentCard;
        this.prevCard = prevCard;
        this.nextCard = nextCard;
    }

    animateForm() {
        if (this.direction === 'forward') {

            if (this.nextCard !== null) {
                this.fadeOut = setInterval(this.fadeOutAnimation, 10);
                this.updateProgressBar;
            }
        } else if (this.direction === 'back') {

            if (this.prevCard !== null) {
                this.fadeOut = setInterval(this.fadeOutAnimation, 10);
                this.updateProgressBar;
            }
        }

    }
    fadeOutAnimation() {
        this.opacity = this.opacity - 0.05;
        console.log(this.opacity, this.currentCard);
        if (this.opacity >= 0) {
            this.currentCard.style.opacity = this.opacity;
        } else {
            this.currentCard.classList.add('d-none');
            this.fadeIn = setInterval(this.fadeInAnimation, 10);
            clearInterval(this.fadeOut);
        }
    }

    fadeInAnimation() {
        this.opacityLeft = this.opacityLeft + 0.1;
        let cardElement;

        if (this.direction === 'forward') {
            cardElement = this.nextCard;
        } else if (this.direction === 'back') {
            cardElement = this.prevCard;
        }

        cardElement.classList.remove('d-none');

        if (this.opacityLeft <= 1) {
            cardElement.style.opacity = this.opacityLeft;
        } else {
            clearInterval(this.fadeIn);
        }
    }

    updateProgressBar() {
        let activeElement = this.progressBar.querySelector('.active');
        let nextListElement = activeElement.nextElementSibling;
        let prevListElement = activeElement.previousElementSibling;

        if (this.direction === 'forward') {
            if (nextListElement !== null) {
                activeElement.classList.remove('active');
                activeElement.classList.add('step-completed');
                nextListElement.classList.add('active');
            }
        } else if (this.direction === 'back') {
            if (prevListElement !== null) {
                activeElement.classList.remove('active');
                prevListElement.classList.remove('step-completed');
                prevListElement.classList.add('active');
            }
        }
    }
}

and from another file I'm importing the class like this:
import animateFormClass from './animateForm';

Ok so in this file I've got some code in which I update some of the object properties but in the animateForm() method the properties seem to be OK BUT when those same object properties are used by the other method called fadeOutAnimation() I've got this message of undefined in the this.currentCard property.
Here's the code in which I make the class instance:
if (document.getElementById('register')) {
    let animate = new animateFormClass('#register');
    let currentCard, prevCard, nextCard;
    document.getElementById('register').addEventListener('click', function(e) {
        if (e.target.classList.contains('next')) {
            animate.direction = 'forward';
            animate.currentCard = e.target.closest('fieldset');
            animate.nextCard = animate.currentCard.nextElementSibling;
            animate.animateForm();
        } else if (e.target.classList.contains('prev')) {
            animate.direction = 'back';
            animate.animateForm(e.target);
        }
    });
}

I get the error when the animate.animateForm() method is called. My environment is working on a PHP web app using Laravel and using the watch task that Laravel has out of the box.
EDIT:
Thank you for your help, I was able to fix it. If anyone was wondering, I changed all the methods of the class as properties and used the arrow function syntax. So thanks again!!!

A: When you're doing setInterval(this.fadeOutAnimation, 10), 'this' inside 'fadeOutAnimation' is binded by window. Use setInterval(() => { this.fadeOutAnimation() }, 10); It preserves 'this' context.

A: Thank you for your help, I was able to fix it. If anyone was wondering, I changed all the methods of the class as properties and used the arrow function syntax. So thanks again!!!
Here's the new code:
export default class animateFormClass {

constructor(formSelector) {
    this.form = document.querySelector(formSelector);
    this.direction = null;
    this.progressBar = document.getElementById('progressbar');
    this.opacity = this.opacityLeft = 0;
    this.buttonElement = null;
    this.currentCard = null;
    this.prevCard = null;
    this.nextCard = null;

    this.animateForm = (buttonElement) => {
        this.buttonElement = buttonElement;
        this.currentCard = this.buttonElement.closest('fieldset');
        this.nextCard = this.currentCard.nextElementSibling;
        this.prevCard = this.currentCard.previousElementSibling;

        if(this.direction === 'forward') {
            if(this.nextCard !== null) {
                this.fadeOut = setInterval(() => { this.fadeOutAnimation() }, 10);
                this.updateProgressBar();
            }
        }
        else if(this.direction === 'back') {
            if(this.prevCard !== null) {
                this.fadeOut = setInterval(() => { this.fadeOutAnimation() }, 10);
                this.updateProgressBar();
            }
        }
    }

    this.fadeOutAnimation = () => {
        this.opacity = this.opacity - 0.05;
        if(this.opacity >= 0) {
            this.currentCard.style.opacity = this.opacity;
        }
        else {
            this.currentCard.classList.add('d-none');
            this.fadeIn = setInterval(this.fadeInAnimation, 10);
            clearInterval(this.fadeOut);
        }
    }

    this.fadeInAnimation = () => {
        this.opacityLeft = this.opacityLeft + 0.1;
        let cardElement;

        if(this.direction === 'forward') {
            cardElement = this.nextCard;
        }
        else if(this.direction === 'back') {
        cardElement = this.prevCard;
        }

        cardElement.classList.remove('d-none');

        if(this.opacityLeft <= 1) {
            cardElement.style.opacity = this.opacityLeft;
        }
        else {
            clearInterval(this.fadeIn);
        }
    }

    this.updateProgressBar = () => {
        let activeElement = this.progressBar.querySelector('.active');
        let nextListElement = activeElement.nextElementSibling;
        let prevListElement = activeElement.previousElementSibling;

        if(this.direction === 'forward') {
            if(nextListElement !== null) {
                activeElement.classList.remove('active');
                activeElement.classList.add('step-completed');
                nextListElement.classList.add('active');
            }
        }
        else if(this.direction === 'back') {
            if(prevListElement !== null) {
                activeElement.classList.remove('active');
                prevListElement.classList.remove('step-completed');
                prevListElement.classList.add('active');
            }
        }
    }
}

}


text:
Q: Using hg repository as web site This is somewhat related to my security question here. Is it a bad idea to use an hg / mercurial repository for a live website? If so, why?
Furthermore, we have dev, test and production installations of our website, like dev.example.com, test.example.com and www.example.com. If it's a bad idea to use a repository for a live/production website, would it be OK to use an hg repository for the dev and test sites?
I'm also concerned about ease of deployment. We have technical and less technical co-workers who will be working with the site. The technical people (software engineers) won't have any problem working with the command line or TortoiseHG. I'm more concerned about the less technical people (web designers). They won't be comfortable working on the command line, and may even find TortoiseHG daunting. These co-workers mostly upload .css files and images to the server. I'd like for these files (at least the .css files) to be under version control, but I want this to be as transparent as possible for the non technical team members.
What's the best way to achieve this?
Edit:
Our 'site' is actually a multi-site CMS setup with a main repository and several subrepositories. Mock-up of the repository structure:
/root [main repository containing core files and subrepositories]
    /modules [modules subrepository]
    /sites/global [subrepository for global .css and .php files]
    /sites/site1 [site1 subrepository]
    ...
    /sites/siteN [siteN subrepository]

Software engineers would work in the root, modules and sites/global repositories. Less technical people (web designers) would work only in the site1 ... siteN subrepositories.

A: Yes, it is a bad idea.
Do not have your repository as your website. It means that things checked in, but unworking, will immediately be available. And it means that accidental checkins (it happens) will be reflected live as well (i.e. documents that don't belong there, etc).
I actually address this "concept" however (source control as deployment) with a tool I've written (a few other companies are addressing this topic now, as well, so you'll see it more). Mine is for SVN (at the moment) so it's not particularly relevant; I mention it only to show that I've considered this previously (not on a Repository though; a working copy, in that scenario the answer is the same: better to have a non-versioned "free" are as the website directory, and automate (via user action) the copying of the 'versioned' data to that directory).

A: Many folks keep their sites in repositories, and so long as you don't have people live-editing the live-site you're fine.  Have a staging/dev area where your non-revision control folks make their changes and then have someone more RCS-friendly do the commit-pull-merge-push cycle periodically.
So long as it's the conscious action of a judging human doing the staging-area -> production-repo push you're fine. You can even put a hook into the production clone that automatically does a 'hg update' of the working directory within that production clone, so that 'push' is all it takes to deploy.
That said, I think you're underestimating either your web team or tortoiseHg; they can get this.

A: me personally (i'm a team of 1) and i quite like the idea of using src control as a live website. more so with hg, then with svn.
the way i see it, you can load an entire site, (add/remove files) with a single cmd
much easier then ftp/ssh this, delete that etc
if you are using apache (and probably iis as well) you can make a simple .htaccess file that will block all .hg files (or .svn if you are using svn)
my preferred structure is
development site is on local machine running directly out of a repository (no security is really required here, do what you like commit as required)
staging/test machine is a separate box or vm running a recent copy of the live database
(i have a script to push committed changes to staging server and run tests)
live machine
(open ssh connection, push changes to live server, test again, can all be scripted reasonably easily, google for examples)
because of push/pull nature of hg, it means you can commit changes and test without the danger of pushing a broken build to the live website. like you say in your comments, only specific people should have permission to push a version to the live site.  (if it fails, you should easily be able to revert to the previous version, via src control)

A: Why not have a repo also be an active web server (for dev or test/QA environment anyway)?
Here's what I am trying to implement:

*

*Developers have local test environments in which they can build and test their code

*Developers make a clone of the dev environment on their local dev machine

*Developers commit as often as they want to their local repo

*When chunk of work is done and tested, then developer pushes working change sets to dev repo

Changes would be merged and tested on Dev, then pushed to Test/QA, and so on.
BTW, we're using Mercurial.  I believe this model would only work using a distributed source code management tool.


text:
Q: Java HIBERNATE + Spring Security. Не получается проверить работу Spring Security Есть готовый проект на Java с использованием HIBERNATE, Primefaces и бд PostgreSQL. Сказали прикрутить Spring Security к логину и регистрации. Вроде всё сделал, но не понимаю как проверить работу Spring Security. Кто может подсказать как продебажить его? Уже 3 дня пытаюсь разобраться. Документация не помогает

A: 1) Авторизация в системе:
Вариант 1:
Вам необходимо создать пользователя в БД, затем закодировать его пароль через какой-нибудь BCrypto-online(google в помощь). После чего написать метод авторизации, используя методы из Spring Security.
Вариант 2:
Вы можете написать метод регистрации, затем зарегистрироваться. После чего написать метод авторизации, используя методы из Spring Security, соответственно, за тем авторизоваться.
пример добавления Spring Security: https://www.baeldung.com/registration-with-spring-mvc-and-spring-security
2) CSRF and CORS:
Добавьте после csrf().disable() следующий код: .cors().disable().
Все вместе должно выглядеть так: .cors().disable().csrf().disable().
Иначе у Вас будет всегда выводится 403 ошибка HTTPS - FORBIDDEN, даже если Вы авторизовались верно в системе.

A: https://habr.com/ru/post/482552/
Мне очень помогла эта статья, тоже долго не мог прикрутить авторизацию по ролям. Но благодаря ей, я достиг своей цели.
В данной статье говорится о регистрации и автоматически присваиваемой роли, роли админ, где он может назначать роль в своей учетной записи. В дальнейшем Вы сами можете создавать роли и прописывать им ссылки в configSpringSecurity. Также создать класс CustomAuthenticationSuccessHandler и переадресовывать на страницу в зависимости от авторизованной роли


text:
Q: How to make the urls and emails linkable in csv sheet using nodejs? I have written the code to download the CSV file after exporting it to CSV using nodejs.
In the CSV file there are some columns like URI and Email which I want linkable means hyperlinked after exported to CSV.
enter image description here


text:
Q: Compound conditional in a bash while loop Im modifying an existing bash script and having some trouble getting the while loop behaving correctly. This is the original code
while ! /usr/bin/executable1
do
    # executable1 returned an error. So sleep for some time try again
    sleep 2
done

I would like to change this to the following
while ! /usr/bin/executable1 && ! $(myfunc)
do
    # executable1 and myfunc both were unsuccessful. So sleep for some time
    sleep 2
done

executable1 returns 0 on success and 1 on failure. I understand that "true" in bash evaluates to 0 so thats why the original script would keep looping till executable returned success
Accordingly myfunc is coded like this
myfunc ()
{
    # Check if file exists. If exits, return 0, If not, return 1
    if [ -e someFile ]; then
        return 0
    fi

    return 1
 }

I notice that the my new while loop does not seem to call executable1. It always calls myfunc() and then exits out of the loop immediately. What am I doing wrong?
I tried various ways of coding the while loop (with (( )), [ ], [[ ]] etc), but nothing seems to fix it

A: You don't need $(...) to call a function, just to capture its standard output. You simply want
while ! /usr/bin/executable1 && ! myfunc
do
    sleep 2
done

Note that myfunc can also be more simply written
myfunc () {
    [ -e someFile ]
}

or even (in bash)
myfunc () [[ -e someFile ]]

Either way, it's almost not worth defining myfunc separately; just use
while ! /usr/bin/executable1 && ! [[ -e someFile ]]
do
    sleep 2
done

It might also be simpler to use an until loop:
until /usr/bin/executable1 || [[ -e someFile ]]; do
    sleep 2
done


text:
Q: Uncaught SyntaxError: Invalid or unexpected token when adding parameter to a javascript method in jstl Im trying to invoke a javascript method in a hyperlink onClick setting a  parameter in JSTL as below :
<c:if test="${not test1 && test2}">

Message....
      <a onclick="executeBusinessPatch(<c:out value="${paymentId}"/>)" style="color: #a94442">Configure Now.

</c:if>

 function executeBusinessPatch(inAppPaymentTenderId) {
  alert(inAppPaymentTenderId);
 }

But im getting above error Uncaught SyntaxError: Invalid or unexpected token when the hyperlink is clicked. What could be gone wrong?

A: onclick="executeBusinessPatch(<c:out value="${paymentId}"/>)"

You have to use ' instead of " when using inline javascript:
onclick="executeBusinessPatch(<c:out value='${paymentId}'/>)"

Otherwise it will treat the " at ..ue="${pay.. as the end of your string and continue parsing ${payment as were it the next attribute of your html element.


text: Q: Application of Doob's Optional Stopping Time Theorem on new stopping time Consider a random walk on a line starting at 0. On each step the probability of moving in either direction (right or left) is 1/2. There are two particular points on the line -a, and b. If $\tau$ is the hitting time of A, then $\tau$ is not bounded, and we cannot apply Doob's Theorem. However, we can apply Doob'ts Theorem to $\tau'$ = $\min(\tau, n)$. I don't understand why $\min(\tau, n)$ is necessarily bounded.. can't the 'walker' stay between -a and b to $\infty$? so then n is $\infty$?


text:
Q: In Numpy, how can I add a 1d array to a 2d array along a new axis Im sure this has been answered before as this seems like a pretty trivial question but I cant for the life of me figure out how to add a 2d array to a 1d array along the column so that there are two values in each row.
a = [[1,2,3], [1,3,5], [1,1,1]]
b = [[1], [2], [5]]

so what numpy function can I use to generate
[ [[1,2,3],[1]], [[1,3,5],[2]], [[1,1,1],[5]] ]

Cheers!

A: this isn't easy with numpy arrays, but you can get the structure you want with:
c = [list(q) for q in zip(a,b)]

# output
[[[1, 2, 3], [1]], [[1, 3, 5], [2]], [[1, 1, 1], [5]]]

casting this to a numpy array gives an array of lists, which is a strange structure and probably not very useful:
arr = np.array(c)

# output:
array([[list([1, 2, 3]), list([1])],
       [list([1, 3, 5]), list([2])],
       [list([1, 1, 1]), list([5])]], dtype=object)


text:
Q: Enter keypress function in Form doesn't work I did this form to calculate shippings:

    Simulação de Entrega:

 Digite seu CEP

    <input id="cep" type="text"/>
    <input id="botao" type="button" class="button-frete" value="<?php echo $this->__('Calcular'); ?>"/>

But I don't know how to make enter keypress work on it:

A: I Make a new one in jquery
    jQuery.noConflict(); // INSIDE INPUT "CEP"
if (jQuery('input#cep').length) {
    jQuery('input#cep').click(function(){ // GET KEYPRESS "E"
        jQuery(document).keypress(function(e) {
            var keycode = (e.keyCode ? e.keyCode : e.which); // ENTER?
            if(keycode == '13') {
                new Ajax.Updater('content-frete', '/Freteproduto?cep='+$('cep').getValue()+'&productid=<?php echo $produto->getId();?>', { method: 'get' });
            }
        });
    });
}


text:
Q: How to display array of objects in table getting dynamically from backend in ReactJS I'm getting data from backend in a dynamic manner which is based in user selection. Now, I need to display that data in the table. Can anyone help me with it?
For ex : I will get data like this from backend for the first time when user selects only 2 fields
{
 "result":[
  {
   "c3":"test_customer1",
   "penddel":"3029"
  },
  {
   "c3":"test_customer2",
   "penddel":"7976"
  },
 ]
}

And when second time when user selects more fields data comes for that fields
For ex:
{
 "result":[
  {
   "c3":"test_customer1",
   "penddel":"3029"
   "c5":"testc1"
  },
  {
   "c3":"test_customer2",
   "penddel":"7976"
   "c5":"testc2"
  },
 ]
}

So everytime data comes based on the user selection of fields, need to display this data dynamically in table

A: You can fetch the data as normal and then just use object keys to pull the headings from the result.
We can then use this array to render the table headings.
Once the table headings are rendered we can then map the data and iterate through each item whilst mapping the previous heading array to render each value.
Using React Class API

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: null,
    };

    this.fetchData = this.fetchData.bind(this);
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    return new Promise(resolve => resolve({
      "result": [{
          "id": "1",
          "name": "john",
          "age": "35"
        },
        {
          "id": "2",
          "name": "johnson",
          "age": "25"
        }
      ]
    })).then((response) => {
      this.setState({ data: response.result });
    });
  }

  render() {
    const { data } = this.state;

    if (!data) {
      return
Loading...
;
    }

    const headings = Object.keys(data[0]);

    return (

            {headings.map((heading) => {heading}	)}

          {data.map((row) => (

              {headings.map((heading) => {row[heading]}	)}

          ))}

    );
  }
};

ReactDOM.render(
  <App /> ,
  document.getElementById('root')
);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" />

Using React Functional Component + React Hooks

const App = () => {
  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    const fetch = () => {
      return new Promise(resolve => resolve({
        "result": [{
            "id": "1",
            "name": "john",
            "age": "35"
          },
          {
            "id": "2",
            "name": "johnson",
            "age": "25"
          }
        ]
      })).then((response) => {
        setData(response.result);
      });
    };

    fetch();
  }, []);

  if (!data) {
    return
Loading...
;
  }

  const headings = Object.keys(data[0]);

  return (

          {headings.map((heading) => {heading}	)}

        {data.map((row) => (

            {headings.map((heading) => {row[heading]}	)}

        ))}

  );
};

ReactDOM.render(
  <App /> ,
  document.getElementById('root')
);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" />

A: You will probably want to store the object you are getting from your backend in a useState hook. You will also want to track how many fields the user has selected with a useState hook. Something like this:
const [data, setData] = useState(null); // no initial data
const [fields, setFields] = useState(2); // 2 initial fields selected

Now you can update the fields state with a method within your function that gets called every time the value changes. Then you want to query your backend with a useEffect hook and pass in the new field value from the backend.
const updateFields = (event) => {
  setFields(event.target.value);
}

useEffect(() => {
  axios.get(`backend/api/?fields=${fields}`)
    .then(res => {
      setData(res.body);
    })
});

As per the comment, if you're not using hooks, you can use ComponentDidMount instead of useEffect and create a similar update method.
const updateFields = (event) => {
  this.setState({ fields: event.target.value });
}

componentDidMount() {
  axios.get(`backend/api/?fields=${fields}`)
    .then(res => {
      this.setState({ data:  res.data });
  })
}

Now you can return JSX that has a field to set the field number as well as map through the data object to set a dynamic table of values. If you're not using hooks, place the this keyword to reference state (i.e. this.data instead of data).
return (
  <input onChange={(e) => updateFields(e)} />

      {Object.keys(data[0]).map((el) => {
        {el}
      })

      {data.map((el, i) => {
        {Object.keys(data[i]).map((elKey) => {el[elKey]}	)}
      }

);

These are two great resources for understanding more about querying data:
https://reactjs.org/docs/hooks-effect.html
https://alligator.io/react/axios-react/
And this is a good resource for understanding more about mapping over objects in React:
https://reactjs.org/docs/lists-and-keys.html

A: How about conditionally rendering the cells?
Like:
data.map(item => (
    {item.age? {item.age}	: null}
))

A: Every time user selects fields, store the field name in a variable.
Ex:
const Header = [{"title":"Name","index":"name"}]

Make sure the key matches with the array index which you get from server(API).
Then create anew component for rendering table and pass data and headers to that as props
Then extract the headers to an array and before rendering data, just check if the specific value exists
const viewTable = (props) => {
    const index = [];
    const header = props.header.map((heading) => {
        index.push(heading.index);
        return {heading.title}
    });

    const tableData = props.data.map((data, key) => {
        return

             {index.map(key => {
                 if (index.indexOf(key) > -1) {
                     return {row[key]}	;
                 }
             })}

    }) ;

    return (

                    {header}

                {tableData}

    );
}

export default viewTable;


text:
Q: ASP.net post to server slow on big pages I have an ASP.net page using jquery 1.10.2 that generates a lot of data an sends it to the client.
When I submit the received clientpage back to the server (pressing submit) it takes a very long time to reach the server. (in chrome it says:uploading xx%)
I now clear the div where the data sits in (

$('#datadiv').html('');

)
but, although it's empty before getting submitted, it still is on snail speed.
Questions:
now that the div is empty what is it sending that takes that long?
How to make it faster (paging is not an option) ?

A: Div or other html-tags are not sended back to server at POST request.
You have to investigate the particular problem. Please install Fiddler to debug the real POST request parameters.
I think that problem is in ViewState or other hidden fields.

A: @lopsider Well fiddler messed up my dev environment somewhat (vs2010 webserver) So as I thought viewstate only passes formfields I never tried mason's suggestion and disabeling it WORKED! So i've to do a bit more reading on the life an contents of viewstat. @Mason & @Yuriy Thnks!


text:
Q: YouTube embedding and wicket fancy box I'm using visural-wicket's fancy box (http://wicket.visural.net/examples/app/fancybox) to display some YouTube videos on my site.
Basicly the HTML looks like this:

...(some other divs)

As you can see only difference is that one is a hyperlink (in my case with fixed width/height and background img) and second one is hyperlink with img.
The first one works good and gives really nice looing fancy box like in an example. The second one instead of making a fancy box, redirects to youtube video on full screen. What might be the problem? Java code looks like this:
public class MyWebPage extends WebPage {
private static final String YOUTUBE_LINK = "someYoutubeVideoLinkHere";
public MyWebPage() {
    add( new Fancybox( "iframe", YOUTUBE_LINK ).setWidth( 560 ).setHeight( 315 ) );
    add( new Fancybox( "iframe2", YOUTUBE_LINK ).setWidth( 560 ).setHeight( 315 ) );
}


text:
Q: Regex for ranges (and specifics) in a zero-padded string? I'm new to regex and I'm trying to match with a string that contains zero-padded digits (suffice to say I'm having some trouble).
I have a thousand files that are named as below; what I'd like to do is write a single expression that could match any file number in a range and/or specific values (like the page selection in a print dialog). So for example, files 20-30 and file 45, 50, and 55.
File naming convention = "FILE-00001.csv" -> "FILE-01000.csv"
To be even more annoying, there could be any number of leading zero characters. Any one have any ideas or hints that could point me in the right direction?

A: as far as the example you've asked for,
FILE-0*(?:2[0-9]|[35]0|[45]5)\.csv

should cover files 20-30, 45, 50 and 55
[edited to use non-capturing group]


text:
Q: Realm multiple database problems There are two databases locally, 'user.realm' and 'person.realm'. 'User' model need to be saved in 'user.realm'. 'Person' model need to saved in 'person.realm' , When the following code is used, the 'User' and 'Person' tables is created in 'user.realm'. I need 'User' model only saved to 'user.realm'.
class User:Object {
    @objc dynamic var id:Int = 0
    @objc dynamic var name:String = ""
}

class Person:Object {
   @objc dynamic var id:Int = 0
   objc dynamic var name:String = ""
}

//create "user.realm"
var config = Realm.Configuration()
config.fileURL = dataPath.appendingPathComponent("user.realm")
Realm.Configuration.defaultConfiguration = config
var realm = try! Realm()

//create  "person.realm"
var config = Realm.Configuration()
config.fileURL = dataPath.appendingPathComponent("person.realm")
Realm.Configuration.defaultConfiguration = config
var realm = try! Realm()

When I execute a user database, I only need to create the "User" table in user.realm, instead of "User" and "Person" two tables are created together in "user.realm", I can't remove the Person model, because then you cannot create the "Person" table in "Person.realm". Personally, it seems that Realm is more troublesome to implement.

A: One of the key points to know about Realm is that it is not a relational database. While it has that 'feel' which is intentional, there are no tables as such and Realm structures are often split amongst different realms. Check out Realm vs Other Databases.
In some cases it's more efficient to store like data within the same Realm - a User and a Person look very similar so it may be better to store them within the same Realm - I just don't know the use case here.
To answer the question though, you can specifically tell Realm what object or objects to store within a realm. It's done through the config like this
let config = Realm.Configuration(objectTypes: [MyClass.self, MyOtherClass.self])
let realm = try! Realm(configuration: config)

That realm will only have MyClass and MyOtherClass in it. Applying that to your question
let config = Realm.Configuration(objectTypes: [UserClass.self])
let myUserRealm = try! Realm(configuration: config)

Will only have one object type in it, a UserClass.
That's covered in the Class Subsets section of the Realm Documentation Provide a subset of classes to a Realm


text:
Q: SUMX Multiple Filter Criteria + VARs I've seen a couple posts that have helped push me along with the proper DAX structure. My background is SQL so I would have approached this with a over partition, however, I think I'm pretty close with my current code. EARLIER() didn't seem to allow me to select my desired variables, so I saw another post that said to declare the variables within the calculated measure.
However, I can resolve my "syntax for 'FILTER' is incorrect".
Factor2 = SUMX(Test_Table,
    VAR FiscalYear = Test_Table[FiscalYear]
    VAR Segment    = Test_Table[Segment]
    Var PerChange  = FILTER(Test_Table,Test_Table[FiscalYear]=FiscalYear && Test_Table[Segment]=Segment),Test_Table[PercentChange])

RETURN PerChange/[MaxYear]

I was also unable to figure out how to apply an if/then with logic like:
IF FiscalYear = MAX(Year), then Factor2 = 1,
ELSE: (run above code)
If this fairly simple to include, please advise, otherwise I can continue to troubleshoot.

A: Try this one:
Factor2 =
VAR FiscalYear = Test_Table[FiscalYear]
VAR Segment = Test_Table[Segment]
VAR PerChange =
    FILTER (
        Test_Table,
        Test_Table[FiscalYear] = FiscalYear
            && Test_Table[Segment] = Segment
    )
VAR Result =
    SUMX ( PerChange, Test_Table[PercentChange] )
RETURN
    CALCULATE (
        IF ( FiscalYear = MAX ( Test_Table[Year] ), 1, DIVIDE ( Result, [MaxYear] ) )
    )

Your comment "What if we just were to try and find the PercentChange for max(FiscalYear) by segment/PercentChange Would that be eaiser?"
So I tried this one:
Factor3 =
VAR FiscalYear =
    MAX ( Test_Table[FiscalYear] ) -- VAR Segment = Test_Table[Segment]
VAR PerChange =
    FILTER (
        Test_Table,
        Test_Table[FiscalYear] = FiscalYear -- && Test_Table[Segment] = Segment
    )
VAR Result =
    SUMX ( PerChange, Test_Table[PercentChange] )
RETURN
    Result

Note: "--" sign preceding the statement means that line is converted to comments, and has no effect on DAX code.


text:
Q: Xcode 13.1 generates error "type 'struct ah' has incompatible definitions in different translation units" in legacy code I have an application that uses mongoose as a library. After updating Xcode to 13.1 (macOS Monterey) I am getting a compile error that I can't figure out how to fix:
type 'struct ah' has incompatible definitions in different translation units

This is in a block of code within mongoose where a struct is being defined and used:
// Parsed Authorization header
struct ah {
  char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
};

// Return 1 on success. Always initializes the ah structure.
static int parse_auth_header(struct mg_connection *conn, char *buf,
                             size_t buf_size, struct ah *ah) {
  char *name, *value, *s;
  const char *auth_header;

  (void) memset(ah, 0, sizeof(*ah));
  if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
      mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
    return 0;
  }

I would really rather not modify the code since it's a 3rd party library that may receive updates. But at the same time I have to be able to build my app.
Is there an Xcode setting that I'm not seeing to get around this? I'm not sure what the error even means.

A: For anyone having problems with this in 2022 and who don't want or can't rename their structs:
I have found this post on a Chinese blog: https://www.cnblogs.com/dzqdzq/p/9977638.html
Basically, the easy fix seems to be to disable the "Enable Modules (C and Objective-C)" build setting. It seems disabling this option makes the XCode Clang compiler work in a way that is more similar to GCC.


text:
Q: Passing object to partial() view helper in ZF2 I'm trying to pass an object to the partial() view helper. While working with normal variables workes fine, I'm not able to pass object to this function.
For example, this workes fine when using $this->test in partial:
$this->partial("module/folder/partial.phtml", array(
    "test" => "foo",
));

But doing the same with an object will result in nothing in partial:
$this->partial("module/folder/partial.phtml", array(
    "test" => $this,
));

I've even tried using setObjectKey, what didn't woked too:
$this->partial()->setObjectKey("test");
$this->partial("module/folder/partial.phtml", $this);

Is there a way to pass an object to an single partial in ZF2?
I want to do this, because my view actually contains many informations the partial needs. I could add them all line-by-line to the partial, but that would just be overhead ...

A: When you pass the parent Zend\View\Renderer\PhpRenderer to your partial it will overwrite/replaces the $test variable with the Zend\View\Renderer\PhpRenderer of your partial, like it is re-using the class. So resulting in a object that is empty as your partial PhpRenderer has no other variables included.
If you want the variables from the parent PhpRender use the following:
$this->partial('folder/partial', ['vars' => $this->vars()->getArrayCopy()]);
// Or so, so you don't need to store the originals within the vars key
$this->partial('folder/partial', $this->vars()->getArrayCopy());

Now within your partial.phtml:
$this->vars['foo']

To confirm this, let your controller return some variable ['foo' => 'bar'] or setup a ViewModel with some test variables. Now setup your partial:
$this->partial('folder/partial.phtml', ['test' => 'abc' 'render' => $this].

And when you debug or var_dump() your PhpRenders variable you'll see that $render containts the variable $test with a value of abc and not the key 'foo' with 'bar' as its value. So it looks like the PhpRenderer is being reused so passing the parent PhpRenderer is not possible.


text:
Q: Centralized all functions/ methods [Android in Java] I would like to centralize most of my common functions and those can just be called anytime anywhere. Is that possible to do that?
For example:
public void showError(final String Error_Msg) {
    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(common_provider.this, Error_Msg, Toast.LENGTH_LONG).show();
        }
    });
}

A: Yes, you can use static functions.
Create Class, for example CommonFucntions.class
CommonFunctions.class
public class CommonFunctions {

    public static void showError(final Activity activity, final String Error_Msg) {
    activity.runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(activity, Error_Msg, Toast.LENGTH_LONG).show();
        }
    });

}

And then, whereever you want, you can use this function, by calling CommonFunctions.showError(this, "Sample error");

A: Extend Application class for that: https://www.mobomo.com/2011/05/how-to-use-application-object-of-android/


text:
Q: How to write a kusto query to group n number of consecutive rows based on value in a column I have a dataset that has values as following
DataSet:
Col1 Col2
A 0
B 1
C 1
D 1
E 0
F 0
G 1
H 0
I 0
J 0
K 1

I want the result to be as follows:
Col1      Col2
[A]        0
[B, C, D]  1
[E, F]     0
[G]        1
[H, I, J]  0
[K]        1

or Alternatively as:
Col1      Col2
[B, C, D]  1
[G]        1
[K]        1

Is there any way to achieve this using kql?
I have looked into using prev function but it only works if there is fixed number of rows for grouping everytime. but here I need to group n rows based on a value in column, but the groups need to separate every time the same value is started again.

A: Here you go:
datatable(Col1:string,Col2:long) [
  "A", 0,
  "B", 1,
  "C", 1,
  "D", 1,
  "E", 0,
  "F", 0,
  "G", 1,
  "H", 0,
  "I", 0,
  "J", 0,
  "K", 1
]
| serialize
| extend NewSession = (row_number() == 1) or (Col2 != prev(Col2))
| extend SessionId = row_cumsum(iff(NewSession, 1, 0))
| summarize Col1 = make_list(Col1) by Col2, SessionId
| project Col1, Col2

The output will be exactly what you wanted.
Note: I use serialize, but you can use order by as well - but you need at least one of them, so that the records will be ordered.


text:
Q: Extracting vector Probabilities from SparkR ML RF without coercing a SparkDataFrame into an R data.frame Check two relevant references
Extracting Class Probabilities from SparkR ML Classification Functions
and
sparkR 1.6: How to predict probability when modeling with glm (binomial family)
I'm just wondering whether there is any method to get these done without converting the SparkDataFrame back to an R data.frame via either as.data.frame or collect. Cuz it seems impossible when there is millions of data...


text:
Q: How do you define the natural numbers for different base systems? When we define the natural numbers through set theory does it matter how the numbers are represented?  For example, does the definition apply to a base 9 or base 16 system just like it would to a base 10 system?  Is the radix independent of the set theoretic definition of the natural numbers or should we somehow work that into the definition. I'm confused on what the natural numbers actually are like their ultimate structure versus how we represent them on paper.

A: No, it does not matter at all.
Natural numbers are not defined by their representation in base $10$, or in any base whatsoever. This comes a long way after numbers have been defined.
One common way of defining them is based upon set theory. Set theory provides the empty set and the possibility to make sets that include other sets; so a definition of integers is:
$0$ is the empty set $\{\}=\emptyset$
$1$ is the set $\{\emptyset\}$
$2$ is the set $\{\emptyset, \{\emptyset\}\}$
and more generally, the sucessor function $S$ is defined as
$S(n)=\{\emptyset,n\}$
Then the set of integers is defined as the smallest set that includes $0$ and its successors - which actually requires some axiom of infinity to make that work.
(I can remember when I was young, and my father explained this to me, and I thought "Oh, these mathematicians are just mad men" :-)).
Actually, this set-theoretic definition of natural numbers, being a recursive construction, explains why recurrence demonstration is so often used for properties on $\mathbb{N}$.
Defining integers by their representation in base $10$ would be more troublesome. We would certainly rather choose base $2$, but that would still be complicated. Think how you would define the successor of a series of $0$'s and $1$'s...
Similarly, real numbers are not defined by their decimal expansion, notably because you get the additional complication that the representation is not unique, i.e. $0.999999... = 1.00000...$.


text:
Q: Can't Find JS file in Console I am pretty new and I am trying to work with the GIPHY API, but I can not get my js file to be found in the browser.  I have tried to create a whole new repo and I got the same issue.  Can anyone help?
Here is my directory:
Image with error
Here is my HTML.  Can anyone Help?
Folder structure
When I look in the console I get the message:Failed to load resource: net::ERR_FILE_NOT_FOUND
There is teh GIPHY sample code in the file so it is not empty.

A: Your path is not correct you need to point to the exact location your file is.
Try with ../js/main.js instead of js\main.js

A: If you can make your source to be just the file name likemain.jsalone
It will make you avoid the mistake of js\main.js thus solving the issue

A: For the standard way, you should move your index.html file in the root of the project and then point your js file like this js/main.js instead of js\main.js


text:
Q: Data storage in C# WPF MVVM application, like Redux in Web application I am writing my first WPF MVVM desktop application in C#.
I have many years of experience in creating React apps with Redux.
When I select a warehouse from a list, I want to request the related articles from the database.
After that, when I type the article number in an input, It needs to get the article from the list I just requested.
When using redux in a React app, you can store the list with articles in the store.
But how can I achieve this kind of data storage in a C# desktop application?
I use a Symphony backend as REST API for the data in de desktop application.
I have searched the internet but fount nothing useful.
Can you help me with this?


text:
Q: open the user's client with attachment I have below code to send an email from browser client.

Send Mail

However, I am looking for an email app (Outlook) which should pop up with recipient, text and attachment. After that, all that is left to do for me is pressing "send" in my outlook.
I've been trying for a while, but I couldn't find a solution. Any help would be appreciated.

A: While Recipients, Subject and Body are supported in the RFC mailto url syntax and implemented by some clients (please note the correct encoding and escaping of special characters like spaces), Attachments are not supported at all.
That would be difficult also, how would you know which (local) file path to pick? Also, the client would open up a potential security risk.


text:
Q: Click event on element with negative z-index I have a parent element with partially transparent background. There is a child element inside of this element. And I need to show child element in the background of parent element, so I set z-index: -1 to child element.
Here is a codepen example: https://codepen.io/anon/pen/xpVbPa
The gray square is a child element. I need to handle click on it. How to do it? I tried to set pointer events: none on parent element, it does not work.

A: Use a pseudo element with a background and add pointer-events: none to it.
Codepen

function childClick() {
  alert('click!');
}
.parent {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  padding: 50px;
  position: relative;
}

.parent:after {
  content: '';
  background: url(https://image.ibb.co/fAYr5R/585e4ad1cb11b227491c3391.png);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
  pointer-events: none;
}

.child {
  width: 150px;
  height: 150px;
  background-color: gray;
  cursor: pointer;
  position: absolute;
}

A: The principle in solving this type of problem is not having the background on the parent of .child, but on a sibling:

function childClick() {
  alert('click!');
}
.parent {
  position:relative;
}
.frontground {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  padding: 50px;
  pointer-events: none;
  position: relative;
  background: url(https://image.ibb.co/fAYr5R/585e4ad1cb11b227491c3391.png)
}
.child {
  width: 150px;
  height: 150px;
  background-color: gray;
  cursor: pointer;
  position: absolute;
  margin: 50px;
}

In your case, the sibling can actually be a pseudo-element, but that might not always be possible.

A: Update your CSS. Set background to child's div :after
.child:after{
  width: 150px;
  height: 150px;
  background-color: gray;
  position: absolute;
  cursor: pointer;
  content:"";
  z-index: -1;
}
.child {
  width: 150px;
  height: 150px;
}


text:
Q: Marshal.StructureToPtr fails in module ntdll.dll I'll start with a bit of history: The issue I'm facing currently appeared suddenly without any changes to the code. Then disappeared in the same way after 3 days. Now it came back in a week and doesn't want to go away =).
I have code that works with printer - settings it's printer preferences to print documents in the specified way. I use local printer which points to TCP address of the network printer (it is common approach for such tasks as I know).
Here follows the code I use to load printer configuration from binary file (previously saved in the similar way). I give all source code with declarations of unmanaged functions calls, because have no idea what could cause the issue. The line that is braking my application (Windows Service):
Marshal.StructureToPtr(pInfo, pPInfo, true); //THIS LINE FAILS

and here is the whole code of a function:
public static bool LoadSettings(string printerName, string filepath)
{
    Logger.GetLog().WriteInformation(string.Format("Loading printer settings '{0}' for printer '{1}'", filepath, printerName), "PrinterSettingsStorage.LoadSettings()");
    bool success = false;
    try
    {
        if (!File.Exists(filepath))
        {
            return false;
        }

        IntPtr hPrinter;
        int bytes = 0;
        IntPtr pPInfo;
        IntPtr pDevMode;
        PRINTER_INFO_2 pInfo = new PRINTER_INFO_2();

        PRINTER_DEFAULTS PrinterValues = new PRINTER_DEFAULTS();
        PrinterValues.pDatatype = 0;
        PrinterValues.pDevMode = 0;
        PrinterValues.DesiredAccess = PRINTER_ALL_ACCESS;

        //retrieve the devmode from file
        using (FileStream fs = new FileStream(filepath, FileMode.Open))
        {
            int length = Convert.ToInt32(fs.Length);
            pDevMode = GlobalAlloc(0, length);
            for (int i = 0; i < length; i++)
            {
                Marshal.WriteByte(pDevMode, i, (byte)fs.ReadByte());
            }
        }

        //get printer handle
        OpenPrinter(printerName, out hPrinter, ref PrinterValues);

        //get bytes for printer info structure and allocate memory
        GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out bytes);
        if (bytes == 0)
        {
            throw new Exception("Get Printer Failed");
        }
        pPInfo = GlobalAlloc(0, bytes);

        //set pointer to printer info
        GetPrinter(hPrinter, 2, pPInfo, bytes, out bytes);

        //place the printer info structure
        pInfo = (PRINTER_INFO_2)Marshal.PtrToStructure(pPInfo, typeof(PRINTER_INFO_2));

        //insert the new devmode
        pInfo.pDevMode = pDevMode;
        pInfo.pSecurityDescriptor = IntPtr.Zero;

        //set pointer to new printer info
        Marshal.StructureToPtr(pInfo, pPInfo, true); //THIS LINE FAILS

        //update
        SetPrinter(hPrinter, 2, pPInfo, 0);

        //free resources
        GlobalFree(pPInfo);
        GlobalFree(pDevMode);
        ClosePrinter(hPrinter);

        success = true;
    }
    catch (COMException ce)
    {
        Logger.GetLog().WriteError(string.Format("COM error loading printer settings to printer: {0}", Marshal.GetLastWin32Error()), ce.StackTrace, "PrinterSettingsStorage.LoadSettings()");
    }
    catch (Exception e)
    {
        Logger.GetLog().WriteError(string.Format("Unknown error loading printer settings to printer"), e.StackTrace, "PrinterSettingsStorage.LoadSettings()");
    }
    finally
    {
        Logger.GetLog().WriteInformation(string.Format("Finish loading printer settings '{0}' for printer '{1}'. Success: {2}", printerName, filepath, success), "PrinterSettingsStorage.LoadSettings()");
    }
    return success;
}

[StructLayout(LayoutKind.Sequential)]
internal struct PRINTER_DEFAULTS
{
    public int pDatatype;
    public int pDevMode;
    public int DesiredAccess;
}

[StructLayout(LayoutKind.Sequential)]
internal struct PRINTER_INFO_2
{
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pServerName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pPrinterName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pShareName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pPortName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pDriverName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pComment;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pLocation;
    public IntPtr pDevMode;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pSepFile;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pPrintProcessor;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pDatatype;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pParameters;
    public IntPtr pSecurityDescriptor;
    public readonly Int32 Attributes;
    public readonly Int32 Priority;
    public readonly Int32 DefaultPriority;
    public readonly Int32 StartTime;
    public readonly Int32 UntilTime;
    public readonly Int32 Status;
    public readonly Int32 cJobs;
    public readonly Int32 AveragePPM;
}

[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GlobalFree(IntPtr handle);

[DllImport("winspool.Drv", EntryPoint = "GetPrinterA", SetLastError = true,
    CharSet = CharSet.Ansi, ExactSpelling = true,
    CallingConvention = CallingConvention.StdCall)]
private static extern bool GetPrinter(IntPtr hPrinter, Int32 dwLevel,
                                        IntPtr pPrinter, Int32 dwBuf, out Int32 dwNeeded);

[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA",
    SetLastError = true, CharSet = CharSet.Ansi,
    ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool
    OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter,
                out IntPtr hPrinter, ref PRINTER_DEFAULTS pd);

[DllImport("winspool.drv", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern bool SetPrinter(IntPtr hPrinter, int Level, IntPtr pPrinter, int Command);

[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true,
    ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool ClosePrinter(IntPtr hPrinter);

Symptoms:

*

*Service simply stops immediately exiting at the referenced line. No finally block execution, no exception caught.

*Windows event log contains error
Faulting module name: ntdll.dll, version: 6.1.7601.17725, time stamp: 0x4ec49b8f
Exception code: 0xc0000374
Fault offset: 0x000ce6c3
Faulting process id: 0x12dc
Faulting application start time: 0x01cdc71b9bf9b661
Faulting application path: C:\Program Files (x86)\MyServiceExePath.exe
Faulting module path: C:\Windows\SysWOW64\ntdll.dll
Report Id: 0eb45111-330f-11e2-be8e-005056975a30
My OS: Windows Server 2008 R2.
As I said, it reproduces constantly for some period of time and then once went away without any changes in the code. I have no idea what causes this issue and why is it so unstable. Hope there are people here, more expirienced with unmanaged code than me =).
Any ideas?

A:         //insert the new devmode
        pInfo.pDevMode = pDevMode;
        pInfo.pSecurityDescriptor = IntPtr.Zero;

        //Add by me
        Marshal.StructureToPtr(pInfo, pPInfo, false);
        //set pointer to new printer info
        Marshal.StructureToPtr(pInfo, pPInfo, true);

        //update
        SetPrinter(hPrinter, 2, pPInfo, 0);
        //Add by me
        Marshal.DestroyStructure(pPInfo, typeof(PRINTER_INFO_2));

        //free resources
        GlobalFree(pPInfo);
        GlobalFree(pDevMode);
        ClosePrinter(hPrinter);


text:
Q: Accessing characters with \symbol I'm trying to use the \symbol{} command to output UTF8 haracters, but I can't get access any characters higher than 0x7E
The following code just outputs a tilde.
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}

\begin{document}

\symbol{'176}
\symbol{'304}

\end{document}

I'm clearly missing something trivial here, but I have no idea what it is.
(If you're wondering why I need this, it's because I need to pass the text to an external program that will embed that text into an SVG, and the quote as in "{a} is part of the syntax and can't be used for umlauts in German.)
Any tips would be great!

A: You are using pdflatex (or latex) so all fonts are 8bit and have at most 256 characters \symbol takes a font slot not a unicode code point.
Even when it works, \symbol does not expand to a character usable in svg, it directly access the font for typesetting, just use ä it will write as an a-umlaut to the external file.


text:
Q: New to Oracle SQL developer I installed Oracle SQL developer on my personal computer.
I want to create my own tables in it and work on them.
But, when I try to make the basic connection, it gives an error below

"network adapter could not make the connection".

Can someone please give a detailed explanation about how can I create my own tables and what I should do to connect to some database?

A: You have to install Oracle database to create your own tables. You can download Oracle XE from this link.
For a detailed explanation about how to connect to a database, this tutorial comes first when you google it.

A: This answer is for windows user. And assume that you have installed oracle database, as answered.

*

*Open cmd: (win+r, input cmd, enter).

*run command:
sqlplus / as sysdba

*create a tablespace:
create tablespace <tablespace-name>

*create user:
Create user <username> identified by <password> default tablespace <tablespace-name> quota unlimited on <tablespace-name>;

*open oracle sql developer, and add a link with the information in step 4. Link type should be set as local! Link type should be set as local! This may be the direct answer to your question.

*Now you could run sql shell in sql developer.


text:
Q: DB2 via OLEDB in VB I've researched google and stackoverflow, but we are drawing blanks....we have a team using the same code to use IBMDADB2 driver with an olebconnection to connect to the companies DB2 database.  Half the team can connect fine, other half gets an error.  This is visual studio 2019, VB, framework 4.7.2
Basics of error is System.Data.OleDb.OleDbException (0x8004d01c): CLI0106E  Connection is closed.  SQLSTATe=08003 CLI0119E Unexpected System failure.  SQLSTATE=58004.
This occurs when trying to open the connection.
The machines where this fails on, can connect fine to the database using IBMS tool.
We've compared db2cli.ini and db2dsdriver.cfg files....They all seem to be the same.
Have also used db2md -i -w db2clpsetcp
It's just using OleDbConnection in framework 4.72
Product Version on System.Data is 4.7.3062.0
DB2Level output
DB21085I This instance or install (instance name, where applicable: "DB2") uses "64" bits and DB2 code release "SQL11055" with level identifier "0606010F". Informational tokens are "DB2 v11.5.5010.1723", "s2103171200", "DYN2103171200WIN64", and Fix Pack "1". Product is installed at "C:\PROGRA~1\IBM\SQLLIB" with DB2 Copy Name "DB2COPY1".
This is what i have, and it works on my machine
IBM Data Server Client - DB2COPY   version 11.5.5010.1723
Teammate has
IBM Data Server Runtime Client DB2COPY1 version 11.1.1011.1315
and doesnt work on her machine
**Added 08/22/2022 -  Teammate updated driver...matches mine, same error.


text:
Q: Django Rest Framework Multiple Nested Writable Serializers I am trying to implement multiple nested writable serializers using django rest framework. I have read the docs available http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations
I have been able to do this for one level nests but have a problem when there are multiple nests. For example, I have these 3 serializers:
class FarmerSerializer(serializers.ModelSerializer):
    dob = serializers.DateField(write_only=True)
    gender = serializers.CharField(write_only=True)

    farms = FarmSerializer(required=False, many=True)

    class Meta:
        ...

    def create(self, validated_data):
        # check if nested objects were provided, in particular farms
        farms = validated_data.pop('farms', None)

        farmer = Farmer(**validated_data)
        farmer.added_by_id = validated_data.get('added_by_id')
        farmer.save()

        if farms is not None:
            for farm in farms:
                new_farm = Farm.objects.create(farmer=farmer, added_by=farmer.added_by, **farm)

                # check for blocks -- fails
                blocks = farm.pop('farm_blocks', None)
                if blocks is not None:
                    for block in blocks:
                        FarmBlock.objects.create(farm=new_farm, added_by=farmer.added_by, **block)

        return farmer

class FarmSerializer(serializers.ModelSerializer):
    county = CountySerializer(read_only=True)
    county_id = serializers.UUIDField(write_only=True)

    farm_blocks = FarmBlockSerializer(required=False, many=True)

class FarmBlockSerializer(serializers.ModelSerializer):
    ...

I'd like to be able to post JSON that is nested and save all 3 levels i.e farmer, farms and farm blocks. It currently works when I'm saving the first 2 levels i.e Farmer and associated farms.
If it helps, here is the JSON structure I'm attempting to save:
[
    {
        "name": "Ashley King",
        "phone_number": "0765124764",
        "gender": "F",
        "dob": "1980-11-26",
        "national_id": "29719008",
        "farms": [
            {
                "name": "Big Farm 3",
                "farm_size": "18",
                "county_id": "5e208ba8-5f6c-4dac-a946-dada0c5250a2",
                "constituency": "Nakuru",
                "ward": "Town",
                "town": "Nakuru",
                "contact_name": "Winnie W.",
                "contact_phone_number": "0724301432",
                "farm_blocks": [
                    {"block_size": 4.56}
                ]
            },
            {
                "name": "Big Farm 4",
                "farm_size": "9.6",
                "county_id": "5e208ba8-5f6c-4dac-a946-dada0c5250a2",
                "constituency": "Nakuru",
                "ward": "Town",
                "town": "Nakuru",
                "contact_name": "Winnie W.",
                "contact_phone_number": "0724301432"
            }
        ]
    },
    {
        "name": "Dennis Wainaina",
        "phone_number": "0764578389",
        "gender": "M",
        "dob": "1988-11-26",
        "national_id": "27675654",
        "farms": [
            {
                "name": "Big Farm 6",
                "farm_size": "18",
                "county_id": "5e208ba8-5f6c-4dac-a946-dada0c5250a2",
                "constituency": "Nakuru",
                "ward": "Town",
                "town": "Nakuru",
                "contact_name": "Winnie W.",
                "contact_phone_number": "0724301432"
            },
            {
                "name": "Big Farm 5",
                "farm_size": "9.6",
                "county_id": "5e208ba8-5f6c-4dac-a946-dada0c5250a2",
                "constituency": "Nakuru",
                "ward": "Town",
                "town": "Nakuru",
                "contact_name": "Winnie W.",
                "contact_phone_number": "0724301432"
            }
        ]
    }
]

A: Maybe you could edit your create method, somewhat like this,
def create(self, validated_data):
    farms = validated_data.pop('farms', None)
    farmer = Farmer.objects.create(**validated_data)

    if farms is not None:
        for farm in farms:
            #pop farm_blocks before creating new_farm
            blocks = farm.pop('farm_blocks', None)
            new_farm = Farm.objects.create(farmer=farmer, added_by=farmer.added_by, **farm)
            #then create farm_bocks
            if blocks is not None:
                for block in blocks:
                    FarmBlock.objects.create(farm=new_farm, added_by=farmer.added_by, **block)

    return farmer


text:
Q: class file version is not the same java.version in Eclipse maven Here is my pom.xml.
As you see , I have the source/target set as 1.6 in maven compiler plugin . While my project property is set as java 1.7.
When i run mvn compile and then check the java class version via javap, i see a version number =51 which indicate the jre1.7.
Do i miss anything here  ?
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <encoding>UTF-8</encoding>
                <compilerVersion>1.6</compilerVersion>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
        <plugin>
    <plugins>


text:
Q: In predicate logic, are these four expression equivalances? (1) $\forall x P(x) \wedge \forall x Q(x)$
(2) $\forall x (P(x) \wedge Q(x)) $
(3) $\forall y (\forall x P(x) \wedge Q(y))$
(4) $ \forall y \forall x(P(x)\wedge Q(y))$
I'm sure that (1) and (2) are equivalance. I think (3) and (4) are the same as (1) and (2) as $$\forall x (B \wedge P(x)) \Leftrightarrow B \wedge \forall x(P(x)),$$ but was not sure.
Anyone have ideas about this?
Thanks!

A: Yes, all four statements are equivalent. They all express that every element of the universe satisfies both $P$ and $Q$.