text:
Q: QPainter and OpenGL native code in QOpenGLWidget class I am preparing a desktop application to draw some 2D plots. I am using C++: Qt 5 and visual studio 2013. I created a simple GUI and put myQOpenGLWidget in it. I am already drawing the plots, axes and ticks using my own openGl shaders. Everything works fine and now I want to add the description to my axes and ticks to make the graph possible to analysis. As in OpenGL itself there is no dedicated functions to render text, I came up with using QPainter object just to add the desired description to already created plot. And here are problems starting...
Here is my functions of my QopenGLWidget implementation:
void GLWidget::initializeGL() {
initializeOpenGLFunctions();
glEnable(GL_POINT_SPRITE);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

vertexShad = new QOpenGLShader(QOpenGLShader::Vertex);
fragmentShad = new QOpenGLShader(QOpenGLShader::Fragment);

bool flag = vertexShad->compileSourceFile(QString("vs.glsl"));
if (flag) printf("compiled vertex Shader\n");
flag = fragmentShad->compileSourceFile(QString("fs.glsl"));
if (flag) printf("compiled fragment Shader\n");
flag = program.addShader(vertexShad);
if (flag) printf("linked vertex Shader\n");
flag = false;
flag =program.addShader(fragmentShad);
if (flag) printf("linked fragment Shader\n");

program.link();
program.bind();
}

paintGL:
void GLWidget::paintGL() {
painter = new QPainter(this);

painter->beginNativePainting();
glViewport(0, 0, this->width(), this->height());
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
drawAxes();
glViewport(MARGIN, MARGIN, this->width() - MARGIN * 2, this->height() - MARGIN * 2);
glScissor(MARGIN, MARGIN, this->width() - MARGIN * 2, this->height() - MARGIN * 2);
glEnable(GL_SCISSOR_TEST);
  // here are the functions which use native openGL code
  // ...
  // disabling openGL settings
glDisable(GL_SCISSOR_TEST);
glDisable(GL_POINT_SPRITE);
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
glDisable(GL_BLEND);
painter->endNativePainting();

drawTicksValues(); // function that uses QPainter
painter->end();
 }

drawTicksValues:
void GLWidget::drawTicksValues() {
char * maxText = new char[4];
sprintf(maxText, "%d", maxY);
char * minText = new char[4];
sprintf(minText, "%d", minY);
painter->drawText(0, MARGIN, QString(maxText));
painter->drawText(0, height() - MARGIN, QString(minText));
painter->drawText(MARGIN, height() - MARGIN + 20, QString("0"));
painter->drawText(width() - MARGIN, height() - MARGIN + 20, QString(100));
}

main:
int main(int argc, char *argv[])
{
 QApplication a(argc, argv);
 QSurfaceFormat  format;
 format.setSamples(4);
 format.setDepthBufferSize(24);
 format.setStencilBufferSize(8);

 QSurfaceFormat::setDefaultFormat(format);
 SymmGaitModels w;
 w.show();
 return a.exec();
}

Unfortunately, when I run the code, with uncommented QPainter part, the axis and plots are cleared, only the numbers I paint with QPainter are shown. But if I comment the QPainter part, the plots and axes are drawed normally. Any suggestions how I can add the text with QPainter to my plot instead of clearing it?

A: I finally managed to get things work.
First of all, I had to change and set the format (you have to change it before widget is shown), for example in main function , before my app was shown
main:
int main(int argc, char *argv[])
{
 QApplication a(argc, argv);

 SymmGaitModels w;
   // GLWidget is my implemantation of QOpenGLWidget
 GLWidget* gl = w.findChild<GLWidget*>("OpenGLWidget");
 QSurfaceFormat  format;
 //format.setSamples(4);
 //format.setDepthBufferSize(24);
 //format.setStencilBufferSize(8);
   format.setProfile(QSurfaceFormat::OpenGLContextProfile::CompatibilityProfile);
 QSurfaceFormat::setDefaultFormat(format);

 gl->setFormat(format);
 w.show();
 return a.exec();
}

Moreover, I had to move all (even enabling and disabling things like blend, point_sprite etc, which caused my problems) of my openGL functions between
QPainter-> beginNativePainting()
 ...
QPainter->endNativePainting();

And I had to implement paintEvent function. I just put paintGL() expression there.
Now my functions look like that:
void GLWidget::initializeGL() {
 printf("autoFILL: %d\n",this->autoFillBackground());
 initializeOpenGLFunctions(); // this function has to stay in initializeGL
 // commented functions below has to be removed and put after beginNativePainting
     //glEnable(GL_POINT_SPRITE);
 //glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
 //glEnable(GL_BLEND);
 //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

   // shaders may be compiled and added here, but program has to be linked and built after beginNativePainting()
 vertexShad = new QOpenGLShader(QOpenGLShader::Vertex);
 fragmentShad = new QOpenGLShader(QOpenGLShader::Fragment);

 bool flag = vertexShad->compileSourceFile(QString("vs.glsl"));
 //bool flag = vertexShad->compileSourceCode(vertexShadSrc);
 if (flag) printf("compiled vertex Shader\n");
 flag = fragmentShad->compileSourceFile(QString("fs.glsl"));
 //flag = fragmentShad->compileSourceCode(fragmentShadSrc);
 if (flag) printf("compiled fragment Shader\n");
 flag = program.addShader(vertexShad);
 if (flag) printf("linked vertex Shader\n");
 flag = false;
 flag =program.addShader(fragmentShad);
 if (flag) printf("linked fragment Shader\n");
}

void GLWidget::paintEvent(QPaintEvent *e) {
 paintGL(); // still this, widget has to be now refreshed by widget->update()
 }

void GLWidget::paintGL() {
 painter = new QPainter(this);
 painter->beginNativePainting();
 //
 glEnable(GL_POINT_SPRITE);
 glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
 glEnable(GL_BLEND);
 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

 program.link();
 program.bind();
 //
 glViewport(0, 0, this->width(), this->height());
 glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
 glClear(GL_COLOR_BUFFER_BIT);
 drawAxes();
 glViewport(MARGIN, MARGIN, this->width() - MARGIN * 2, this->height() - MARGIN * 2);
 glScissor(MARGIN, MARGIN, this->width() - MARGIN * 2, this->height() - MARGIN * 2);
 glEnable(GL_SCISSOR_TEST);
 // methods using native openGL functions here
 glDisable(GL_SCISSOR_TEST);
 glDisable(GL_POINT_SPRITE);
 glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
 glDisable(GL_BLEND);
 program.disconnect();
 painter->endNativePainting();
 drawTicksValues();
 painter->end();
}

After adding paintEvent implementation, the openGL widget has to be now refreshed using widget->update().
Hope it will be helpful for other people who are struggling with using both QPainter and native openGL functions, as Qt doc seems to be a little shallow on this topic.
Thanks!
Adam


text:
Q: Enabling laravel 4 route to read slug instead of id I have the following route in laravel.
Route::get('/{id}', 'HomeController@profile')->where('id', '[0-9A-Za-z\-]+');

If id corresponds to id in a database, ex: site.com/23 then I am able to fetch results from database with that specific id. However, if I want to fetch something like a title slug ex: site.com/this-is-title then it won't work at all. I have no idea how to tell laravel to query based on anything other than an database id.
My controller is:
class HomeController extends BaseController{
        public function profile($company_slug){
        $result = Clients::all($company_slug);
        return View::make("home.profiles", compact("result"));
    }
}

Here is my template.
@extends("layouts.master")

@section("main-content")
<?php
   {{ $result->company_slug }}
?>

@stop

There is no output. If I do <?php var_dump($result) ?> I get NULL.
But as I said, if I pass an id site.com/32 then I get result from database a for that id.

A: You might use the route models:
Solution 1:
Route::bind('profiles', function($value)
{
    $records = Profiles::where('company_slug', $value)->all();

    if ( ! $records->count())
    {
        App::abort(404);
    }
    else
    {
        return $records;
    }
});

Route::get('{profiles}', 'HomeController@profile');

class HomeController extends BaseController
{
    public function profile($profiles)
    {
        return View::make("home.profiles")->with('profiles', $profiles);
    }
}

Solution 2:
Route::get('{slug}', 'HomeController@profile');

class HomeController extends BaseController
{
    public function profile($slug)
    {
        return View::make("home.profiles")
            ->with('profiles', Profiles::where('company_slug', $slug)->all());
    }
}

Docu is available here.

A: class HomeController extends BaseController{
    public function profile($company_slug){
        $result = Clients::where('company_slaug', '=', $company_slug)->get();
        if (empty($result)) {
            //not found
        }
        return View::make("home.profiles", compact("result"));
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add/modify HTML attributes through Flask? I have a button in html, let's say:
<button type="button">Button</button>

I wish to be able to disable this button through flask (for example after it has been pushed). What I would like to know is how I would add the disabled attribute onto the button. In other words, turning it into:
<button type="button" disabled>Button</button>

A: When you call return render_template('template.html', variables=values) at the end of your route, pass a boolean:
return render_template('template.html', var1=val1, var2=val2,..., button=button)

You can set the value of button in your route. Then in your jinja2 template, just put in a branch:
{% if button %}
<button type="button">Button</button>
{% else %}
<button type="button" disabled>Button</button>
{% endif %}

If you need the button to be disabled dynamically after the page is rendered, @ltd9938 is correct, you need javascript.
I read now you mean after it has been pushed, in which case, yes, you need javascript.


text:
Q: Why does my windows in Windows act weird when moving them fast? I am not able to ask a proper question because I have no idea what the thing I am asking for is called. Perhaps it's tearing but I'm very unsure.
For example, if I grab a window and drag it around on the screen rapidly, the window will seem to be duplicated everywhere.
I don't know how to explain it so here is a video: http://tinypic.com/player.php?v=ta4u8p%3E&s=8#.UvZ8tPl_v60

A: My guess would just be screen lag, or just the way humans see things. I mean you're just jerking the window around, if you do that with anything else in real life, you see "double". I think that may be the case, but most likely just some screen lag. Doesnt seem like a problem though, since I cant think of any reason to ever do that....


text:
Q: How do I run multiple configuration commands in Dell EMC OS10 with Paramiko? I am trying to run a series of commands to configure a vlan on a Dell EMC OS10 server using Paramiko. However I am running into a rather frustrating problem.
I want to run the following
# configure terminal
(config)# interface vlan 3
(conf-if-vl-3)# description VLAN-TEST
(conf-if-vl-3)# end

However, I can't seem to figure out how to achieve this with paramiko.SSHClient().
When I try to use sshclient.exec_command("show vlan") it works great, it runs this command and exits. However, I don't know how to run more than one command with a single exec_command.
If I run sshclient.exec_command("configure") to access the configuration shell, the command completes and I believe the channel is closed, since my next command sshclient.exec_command("interface vlan ...") is not successful since the switch is no longer in configure mode.
If there is a way to establish a persistent channel with exec_command that would be ideal.
Instead I have resorted to a function as follows
chan = sshClient.invoke_shell()
chan.send("configure\n")
chan.send("interface vlan 3\n")
chan.send("description VLAN_TEST\n")
chan.send("end\n")

Oddly, this works when I run it from a Python terminal one command at a time.
However, when I call this function from my Python main, it fails. Perhaps the channel is closed too soon when it goes out of scope from the function call?
Please advise if there is a more reasonable way to do this

A: Regarding sending commands to the configure mode started with SSHClient.exec_commmand, see:
Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko
Though it's quite common that "devices" do not support the "exec" channel at all:
Executing command using Paramiko exec_command on device is not working

Regarding your problem with invoke_shell, it's quite possible that the server needs some time to get ready for the next command.
Quick-and-dirty solution is to "sleep" shortly between the individual send calls.
Better solution to is to wait for command prompt before sending the next command.


text:
Q: Store javaScript variable value in PHP variable How can we have JavaScript variable value in PHP variable within the same page??
I have a JavaScript variable which have the JSON String and I want to store in PHP variable so that I can store it into database.
Is it possible??

A: You should write a php page accepting the JSON using post and save it to database.
In javascript when you are ready to save the JSON, send the JSON to the PHP page using AJAX. This is the way to save some client side data without using forms.
As explained in this answer
Send JSON data from Javascript to PHP?
or if its a form you can refer this answer to submit the serialised data with HTML form
How to pass JavaScript variables to PHP?

A: Use jQuery.
$.get('file.php?var='+variable);
Then in PHP $_GET['var'];


text:
Q: Rails 5 - Export to XL/CSV but through Associations I've been following this Railscast on CSV/Excel Export but I'm having a bit of an issue with the association logic.
CSV Confusion/Issue
In my Collection Model I have
class Collection < ApplicationRecord
  belongs_to :user
  has_many :card_collections
  has_many :cards, through: :card_collections

  def self.to_csv
    attributes = %w{name}

    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |collection|
        csv << attributes.map{ |attr| collection.send(attr) }
      end
    end
  end

  # validates :user_id, presence: true
end

CSV Export
name
Demo 2
HEHHEHEEHHE

name is the column name
Demo 2 is the first Collection
HEHHEHEEHHE is the second Collection
I need far more information, but once I get 'one' parameter I can go from there. But this isn't working.'name' will return the name of ALL collections, which isn't quite what I want at all, but I'm also trying to get information about the 'cards' in the collection (Referenced by cards_collection)
To give you an example - In console I would type:
c = Collection.last
c.cards.first.name and I would get the first cards name.
I'm unsure if I should be making this self.to_csv function in the Card_collections controller, the Cards controller or what. I'm found a lot of similar questions regarding CSV through associations but nothing that has led me to a solution
Excel Confusion
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://www.w3.org/TR/REC-html40">
  <Worksheet ss:Name="Card Collection">

      <Row>
        <Cell><Data ss:Type="String">Name</Data></Cell>
        <Cell><Data ss:Type="String">Text</Data></Cell>
        <Cell><Data ss:Type="String">Set</Data></Cell>
      </Row>
    <% @collection.card_collections.each do |collection| %>
      <Row>
        <Cell><Data ss:Type="String"><%= collection.card.name %></Data></Cell>
        <Cell><Data ss:Type="String"><%= collection.card.text %></Data></Cell>
        <Cell><Data ss:Type="String"><%= collection.card.set %></Data></Cell>
      </Row>
    <% end %>

  </Worksheet>
</Workbook>

Is a sample script - I actually have this wrapped in an 'each' because if they choose Excel I'll allow them to get one sheet per 'collection'.
To give you an idea of the relation, my Collection View looks like -

<%= notice %>

<%= @collection.name %>

Made By:

  <% if @collection.public %>
    <%= link_to @collection.user.name, {:controller => "users", :action => "show", :id => @collection.user.id} %>

  <% else %>
    Anonymous

  <% end %>

Total Cards: <%= @collection.card_collections.sum(:card_counts) %>
Distinct Cards: <%= @collection.card_collections.count %>

  <% @collection.card_collections.in_groups_of(3, false).each do |group| %>

    <% group.each do |card| %>

        <%= image_tag(card.card.image_url, class: "img-responsive") %>

          <%= link_to card.card.name, {:controller => "cards", :action => "show", :id => card.card.id }%>

<%= card_text_swap(card.card.text) %>

Set: <i class="ss ss-<%= card.card.set.downcase %> ss-3x ss-<%= card.card.rarity.downcase %>">
               <%= card.card.setName %>

Total in Collection: <%= card.card_counts %>

    <% end %>

  <% end %>

<%= link_to 'Edit', edit_collection_path(@collection) %> |
<%= link_to 'Back', collections_path %>

I struggled in making the view originally but finally got it working, and I'm trying to use the same logic in the Excel export, but it's not rendering properly. (Immediate nil errors, so I think this might be a failure on my part.)
Additional Info All of this is stored within ActiveDirectory, and being rendered to a view currently. Unsure what other information I should offer.
New Excel Issue
Collections_Controller
  def show
    @collection = Collection.find(params[:id])
    respond_to do |format|
      format.html
      format.csv { render text: @collection.to_csv }
      format.xls { send_data @collection.to_csv(col_sep: "\t") }
    end
  end

View
  <%= link_to "CSV", collection_path(format: "csv") %> |
  <%= link_to "Excel", collection_path(format: "xls") %>

CSV is now working - Excel is not.
Error Provided:
ArgumentError in CollectionsController#show
wrong number of arguments (given 1, expected 0)

A: "def self.to_csv" defines a class method. If you want to list cards for given Collection you need to define and call (in show method of your collections controller) an instance method.
So I changed your to_csv in the following way:
def to_csv
  attributes = %w{name}

  CSV.generate(headers: true) do |csv|
    csv << attributes
    cards.each do |card|
      csv << attributes.map{ |attr| card.send(attr) }
    end
  end
end

This is how to call to_csv in your controller:
class CollectionsController < ApplicationController
  def show
    @collection = Collection.find(params[:id])
    respond_to do |format|
      format.html
      format.csv { render text: @collection.to_csv }
    end
  end
end

for Excel:
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://www.w3.org/TR/REC-html40">
  <Worksheet ss:Name="Card Collection">

      <Row>
        <Cell><Data ss:Type="String">Name</Data></Cell>
        <Cell><Data ss:Type="String">Text</Data></Cell>
        <Cell><Data ss:Type="String">Set</Data></Cell>
      </Row>
    <% @collection.cards.each do |card| %>
      <Row>
        <Cell><Data ss:Type="String"><%= card.name %></Data></Cell>
        <Cell><Data ss:Type="String"><%= card.text %></Data></Cell>
        <Cell><Data ss:Type="String"><%= card.set %></Data></Cell>
      </Row>
    <% end %>

  </Worksheet>
</Workbook>

And generally when you want to access cards for given @collection just use cards relation and you will not need extra .card when you access attributes of given card.


text:
Q: Eclipse: Failed to initialize Monitor Thread: Unable to establish loopback connection I have Eclipse Indigo installed on Win7 64bit with the ADT plugin and Android SDK's installed.
An error occurs when I have my emulator open and I try to launch my test application:
Failed to initialize Monitor Thread: Unable to establish loopback connection

I have looked into this error and it most often appears to be a firewall issue but with the firewall turned off I still get the error. Would it have anything to do with me having another Eclipse based IDE installed (Aptana 3)?
Things I have tried so far:

*

*Turn firewall off

*changed ddms port to 8601

*checked localhost is set to 127.0.01

I'm running out of ideas so any help of suggestions would be appreciated.

A: No need to disable IPV6. Just force Eclipse to use IPV4.
Edit eclipse.ini and add the last line:
openFile
-vmargs
-Djava.net.preferIPv4Stack=true

A: Solution : turn off Teredo Tunneling Pseudo-Interface.
This probably converts IP4 to IPv6 addresses or something, resulting in an IPv6 address for your localhost (strange though, that a PING still results in IP4). Anyway, turning it off (Device manager > View > Show hidden devices > right click on Teredo > disable) solves the problem!
I found out by doing a ipconfig /all in the NON working situation. It showed :
Tunnel adapter Teredo Tunneling Pseudo-Interface:
Connection-specific DNS Suffix . :

Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface

Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0

DHCP Enabled. . . . . . . . . . . : No

Autoconfiguration Enabled . . . . : Yes

IPv6 Address. . . . . . . . . . . : 2001:0:5ef5:79fb:####:###:####:####(Preferred)

Link-local IPv6 Address . . . . . : fe80::3c47:###:####:#### (Preferred)

//edit : I guess it's technically a workaround untill Eclipse supports IPv6

A: Ahah!!
Finally fixed this one.
It was a problem I believe with my bigfoot killer network
So, here is what I did.
Open CMD as administrator ( Right click, open as administrator )
Type: "netsh winsock reset"
Restart the computer
When it comes up saying:
"Your LSP is not mapped correctly, would you like to re map it?"
Click "NO"
Then all is well..
Only now, I do have it asking me about LSP mapping each time I boot, this f

A: Was the same problem, tried everything and only completely deleted Java 7 and installed Java 6 JDK solved problem!

A: I had the same problem with my Killer Networks Wireless card N-1103. I found that installing the latest driver from their website cured it

A: It seems that Eclipse is blocked...
Go to command prompt and to /tools directory and type:
adb kill-server
adb start-server

Hope this helps...

A: Had the same problem here.  My problem was a firewall issue.  I use VirtualBox sometimes and found that the virtual machine's network adapter was the roadblock.  Disabling the virtual adapter in Windows device manager solved my issue.


text:
Q: Is there any way to see that $H= p^2 +x^2$ has level-spaced spectrum from the symmetry? I heard that Ken Wilson had an explanation of the level-spacing of the harmonic oscillator spectrum directly from the symmetry of $H$ under interchange of $p$ and $x$, without ladder operators or direct computation.
After some thought, I don't know what such an explanation may be.


text:
Q: how to compare sql results How to get the minimum from a query result ?
image of the query
i want the min of the [serving-num], is it possible ?

A: select min([serving-num]
from(
select count([Server-ID])[serving-num],[Server-ID]
from [In-Order]
where [Server-ID] in(
select Id
from Employees
where Fname='dima' or Fname= 'sami')
group by [Server-ID]
)t

the problem was all about the letter t i inserted in the last line.


text:
Q: Tensorflow: "iterating over `tf.Tensor` is not allowed" while trying to train a CNN with multiple inputs I'm trying to make a CNN that takes 3 pictures to make a prediction. Inside the neural net, the predictions from 3 neural networks are concatenated. I'm having difficulties giving it proper input. The example can easily be copy/pasted and ran.
The problem arises just before the call() method, where I'm trying to separate the input to send them into different neural nets. I tried multiple assignments, I tried, zip(), etc.
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
from tensorflow import keras as K
import numpy as np
from functools import partial

mnist = K.datasets.cifar10.load_data()

(xtrain, ytrain), (xtest, ytest) = mnist

train_indices = np.random.randint(0, 50_000, (100_000, 3))
test_indices = np.random.randint(0, 10_000, (20_000, 3))

train_inputs = xtrain[train_indices].astype(np.float32)/255
test_inputs = xtest[test_indices].astype(np.float32)/255

train_outputs = np.array(np.sum(ytrain[train_indices], axis=1) % 2 == 0, dtype=np.int32)
test_outputs = np.array(np.sum(ytest[test_indices], axis=1) % 2 == 0, dtype=np.int32)

x = tf.data.Dataset.from_tensor_slices(train_inputs).map(lambda x: tf.expand_dims(x, 1))
y = tf.data.Dataset.from_tensor_slices(train_outputs)

train_ds = tf.data.Dataset.zip((x, y))
test_ds = tf.data.Dataset.from_tensor_slices((test_inputs, test_outputs))

class MultiInputCNN(K.Model):
    def __init__(self):
        super(MultiInputCNN, self).__init__()
        custom_net = partial(K.applications.MobileNetV2,
                             input_shape=(32, 32, 3),
                             include_top=False,
                             weights=None)

        self.net1 = custom_net()
        self.net2 = custom_net()
        self.net3 = custom_net()

        self.concat = K.layers.Concatenate()
        self.pool = K.layers.GlobalAveragePooling2D()
        self.dropout = K.layers.Dropout(.5)
        self.dense = K.layers.Dense(2)

    def call(self, inputs, training=None, **kwargs):
        x, y, z = inputs[0]
        a = self.net1(x)
        b = self.net2(y)
        c = self.net3(z)

        x = self.concat([a, b, c])
        x = self.pool(x)
        x = self.dropout(x)
        x = tf.nn.sigmoid(self.dense(x))
        return x

model = MultiInputCNN()

model(next(iter(train_ds)))

OperatorNotAllowedInGraphError: iterating over tf.Tensor is not allowed: AutoGraph did not convert this function. Try decorating it directly with @tf.function.

A: here is my solution... if I understand correctly there are 3 modilenet (not 1 with shared weights, also in this case the code below is easy to modify)
class MultiInputCNN(K.Model):
    def __init__(self):
        super(MultiInputCNN, self).__init__()

        self.custom_net1 = K.applications.MobileNetV2(
                             input_shape=(32, 32, 3),
                             include_top=False,
                             weights=None)

        self.custom_net2 = K.applications.MobileNetV2(
                             input_shape=(32, 32, 3),
                             include_top=False,
                             weights=None)

        self.custom_net3 = K.applications.MobileNetV2(
                             input_shape=(32, 32, 3),
                             include_top=False,
                             weights=None)

        self.concat = K.layers.Concatenate()
        self.pool = K.layers.GlobalAveragePooling2D()
        self.dropout = K.layers.Dropout(.5)
        self.dense = K.layers.Dense(2)

    def call(self, inputs, training=None, **kwargs):
        x, y, z = inputs[0]
        net1 = self.custom_net1(x)
        net2 = self.custom_net2(y)
        net3 = self.custom_net3(z)

        x = self.concat([net1, net2, net3])
        x = self.pool(x)
        x = self.dropout(x)
        x = tf.nn.sigmoid(self.dense(x))
        return x

model = MultiInputCNN()

model(next(iter(train_ds)))

here the running example: https://colab.research.google.com/drive/1pYH7wExp_yglf_8vbszzvnuSHP9wZMv3?usp=sharing (I reduce n_sample to not run out of ram)


text:
Q: Jest unable to mock an api call successfully Unable to mock api call successfuly in Jest test
networkHelper,js
import axios from 'axios';

export const getOptions = (url, userKeys) => axios.get(`${url}value=${userKeys}`)
    .then((res) => res);

Test in jest is as follows:
options.test.js

const mockData = [
    { label: 'SEABROOK, 3028, VIC' },
    { label: 'SEABIRD, 6042, WA' },
];

jest.mock('axios');

describe('test api', ()=> {
    it('should resolve api call', async () => {
        axios.get.mockResolvedValue({data: mockData});

        const fetchOptions =getOptions('http://localhost:8080/options, 'seab');
        expect(fetchOptions.data).toEqual(mockData);
    }
})

If i run the above test, I get
Promise.pending()

and if i run as
await getOptions('http://localhost:8080/options, 'seab');

then I am getting network error.
I am unsure why this is happening , can someone please point out, what I am missing here. I dont want to make a network call, but with await its making a network call

A: Does it work if you add the missing close parenthesis?
it('should resolve api call', async () => {
  ...
}); // Missing close parenthesis here


text:
Q: Condensing python code for creating tkinter widgets I have a program that I'm designing to teach myself Python but have gotten stuck. I've run across a way to condense python code using % and a list of arguments to have it run as code and looping through the list of arguments until it's done, but can't seem to find it in the documentation or with Google, mostly because I can't figure out how to search for it (sadly it's pretty vague I know).
Mostly what I'm trying to do is prevent having to write approx. 300 lines simply for GUI buttons, labels, frames, ect. with very few changes between them.
Obviously the code is huge so it's all available at Github, github.com/kari-fox/MixxMaster. I'm looking for any kind of recommendations for condensing all of the GUI elements, mostly because I find myself copy/pasting any time I need to make minor changes to any of the similar pieces.

A: Thanks to Steven Summers in the comments for mentioning classes. I had no idea they were so powerful! I found this guide (https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/) and it made understanding and implementing classes work perfectly! That helped me cut out almost 100 lines of purely window-building code and let me do a few sneaky things besides. If anyone wants to see the full implementation check out the github link in the question.


text:
Q: Multiple Choice Answer Key in exam package at the end of document I think this is a follow up question to:
Print answer key to multiple choice questions
I am trying to create an answer key at the end of my exam class document where all the questions are multiple choice.  Thus, the correct answers are already encoded into the document, as \correctchoice instead of \choice.
What I want it to do is print a simple table at the end of the document with the question number in the first column followed by the letter of the correct answer (as indicated by \correctchoice).  I have gotten close, but the only answer stored is the last one.
I have been searching the similar questions, but the problem seems to be in storing the correct choice somewhere, along with the questionlabel and then retrieving it at the end.  I am one of those self-taught LaTeXers who cobbles together things I have found elsewhere.  This is what I have tried so far.  It has two problems, it makes every answer E and it doesn't automatically label the \correctchoice:
\documentclass[answers
]{exam}
\usepackage{forloop}

\makeatletter
\let\xa=\expandafter

\newcounter{numsolns}
\setcounter{numsolns}{0}

\newcommand\solu{%
  %Saves the parameter as a solution
  \stepcounter{numsolns}%
  %\showthe\c@numsolns
  \xa\xdef\csname soln-label-\roman{numsolns}\endcsname{\questionlabel}%
  \xa\long\xa\gdef\csname soln-\roman{numsolns}\endcsname{\thechoice}%
}

%The following is from the exam.sty with one change:
       \def\CorrectChoice{%
         \if@correctchoice
           \endgroup
         \fi
         \ifprintanswers
           % We can't say \choice here, because that would
           % insert an \endgroup:
           \begingroup \@correctchoicetrue
           \CorrectChoice@Emphasis
         \fi
         \item
         \do@choice@pageinfo
                \solu%
       } % CorrectChoice
       \let\correctchoice\CorrectChoice

\makeatother

\begin{document}

\begin{questions}
\question[5] Important Question 1
    \begin{choices}
    \choice 99
    \correctchoice 100 \solu
    \choice 50
    \choice 1
    \choice none of these
    \end{choices}

\vfill

    \question[5] Important Question 2.
\begin{choices}
\CorrectChoice 6 \thechoice  \solu
\choice 12
\choice 24
\choice 36
\choice none of these
\end{choices} \answerline \vfill

\end{questions}

\newcounter{loopcounter}
\setcounter{loopcounter}{0}

  \begin{center}
        \ifnum\arabic{numsolns}>0\relax
        \clearpage
        \vspace{1in}
    \begin{tabular}{|c|c|}\hline
    Question & Correct Answer\\\hline
     \forloop{loopcounter}{1}{\value{loopcounter} < \arabic{numsolns}}{%
    \csname soln-label-\romannumeral\value{loopcounter}\endcsname&
                \csname soln-\romannumeral\value{loopcounter}\endcsname \\\hline}
                                \csname soln-label-\romannumeral\arabic{numsolns}\endcsname&
                \csname soln-\romannumeral\arabic{numsolns}\endcsname \\\hline

    \end{tabular}
    \fi
    \end{center}
\end{document}

Thanks to the comments, I have a partially working example.
\documentclass[answers
]{exam}

%%%%The following sets up a box to save all the answer information into.
\newbox\allanswers
\setbox\allanswers=\vbox{}

\newenvironment{answer}
{%
  \global\setbox\allanswers=\vbox\bgroup%
  \unvbox\allanswers%
    \thequestion  \thechoice\\
}%
{%
  \egroup%
}

\newcommand{\showallanswers}{\par\unvbox\allanswers}
%%%%%%%%%%%%%%%%

\makeatletter
\let\xa=\expandafter

%The following is from the exam.sty with one change:
       \newcommand{\CorrectChoice}{%
         \if@correctchoice
           \endgroup
         \fi
         \ifprintanswers
           % We can't say \choice here, because that would
           % insert an \endgroup:
           \begingroup \@correctchoicetrue
           \CorrectChoice@Emphasis
         \fi
         \item
         \do@choice@pageinfo %
       } % CorrectChoice

\makeatother

%%%%%%%%%This interacts with the exam.sty to put the answer in the appropriate spot.
\newcommand{\corchoice}[1]{ \CorrectChoice  #1 \begin{answer}\end{answer} }
\let\oldCorrectChoice\CorrectChoice
\renewcommand{\CorrectChoice}{\oldCorrectChoice \begin{answer}\end{answer} }
\let\correctchoice\CorrectChoice

\begin{document}

\begin{questions}
\question[5] Important Question 1
    \begin{choices}
    \choice 99
    \corchoice{ 100}
    \choice 50
    \choice 1
    \choice none of these
    \end{choices}

\vfill

    \question[5] Important Question 2.
\begin{choices}
\corchoice{ 6}
\choice 12
\choice 24
\choice 36
\choice none of these
\end{choices} \answerline \vfill

\end{questions}

\begin{center}
  Here are the answers:
\end{center}
\showallanswers

\end{document}

There are several issues with this:

*

*I can't seem to change the \newenvironment to a \newcommand and it
    seems wrong to be using \begin{answer}\end{answer} as my way of
    loading the information into the box, but I can live with it.

*I can't seem to change the definition of \correctchoice to use the new environment.  I have tried hacks like
    \let\oldCorrectChoice\CorrectChoice, but nothing I try seems to
    work.  This may be because I am using the exam.sty and I am trying
    to do something impossible.

*In the event that (2) is impossible, I would really like to have a
command that doesn't take extra data as I have now with
    \corchoice{}, but when I try that, the \savebox is eating the \item number.

A: I started with the first answer to Showing Solutions of the Questions "separately" and modified it to something that is nearly exactly what I wanted.  It turns out that \item and \setbox don't play well with each other (read to the bottom of Missing Item number in enumerate for the details).
MWE:
\documentclass[answers]{exam}

%%%%The following sets up a box to save all the answer information into.
\newbox\allanswers
\setbox\allanswers=\vbox{}

\newenvironment{answer}
{%
  \global\setbox\allanswers=\vbox\bgroup %
  \unvbox\allanswers%
    \thequestion \thechoice\\
}%
{%
  \egroup%
}

\newcommand{\CC}{\CorrectChoice \leavevmode\begin{answer}\end{answer}}% New command \CC replaces \CorrectChoice from exam.sty and saves answers in the box \allanswers .

\newcommand{\showallanswers}{%
\ifprintanswers \centering Here are the answers: \par \usebox\allanswers \fi}

\begin{document}

\begin{questions}
\question[5] Important Question 1
    \begin{choices}
    \choice 99
    \CC 100
    \choice 50
    \choice 1
    \choice none of these
    \end{choices}

% \vfill

    \question[5] Important Question 2.
\begin{choices}
\CC 6
\choice 12
\choice 24
\choice 36
\choice none of these
\end{choices} \answerline %\vfill

\end{questions}

\showallanswers
% The answers have the same text format as the answers within the question, so are naturally \textbf when

\end{document}

The only thing that would make this better is to have the list of problem numbers and answers inside a tabular environment, but I am going to leave that for another day.


text:
Q: Intervals and sets I never took calculus until now, but as a stat major I have sometimes used the notation $x\in [a, b]$ as an alternative way of writing $a\leq x \leq b$. Does it make sense to express it like this, or is this incorrect? Or should I be using something like $\{x\in\mathbb{R} : a\leq x \leq b\}$?

A: One may want to distinguish two kinds of things:

*

*$x\in [a,b]$ and $a\le x\le b$ are statements about $x$. (They are the same statement written in different ways.)

*$[a,b]$ and $\{x\in\mathbb R: a\le x\le b\}$ are sets. (They are the same set written in different ways.)

It is very common to mix the notation, e.g., to talk about "the measure of the set $x\ge 2$". The meaning is usually clear from context. But personally,  I prefer not to use 1 when I mean 2.


text:
Q: How to remove Parent checkbox in pygtk I have created one Treestore in pygtk. Everything is fine only problem is, I don't want patent checkbox. you can see in below picture.
Computer1 [ ]-----This checkbox I don't want
    C drive [ ]
    D drive [ ]
    E drive [ ]

I have written code as,
self.view = gtk.TreeView( model )
self.renderer = gtk.CellRendererText()
self.renderer.set_property( 'editable', False )

self.renderer1 = gtk.CellRendererToggle()
self.renderer1.set_property('activatable', True)
self.renderer1.connect( 'toggled', self.col1_toggled_cb, model )

self.column0 = gtk.TreeViewColumn("Computer Name", self.renderer, text=0)

self.column1 = gtk.TreeViewColumn("Select Drive", self.renderer1 )
self.column1.add_attribute( self.renderer1, "active", 1)
self.view.append_column( self.column0 )
self.view.append_column( self.column1 )

self.tree_store = gtk.TreeStore( gobject.TYPE_STRING,
                                 gobject.TYPE_BOOLEAN )
for item in tasks.keys():
    parent = self.tree_store.append( None, (item, None) )
    if len(tasks[item])>1:
        for x in range(0,len(tasks[item])):
                self.tree_store.append( parent, (tasks[item][x],1) )
    else:
        self.tree_store.append( parent, (tasks[item][0],None) )

A: Expand your tree store to include a boolean that specifies whether the checkbox is to be visible, and connect the visible property of the checkbox renderer with the value in the tree store. You can do that by calling add_attribute:
self.column1.add_attribute( self.renderer1, "visible", 2)

...or by adding the keyword argument named like the property to the gtk.TreeViewColumn constructor. Here is a small runnable example demonstrating all of the above:
import gtk, gobject

tree_store = gtk.TreeStore(gobject.TYPE_STRING,
                           gobject.TYPE_BOOLEAN,
                           gobject.TYPE_BOOLEAN )
root = tree_store.append(None, ("Computer 1", False, False))
tree_store.append(root, ("C drive", False, True))
tree_store.append(root, ("D drive", True, True))

view = gtk.TreeView(tree_store)
renderer1 = gtk.CellRendererText()
renderer2 = gtk.CellRendererToggle()

view.append_column(gtk.TreeViewColumn("Computer Name",
                                      renderer1, text=0))
view.append_column(gtk.TreeViewColumn("Select Drive",
                                      renderer2, active=1, visible=2))
w = gtk.Window()
w.add(view)
w.show_all()
gtk.main()


text:
Q: $(...).sparkline is not a function (jQuery Sparklines) I'm currently running into an issue when using a package called jQuery Sparklines by Gareth Watts. Does anyone have any experience with this package? It seems to be pretty outdated but some people still use it here..
I am importing the package via script tag in a Flask view using regular ol' script tags:
<script src="/custom/css/JS/jquery-sparklines.js"></script>
And have checked the console to make sure jQuery is also installed and loaded before I load the script tag above.
I noticed the issue when I was trying to emulate the example jFiddle in the docs:
I was able to create a working version of the fiddle myself here but only by adding jQuery 1.9.1 on the extensions dropdown, and then toggling the "migrate 1.1.0" slider in the JS section.. pic here
Even with my example working somewhat, AND importing the same things in my html, the HTML doesn't pick up the custom jQuery function in the external code and get:
$(...).sparkline is not a function
Does anyone have any experience with this library? I've followed the docs but theres something i'm obviously missing.
SOS : ( or maybe reccomend other sparkline packages? : (
Thank you soooo much for your time!
UPDATE:
Still fails to recognize sparkline code with the cdn instead of downloaded files : (

A: Do not know why, but when I put the sparkline reference right before where I use it, the problem's gone.
It looks like:
<script src="~/Scripts/sparkline/jquery.sparkline.js"></script>
<script type="text/javascript">
    var $jq = jQuery.noConflict();
    $jq(document).ready(function() {
        $jq(".sparkline_bar").sparkline([5,6,7,2,0,-4,-2,4], {
            type: 'bar'});
        //Some other things.

A: Solved:
I had JS code that was conflicting with the sparklines code in the  tags to initialize the lines.
Fixed by simply initializing the lines FIRST before any other JS stuff.


text:
Q: PL/SQL XMLType operation performance I have a PL/SQL function to parse my XML block and return it into a VARCHAR variable.
My XML block is not too complex. Have only 14 tags and don't have any repeating structure.
Inside my function I made this XMLType operation:
SELECT    px_Header
                               || 'R5'
                               || RPAD (NVL (A1, ' '), 2)
                               || RPAD (NVL (A2, ' '), 10)
                               || RPAD (NVL (A3, ' '), 3)
                               || RPAD (NVL (A4, ' '), 1)
                               || RPAD (NVL (A5, ' '), 1)
                               || RPAD (NVL (A6, ' '), 10)
                               || RPAD (NVL (A7, ' '), 1)
                               || RPAD (NVL (A8, ' '), 8)
                               || RPAD (NVL (A9, ' '), 1)
                               || RPAD (NVL (A10, ' '), 16)
                               || RPAD (NVL (A11, ' '), 2)
                               || RPAD (NVL (A12, ' '), 8)
                               || RPAD (NVL (A13, ' '), 1)
                               || RPAD (NVL (A14, ' '), 1)
                               || CHR (13)
                               || CHR (10)
                          INTO lv_return
                          FROM XMLTABLE (
                                  '/IN_DATA'
                                  PASSING px_Block
                                  COLUMNS A1          VARCHAR2 (2) PATH 'A1',
                                          A2       VARCHAR2 (10)
                                                                     PATH 'A2',
                                          A3             VARCHAR2 (3) PATH 'A3',
                                          A4             VARCHAR2 (1) PATH 'A4',
                                          A5     VARCHAR2 (1)
                                                                     PATH 'A5',
                                          A6       VARCHAR2 (10)
                                                                     PATH 'A6',
                                          A7         VARCHAR2 (1)
                                                                     PATH 'A7',
                                          A8              VARCHAR2 (8) PATH 'A8',
                                          A9    VARCHAR2 (1)
                                                                     PATH 'A9',
                                         A10             VARCHAR2 (16)
                                                                     PATH 'A10',
                                          A11          VARCHAR2 (2)
                                                                     PATH 'A11',
                                          A12          VARCHAR2 (8)
                                                                     PATH 'A12',
                                          A13   VARCHAR2 (1)
                                                                     PATH 'A13',
                                          A14         VARCHAR2 (1)
                                                                     PATH 'A14');

This function takes 0.0945 seconds to perform. Not to so much, I think. But my process need to iterate 100000 times, so I call this function 100000 time.
Is there any faster way to implement this to improve, even if only a few thousandths of a second?

A: Combine XML and process one large document instead of many little documents.  This at least reduces the amount of context switches between SQL and PL/SQL, and
 probably allows Oracle to take advantage of other efficiencies as well.
Instead of processing one-row-at-a-time:
<IN_DATA><A1>1</A1><A2>2</A2></IN_DATA>

Process multiple rows:
<ALL_DATA>
    <IN_DATA><A1>1</A1><A2>2</A2></IN_DATA>
    <IN_DATA><A1>3</A1><A2>4</A2></IN_DATA>
</ALL_DATA>

With code like this:
--Process XML.
declare
    v_strings sys.odcivarchar2list;
    px_Block xmltype := xmltype('
        <ALL_DATA>
            <IN_DATA><A1>1</A1><A2>2</A2></IN_DATA>
            <IN_DATA><A1>3</A1><A2>4</A2></IN_DATA>
        </ALL_DATA>');
begin
    --Get strings.
    select A1||' '||A2
    bulk collect into v_strings
    from
    xmltable
    (
        '/ALL_DATA/IN_DATA' passing px_Block columns
        a1 varchar2 (2)  path 'A1',
        a2 varchar2 (10) path 'A2'
    );

    --Display strings for testing.
    for i in 1 .. v_strings.count loop
        dbms_output.put_line(v_strings(i));
    end loop;
end;
/

Results:
1 2
3 4

EDIT
If the documents cannot be combined, and if the input string is relatively simple and can be trusted, replacing the XML processing with string functions may significantly improve performance.
The example below uses a smaller input string, but changing from XML to string processing shrinks the time from 30 seconds to almost none.
--Process XML.
declare
    v_result varchar2(100);
    v_xml xmltype := xmltype('<IN_DATA><A1>1</A1><A2>2</A2></IN_DATA>');
    v_string varchar2(100) := '<IN_DATA><A1>1</A1><A2>2</A2></IN_DATA>';

    function get_string_from_xml(p_xml xmltype) return varchar2 is
        v_string varchar2(100);
    begin
        --Get strings.
        select A1||' '||A2
        into v_string
        from
        xmltable
        (
            '/IN_DATA' passing v_xml columns
            a1 varchar2 (2)  path 'A1',
            a2 varchar2 (10) path 'A2'
        );
        return v_string;
    end get_string_from_xml;

    function get_string_from_string(p_string varchar2) return varchar2 is
        v_string varchar2(100);
    begin
        return
            substr(p_string, instr(p_string, '<A1>') + 4, instr(p_string, '</A1>') - instr(p_string, '<A1>') - 4)
            ||' '||
            substr(p_string, instr(p_string, '<A2>') + 4, instr(p_string, '</A2>') - instr(p_string, '<A2>') - 4);
    end get_string_from_string;

begin
    --27 seconds
/*
    for i in 1 .. 100000 loop
        v_result := get_string_from_xml(v_xml);
    end loop;
*/

    --0 seconds
    for i in 1 .. 100000 loop
        v_result := get_string_from_string(v_string);
    end loop;
end;
/

Another way of looking at this is that your original function takes 2.5 hours to process 100,000 XML documents with a single thread.  That sounds quite reasonable.  Some simple parallelism should be able to shrink the time from hours to tens of minutes.


text:
Q: Change Gridview row value based on current date in asp.net C# I am not able to solve this. I want to check if the received date (DateOfRecd) is passed from current date, then it should be red.
But I cant. Please help me. My code is:
<asp:BoundField DataField="ItemTypeName" HeaderText="ItemTypeName" SortExpression="ItemTypeName" />
<asp:BoundField DataField="BrandName" HeaderText="BrandName" SortExpression="BrandName" />
<asp:BoundField DataField="ModelName" HeaderText="ModelName" SortExpression="ModelName" />
<asp:BoundField DataField="ItemSerial" HeaderText="ItemSerial" SortExpression="ItemSerial" />
<asp:BoundField DataField="DateOfRecd" HeaderText="DateOfRecd" DataFormatString="{0:dd-MMM-yy}" SortExpression="DateOfRecd" />

My C# Code is:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string v_ExpiryDate = (string)DataBinder.Eval(e.Row.DataItem, "DateOfRecd");
        string Test = DateTime.Compare(DateTime.Now, Convert.ToDateTime(v_ExpiryDate)).ToString();
        if (Test == "0")
        {
            e.Row.BackColor = System.Drawing.Color.Red;
        }
        else
        {
            e.Row.BackColor = System.Drawing.Color.White;
        }
    }
}

A: I highly doubt the value of Test will ever be 0. DateTime.Compare gives 3 possible values, -1, 0 and 1. It will be negative if T1 is smaller than T2 and 1 when T1 is bigger than T2.
The value will only be 0 when the two dates are the same and that is highly unlikely since DateTime.Now give you the time to the second. So if DateOfRecd is not accurate to the second the moment you open the page the GridView row will never be red.
I think you only want the Date part, not the hours and seconds. So use `DateTime.Now.Date'
string Test = DateTime.Compare(DateTime.Now.Date, Convert.ToDateTime(v_ExpiryDate)).ToString();

Or just compare the dates directly.
if (DateTime.Now.Date > ExpiryDate)
{
    e.Row.BackColor = System.Drawing.Color.Red;
}


text:
Q: Using $.length() to check for presence of
* not working I want to check if a list item already exists on the page before adding it.  My code below attempts to do this by checking the length of the ID for the list item.  However, no matter what my if statement always resolves to true.  Can someone tell me what the problem is?
function addSpotsToMarketTree(dmaName, spot) {
    var id = "#" + dmaName + "-spots";
    var liID = "#" + spot + "-" + dmaName;
    if ($(liID).length == 0) {
        $(id).append("
" + spot + "
");
    }
}

A: A direct copy of your code into jsFiddle seems to work as expected with a couple of assumptions about the IDs.  Are you sure you are building up the IDs correctly?
Edit
Looking again at your code, it looks like you are including the # in the ID of the created list item, meaning you are creating something like

This means that your selector will never match and so your if statement will always be true.
Live Demo

A: if ( ! $(liID).length ) {
    // the selector is empty
}

Double check to make sure your selector is good.

A: Your code is working just fine so my guess is your IDs are not coming across correctly. Set a breakpoint at your if statement (firebug of webkit dev tools) and see what your liID is.


text:
Q: homebrew how to use versions tap Following some online directions to install older versions of formulae, get this:
% brew tap homebrew/versions

Error: homebrew/versions was deprecated. This tap is now empty and all its contents were either deleted or migrated.

What does this mean and where have they migrated to/what to do now as its alternative?

A: The packages/formulae in tap homebrew/versions are merged into homebrew-core. If you wanna find an old version of a package. Just search it in the homebrew-core tap,
❯ brew search go
==> Formulae
algol68g                                  go@1.14                                   googler                                   mongo-orchestration
anycable-go                               go@1.9
...
go@1.10                                   google-benchmark                          libgosu                                   wireguard-go
go@1.11                                   google-java-format                        lunchy-go                                 write-good
go@1.12                                   google-sparsehash                         mongo-c-driver
go@1.13

Basically all old package are migrated as package@X.Y in homebrew-core.
BTW, homebrew-core is the default tap included after homebrew installation.


text:
Q: What should I do with ImageView when leaving an Activity? I'm running into some memory issues that are causing my app to crash. On my MainActivity, I have a large bitmap in an ImageView, but the crashes are happening when I'm in other activities that also have large bitmaps.
When leaving my MainActivity to go to another Activity, should I be setting my bitmap to null?
@Override
protected void onStop() {
    super.onStop();
    myImageView.setImageBitmap(null);
}

Or can I rely on Java GC to recycle the allocated memory for the bitmap?

A: Yes, if you are OK with reloading bitmap next time your activity is restarted, it is better to recycle it in onStop. Otherwise GC will not collect it - it is attached to a view, view is attached to the activity, why would GC recycle it?

A: Make sure you resize that bitmap to the smallest possible size that's still looking fine for the purpose you need. Also deploying it in each drawable-?dpi folder with proper resize for each is important, so the system doesn't scale up even more the already large bitmap you have. This approach solved my memory crash I had when using large images for some View backgrounds.
I don't think recycling the bitmap will ensure that the GC freed the memory in time before the second activity starts with its large bitmap/s.

A: Just before you call your other activities use the finish(); method. This will close the current activity and make the resources available.

A: I unbind all the views recursively using the method below. You should pass the root view and then all its childs will be cleaned. You can add more stuff to this method to recycle bitmaps, destroy webviews, clean listeners, etc!
public static void unbindDrawables(View view) {
    try {
        if (view != null) {
            if (view.getBackground() != null) {
                view.getBackground().setCallback(null);
            }
            if (view instanceof ImageView) {
                view.setImageBitmap(null);
            } else if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    unbindDrawables(((ViewGroup) view).getChildAt(i));
                }
                ((ViewGroup) view).removeAllViews();
            }
        }
    }
    catch (Exception e) {
        // some ViewGroups don't support the removeAllViews method
    }
}


text:
Q: How to Show a layout by just using MainActivity Context in Android I am making a library where I want to show a layout which actually tells either my mPos device is connected with Bluetooth or not. Connection code is in Library and connection call will be started from MainActivity.
Now Problem starts from here: I want to show some Layout or define the layout in my library. It's fine I can pass this or context of MainActivity to my Library.

To make it clear my Library code is not inheritable from Activity
  class

Please don't tell me you can make connection without the library. I just need to show a Layout inside my library and then I want to remove (pull) it, so my main activity becomes visible. It should be something NavigationController

A: I think you are looking at this the wrong way round.
You are thinking [My Project] - starts -> [Activity] and [My Project] handles everything the activity does.
In fact because the OS (Android) can only run Activities (not your project classes independently) it should be [Activity] - starts -> [My Project Service] which handles messages from activity.
When the project is set up like this, you can display the layout normally (as with any Activity). Your existing project classes can still be the ones making all the decisions, it's just started in the opposite order.
This is the same concept used for any cross-platform apps (eg libgdx): The app is a native wrapper (Activity) that runs your common code.
Edit:
When you just want to trigger something in the Activity when a method is called in your own class, you can use a callback interface:
public interface OnConnectionMadeListener {
     void onConnectionMade();
}

Your activity can implement it
public class MainActivity extends Activity implements OnConnectionMadeListener {

     private View mOverlay;

     public void onCreate() {
          ...
          mOverlay = findViewById(R.id.overlay);
          mOverlay.setVisibility(View.GONE);
          new MyConnectionObject(this); //this will be your class that has the madeConnection() method
     }

     ...

     public void onConnectionMade() {
         //show the overlay
         mOverlay.setVisibility(View.VISIBLE);
     }

}

Then inside your object
public class MyConnectionObject {

    private OnConnectionMadeListener mCallback;

    public MyConnectionObject(OnConnectionMadeListener callback) {
         ...
         mCallback = callback;
    }

    public void madeConnection()  {
        ...
        if (mCallback != null) {
            mCallback.onConnectionMade();
        }
    }
}

A: As you said, you've context there in that method. You can use System Level Alert to show full window layout over that activity. Your activity will be the host of that alert and will keep running below but user won't be able to see it because system alert view would have occupied the screen over it.
This is how you can show alert with context: https://stackoverflow.com/a/21182403/2105241
PS. It isn't a good solution to use system alerts :)

A: Create a static method in your library class. Create a context object, then with the static method accept the context and set accordingly. Now whenever you first call this library , call this method first and after that you can use the context object anywhere in your code. Tip do not declare the context as static, it will cause bad memory leaks.


text:
Q: SSIS Inserting incrementing ID with starting range into multiple tables at a time Is there are one or some reliable variants to solve easy task?
I've got a number of XML files which will be converting into 6 SQL tables (via SSIS).
Before the end of this process i need to add a new (in fact - common for all tables) column (or field) into each of them.
This column represents ID with assigning range and +1 incrementing step. Like (350000, 1)
Yes, i know how to solve it on SSMS SQL stage. But i need a solution at SSIS's pre-SQL converting lvl.
I'm sure there should be well-known pattern-solutions to deal with it.

A: I am going to take a stab at this. Just to be clear, I don't have a lot of information in your question to go on.
Most XML files that I have dealt with have a common element (let's call it a customer) with one to many attributes (this can be invoices, addresses, email, contacts, etc).
So your table structure will be somewhat star shaped around the customer.
So your XML will have a core customer information on a 1 to 1 basis that can be loaded into a single main table, and will have array information of invoices and an array of addresses etc. Those arrays would be their own tables referencing the customer as a key.
I think you are asking how to create that key.
Load the customer data first and return the identity column to be used as a foreign key when loading  the other tables.
I find it easiest to do so in script component. I'm only going to explain how to get the key back. I personally would handle the whole process in C# (deserializing and all).
Add this to Using Block:
Using System.Data.OleDB;

Add this into your main or row processing depending on where the script task / component is:
string SQL = @"INSERT INTO Customer(CustName,field1, field2,...)
               values(?,?,?,...); Select cast(scope_identity() as int);";

OleDBCommanad cmd = new OleDBCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = SQL;
cmd.Parameters.AddWithValue("@p1",[CustName]);
...
cmd.Connection.Open();
int CustomerKey = (int)cmd.ExecuteScalar(); //ExecuteScalar returns the value in first row / first column which in our case is scope_identity
cmd.Connection.Close();

Now you can use CustomerKey for all of the other tables.


text:
Q: Convert decimal to hexadecimal value I wrote C code to convert from decimal to hexadecimal, but i compile that one it show only the hexadecimal value of 10 to 15 that mean A to F. Please see my code below.
main()
{
    int n,r[10],i,d=0,e=1;
    printf("Enter the decimal number\n");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        r[i]=n%16;
        n=n/16;
        d=d+(r[i]*e);
        e=e*10;
    }
    i--;
    for(i=n;i>=0;i--)
    {
        if(r[i]==10)
            printf("A");
        else if(r[i]==11)
            printf("B");
        else if(r[i]==12)
            printf("C");
        else if(r[i]==13)
            printf("D");
        else if(r[i]==14)
            printf("E");
        else if(r[i]==15)
            printf("F");
        else
            printf("hexa decimal value %d\n",d);
    }
}

A: #include <stdio.h>

int main(void) {
  int n;

  if (scanf("%d", &n) == 1) {
    printf("hexadecimal: %x\n", n);
  }
  return 0;
}

A: Please format you code.
Perhaps this is a homework, but if you are just interested in the conversion, do it like this.
int decNum;
scanf("%d",&decNum);
print("%x\n",decNum);

A: Convert Decimal to Hexadecimal in C Language
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
    long int n,n1,rem;
    char *ans="\0",*ch;
    clrscr();
    printf("\nEnter Your Decimal No :: ");
    scanf("%ld",&n);

    n1=n;
    while(n>0)
    {
        rem=n%16;
        ch=NULL;
        sprintf(ch,"%s",((rem==10)?"A":(rem==11)?"B":(rem==12)?"C":(rem==13)?"D":(rem==14)?"E":(rem==15)?"F":"Z"));
        if(strcmp(ch,"Z")==0)
            sprintf(ch,"%ld",rem);
        strcat(ans,ch);
        n=n/16;
    }

    printf("\nYour Decimal No is :: %ld",n1);
    printf("\nConvert into Hexadecimal No is :: %s",strrev(ans));
    printf("\n\n\n\tThank You");
    getch();
}


text:
Q: When are .Net interfaces considered to be equivalent? I am writing code to implement a plug-in type of architecture.  I have defined an interface, let's call it IThing in the namespace MyStuff, for the plug-in and I also have code to dynamically create an instance of the plug-in from a DLL.  My code does this by looking through exposes classes, fields and methods and ultimately testing what it finds with:
if (typeof(IThing).IsAssignableFrom(instType))

This is all fine and works OK when the interface is implemented by something in my own code, i.e. referencing the assembly that provides the MyStuff.IThing definition.
Another developer, in another company located in a different country, is writing the pluggable component.
I sent the interface definition, i.e. the C# source, for MyStuff.IThing to the developer and he included it in his code.
The problem we saw first is that his component, even though it implemented MyStuff.IThing, would fail the above IsAssignableFrom test.  The reason for the failure seems to be that he has the interface definition in a different assembly (naturally), even though it has the same namespace and the interface definition has not changed.  The solution here is simple enough, which is that I send him the assembly DLL containing the interface.
My question is this:  given that the namespace matches and the interface definition is identical, why should it matter which assembly it is found in?  If assembly A contains MyStuff.IThing with exactly the same interface definition as MyStuff.IThing in assembly B, why are those assemblies not interchangeable for the purposes of an application that wants to work with an instance of MyStuff.IThing?

A:
given that the namespace matches and the interface definition is identical, why should it matter which assembly it is found in?

The choice of treating these interfaces as equivalent would make it harder to compare interfaces: rather than comparing a fixed set of items (i.e. the qualified name and the assembly) CLR would need to compare the qualified name, and the list of all properties and all methods, along with their argument types, which would be recursive. Doing so would be prohibitively slow, especially if you want to do it consistently and include classes and structs into a similar comparison scheme.
Note: when you share a DLL with the developer in another country, make sure that your assembly has a strong name. This would ensure that you both link to the same assembly, and detect mismatches early. For example, if you change your interface, but the other developer sends you a plug-in compiled with an old DLL, the plugin would fail to load.

A: .NET does not check the properties and their types and make a conclusion for equivalences.
In your case, the simplest way would be putting your interfaces in a class library and share that DLL with those who'd like to implement the interface.


text:
Q: How can I set IE 9 on Windows 7 Pro 64-bit to ALWAYS run as administrator? On other applications you just right-click the application shortcut, select properties, select the compatibility tab, and then select the option to run as administrator.
However, these options appear to be grayed out and unselectable on IE.
Thanks in advance.

A: Don't do this.
IE9 has taken many steps to be a more secure browser, and as such it shouldn't be run in Administrator mode, unless you're trying to resolve another particular problem.
If you look at the Compatibility Tab on the proper window it clearly states

Compatibility modes cannot be set on this program because it is part of this version of Windows.

So if you really wanted to change the Privilege Level you would have to circumvent some deeper in Windows.
You would be better off finding a work-around to the problem you think needs to be solved by always running in administrator mode.

A: I don't think you're looking in the right spot.
Go to the Shortcut tab and click the Advanced... button:

Then check the Run as administrator checkbox

You will still have to confirm the privilege elevation every time you use the shortcut.


text:
Q: What neural network topology is recommended to predict signals? Assumed I have gathered some measures of a complex system and I want to train a neural network to predict certain measure outcomes based on some simulated inputs, what ANN layout would you recommend?
The inputs are unbound FP numbers, i.e. 0 to infinity, the outputs are mixed, i.e. some are ranged FP, others are unbound - so part of the problem is to represent possible outcomes if inputs are outside of the training data space
A simple example of the kind of problem I am looking at:
Predict the fuel consume of a car based on recorded (speed,consume) tuples, where training data would be various between 0 to 150km/h,  and then querying the ANN with input 220km/h

A: I am not sure if you will be predicting several values or an actual signal. Because those are different problems.
If by several values you mean a continuous signal, I suggest the use of Reccurent Neural Networks (RNN) and/or Long Short Term Memory (LSTM). You should read on both and decide which suits your problem best.
As for predicting several values, I have never heard on a Neural network returning several values that are not homogeneous in type (this falls in the first suggestion). Therefore you will probably need to build a different model for each of your desired outputs.
I hope I understood your question, if not, feel free to edit and I will edit my answer accordingly.


text:
Q: How can I selectively apply CSS when an element doesn't have an ancestor with a certain class Trying to not overwrite some existing CSS in the codebase.
.my-new-class {
   .existing-class {
      ...some new styles
   }
}

.existing-class {
    ...some old styles
}

I've tried this, which I know doesn't work and I know why:
.existing-class {
 :not(.my-new-class) & {
    ...some old styles
 }
}

but I'm failing to figure out what (or if) there's a way of accomplishing what I want.
Basically, I only want styles to apply if a certain element doesn't have an ancestor (anywhere in the tree) with a certain class....or maybe there's a better way somebody can suggest?
Thanks SO!

A: Thanks to @Temani for telling me I needed a new approach. I'm going to answer my question for anybody else who might come across it.
I changed my HTML code so that I knew the position of .my-new-class in the ancestor tree (made it the second ancestor) so I was able to do this:
.my-new-class {
   .existing-class {
      ...some new styles
   }
}

.existing-class {
   &:not(.my-new-class)>*>& {
    ...some old styles
   }
}

HTML:

   ...with the old style

  <some-element>

      ...with the new style

  </some-element>


text:
Q: How to specify interaction beetween button click event handlers? In the program, by clicking button2, is created a table and imlemented data insertion. Also created textbox and login button, which is used for reading data from this textbox. When the login button is pressed, next actions should happen:

*

*MessageBox should display some text;

*login.Text should be changed;

*table, which was created by clicking button2 should be deleted.

I dont know actually how to get access from login.click event handler to table in button2. I guess it should be done somehow by using EventArgs, but i dont understand how. Also I thought about creating some variable outside button2 handler scope, and use it later, but I guess its a bad practise.
Please,tell me how to solve this, or maybe its just wrong decision to create windows forms components such a way? if it`s so, then how to?) here is my code:
    private void button2_Click(object sender, EventArgs e)
    {
        label1.Hide();
        label2.Hide();
        textBox1.Hide();
        textBox2.Hide();
        button2.Hide();

        int user_count = Int32.Parse(textBox2.Text);
        int file_count = Int32.Parse(textBox1.Text);
        DataGridView T = new DataGridView();
        T.Dock = DockStyle.Top;
        T.AutoResizeColumns();
        T.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        T.ColumnCount = file_count + 1;
        T.RowCount = user_count + 1;

        Controls.Add(T);

        Controller_cs c = new Controller_cs(user_count, file_count);

        for(int i = 1; i < T.RowCount; i++)
        {
           T.Rows[i].Cells[0].Value = c.user_name_insertion(i-1);
        }

        for (int i = 1; i < T.ColumnCount; i++)
        {
            T.Rows[0].Cells[i].Value = c.file_name_insertion(i - 1);
        }

        for(int i = 1; i < T.RowCount;i++)
        {
            for(int j = 1; j < T.ColumnCount;j++)
            {
                T.Rows[i].Cells[j].Value = c.rigts_insertion(j-1,i-1);
            }
        }

        Label l = new Label();
        l.Text = "Name";
        l.Left = 20;
        l.Top = 180;
        Controls.Add(l);

        TextBox username = new TextBox();
        username.Left = 20;
        username.Top = 210;
        Controls.Add(username);

        Button login = new Button();
        login.Text = "Enter";
        login.Left = 130;
        login.Top = 175;

        login.Click += login_handler;
        Controls.Add(login);
    }

    private void login_handler(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (b.Text == "Enter")
        {
            b.Text = "Exit";
            MessageBox.Show("Enter is done");
        }
        else
        {
            b.Text = "Enter";
            MessageBox.Show("Quit is done");
        }
    }


text:
Q: Is ASP.NET name-mangling consistent? When you have an ASP control like this:
<asp:TreeView ID="TreeItems" runat="server"></asp:TreeView>

The html that it generates mangles the names. If I want to access the ids of the generated items directly, I can try and figure out what it mangles the names to and look for that ID.
Are the names of the items generated guaranteed to be done in a specific way by whatever standard there is from Microsoft? I'm just afraid of this breaking if they release a new version of .NET that does it in a different way. Is there a way to generate the name mangling myself in code?

A: It isn't guranteed to be consistent (it's an implementation detail)
Use ClientID instead (which gives you the generated id).

A: I believe with ASP.NET on .NET 4, you can specify that the IDs be generated a certain way.
See: http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
Additionally, if you are using jQuery, you can be sure that the nominal ID will be in the client ID, so you could select it with something like:
$("input[id*='TreeItems']")

See: http://api.jquery.com/attribute-contains-selector/

A: If you want to use it in a client-side script, you can do the following:
<script type="text/javascript">
    //initialize client names of server side controls.
    var TreeItemsId = "<%= TreeItems.ClientID  %>";
</script>

When it renders out to the client it'll look like something like this:
<script type="text/javascript">
    //initialize client names of server side controls.
    var TreeItemsId = "ctl00_TreeItems";
</script>

A: No, it's not guaranteed to be consistent.
It should be consistent as long as the same version of the framework is used, but updates to the server may change this, so you shouldn't rely on knowing the generated name.
Use the ClientID property to find out the generated id of a control.


text:
Q: Getting null value in user control mvc I am trying to add user control for textbox having calender
My View
  @Html.Partial("~/Views/Shared/EditorTemplates/DateTime.ascx", "FromDate");

My User Control
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %>

<%= Html.TextBox(ViewData.ModelMetadata.PropertyName, new { @class="datepicker"} )%>

<script type="text/javascript">
$(document).ready(function () {
    $('.datepicker').datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'mm-dd-yy',
        showButtonPanel: true,
        gotoCurrent: true
    });
});

My Controller
[HttpGet]
    public ActionResult SetTask()
    {
        SetTask model = new SetTask();

        var data = (from d in edc.ProjectTBs
                    select d).ToList();

        model.ProjectList = new SelectList(data, "ProjectID", "ProjectName").ToList();
        model.ProjectList.Insert(0, new SelectListItem { Text = "--Select--", Value = "0" });

       // ModelState.Clear();

        return View(model);
    }

Error Message
Value cannot be null or empty.
Parameter name: name

Please help me for getting value passed from view to user control.
I want to use multiple time on same page of this user control.
If there is any other way to like this functionality also helpful.

A: Instead of Partial View use EditorFor.
Call it like this:      <%= Html.EditorFor(m => m.PropertyName) %>
Use this sample if you want in proper way.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>

 <%= Html.TextBox("", (Model.HasValue ? Model.Value.ToString("dd-MM-yyyy") : string.Empty), new { @class = "datepicker" }) %>

<script type="text/javascript">
    $(document).ready(function() {
        $('.datepicker').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'mm-dd-yy',
    showButtonPanel: true,
    gotoCurrent: true
});
    });
</script>


text:
Q: How to unset spy on document.getElementById created using jasmine.createSpy document.getElementById = jasmine.createSpy('HTMLElement').and.returnValue(null);

I am creating a spy to make document.getElementById return the required element in of one my tests. Due to document being global, this spy lives across the spec files. Is there a way to remove this spy and revert the getElementById to it's original implementation after the test executes?
Note: I am using new version of Jasmine and Karma which executes the unit test randomly (Random test execution is required). I am required to spy on getElementById in multiple spec files. If I set the return value to null in one of the test then even after resetting it to return valid dom element in other test, still it returns null in other test as well due to new random feature of Karma.

A: Yes, but you will need to use a different method to spy on document.getElementById.
Jasmine automatically removes spies created with methods like spyOn() (source).
So just change your code to:
spyOn(document, 'getElementById').and.returnValue(null);

and it should automatically remove the spy once the test completes.

A: Reset single spy call
spyOn(object, 'method');
expect(object.method).toHaveBeenCalled();
object.method.calls.reset();

Reset all spy calls
If you would like to reset all spy calls, then use:
spy.calls.reset()

Here is the documentation for it: https://jasmine.github.io/api/2.6/Spy_calls.html


text:
Q: How can I use a serial port to listen to if toggles are switched? In my software I need to detect when an operator toggles one of two miniature toggle electric switches:

and which one.
I want to do this with as little external hardware as possible.
I was thinking that maybe I could use a USB to serial cable?
Looking at the WaitCommEvent documentation I notice that I can listen to for instance:

*

*EV_CTS: The CTS (clear-to-send) signal changed state.

*EV_DSR: The DSR
(data-set-ready) signal changed state.

Looking at the DB-9 pins:

It seems that I could connect a voltage source trough the toggle 1 to pin 8 (CTS) and to ground?
Likewise it seems that I could connect a voltage source trough the toggle 2 to pin 6 (DSR) and to ground?
Will this work? Is there a better way to do this only using a USB to serial cable?

A: For the sake of sparing you the work of reposting to the electronics exchange:
According to this document, setting CTS on means a voltage of at least +3V on the CTS line, relative to GND. Similarly, setting CTS off means a voltage of at least -3V on the CTS line, relative to GND. So you'd need two voltage sources, one for >+3V (GND to Serial GND) and one isolated one for <-3V (Plus to Serial GND).
DSR functions similarly, according to the document.
Also, your switch looks like an SPST. You'd need at least an SPDT for this if you want to avoid using resistors.


text: Q: How to fix Error: The method 'ancestorStateOfType' isn't defined for the class 'BuildContext' I know, this question has already been asked, but there they always talk about something callec "bloc" and I have no idea what this is and I don't use it in my app. Anyways, since the latest update of flutter, I get this error Error: The method 'ancestorStateOfType' isn't defined for the class 'BuildContext'. and I don't know how to solve it. Has anyone an idea?


text:
Q: How create a query to show all functions and procedures to which I have access? SQL Oracle How can I write a query to show all functions and procedures to which I have access. Including the owner of the object as well.?
Oracle SQL.

A: SELECT *
FROM all_source
WHERE type in ('PROCEDURE', 'FUNCTION')
AND OWNER = ''; -- ENTER YOUR OWNER NAME HERE

Or maybe this is what you are looking for:
  SELECT *
  FROM dba_tab_privs
  WHERE TYPE IN ('PROCEDURE', 'FUNCTION')
  AND (GRANTEE = '' -- ENTER YOUR USER NAME HERE
       OR GRANTEE in (SELECT granted_role
                      FROM dba_role_privs
                      WHERE GRANTEE = '') -- ENTER YOUR USER NAME HERE


text:
Q: How to add FontAwsome Icon on HTML Button only using CSS? I have an HTML button with icon in text format ">". I want to replace this text ">" with any FontAwsome icon but I don't have access to HTML, JS and PHP. I can only apply CSS. How to add FA icon using only css?
HTML Code:
<button type="button" role="presentation" class="owl-next">></button>

CSS Code I try to write:
.owl-next {
     font-family: Font Awesome;
     font-weight: 900;
     content: "\f007";
}

Link of the web page where this HTML button is used: http://35.154.177.245:8080/cblibrary/

A: I found an example that shows exactly how to do something similar, hope it helps:

 Login

 TPS Reports

 Twitter

You just need to adjust the code to your needs but it works.
** Edit:
Make sure you add this after the  tags but before the  closing tag in order to get the FontAwesome icons:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/fontawesome.min.css

A: To Achieve this the icon on button you will have to use before Selector in CSS.
 .owl-next::before {
    font-family: Font Awesome;
    font-weight: 900;
    content: "\f007";
  }

Check this to See more examples


text:
Q: Styles are not taking in for no button When I change the color of the "no button" it's not changing.
When I debug it I found out that it is over written by some other color.
How can I fix it?
It's working for "yes button", but not working for "no button".
http://jsfiddle.net/VXXPC/15/

    eWaste

        <input name="Finish"
               style="width:70px; background-color:#0e6a91; height:24px;"
               value="Yes"
               type="submit" >
        <input style="width:70px; height:24px; background-color: #la4567;"
               name="Finish"
               value="No"
               type="submit" >

    Notes

        <textarea rows="3" cols="80" style="width: 280px;"></textarea>

A: You have a typo in the colour of the no button. You have #la4567. l (lower case L) is not a valid hex character. Did you intend for this to be a 1 (one)?
#1a4567


text:
Q: What does dojo.empty() / domConstruct.empty() do exactly Let's say I register some widgets with some ids(let's say id1, id2) in someNode. Now if I do, domConstruct.empty(someNode), this will remove the widgets from someNode by doing someNode.innerHTML= "". But are the widgets still in memory?
What I mean to say is, after domConstruct.empty(someNode), will I be able to register a widget with id1 or id2?
If not, then how can I achieve the same? I do not want to check for widget with same id during its creation and destroy it if it exists.
P.S: I am assuming that dojo.empty() and domConstruct.empty() work in the same way.

A: dojo/dom-construct's APIs do not know anything about Dijit widgets, so when you run domConstruct.empty(node) or domConstruct.destroy(node), it does nothing to look for and destroy widgets.  (I've explained how to do that in a largely-related question.)
When Dijit widgets are created, they are populated in a hash maintained by the dijit/registry module, which allows them to be accessed by ID (or node) in the future.  dijit/registry.findWidgets is also used by dijit/_WidgetBase#getChildren (which is in turn used by container and layout widgets) to retrieve child widgets according to the DOM tree.
Since dojo/dom-construct knows nothing of Dijit, it simply destroys all DOM nodes underneath the given node, and doesn't update Dijit's registry.  Thus, you end up with an inconsistent state, where Dijit thinks these widgets still exist, but their DOM has actually been destroyed.  As answered in the other question, you should use findWidgets to properly destroy the widgets first, or consider using a layout widget or ContentPane to manage the child widgets for you.


text:
Q: The formula that I have in my code which is causing the error is the formula that was given for the assignment //The error message I'm getting is saying "cannot find symbol- method second(double)
but I feel as though I have identified everything already. (I'm clearly wrong). I think there is a problem with the formula as well but that is the code I was given for the formula. Any help would be greatly appreciated.
    import java.util.GregorianCalendar;
    import javax.swing.JComponent;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Line2D;
    import java.awt.*;//import * Class

    public class ClockComponent extends JComponent
    {

        double hour;
        double minute;
        double second;

        public void setCurrentTime()
        {

            GregorianCalendar calendar = new GregorianCalendar();

            hour = calendar.get(calendar.HOUR_OF_DAY);
            minute = calendar.get(calendar.MINUTE);
            second = calendar.get(calendar.SECOND);
        }

        public void paintComponent(Graphics g)
        {
            Graphics2D g2 = (Graphics2D) g;

            int xCoord = 40;
            int yCoord = 25;

            Ellipse2D.Double clockFace = new Ellipse2D.Double(xCoord, yCoord, 700, 700);
            g2.setColor(Color.black);
            g2.draw(clockFace);
            g2.fill(clockFace);

            g2.setColor(Color.red);
            Font font1 = new Font("Old English Text MT",Font.BOLD,30);
            g2.setFont(font1);
            g2.drawString("John Doe", 305, 680);

            g2.setColor(Color.yellow);
            Font font2 = new Font("Arial",Font.BOLD,30);
            g2.setFont(font2);
            g2.drawString("III", xCoord + 670, yCoord + 355);
            g2.drawString("VI", xCoord + 340, yCoord + 685);
            g2.drawString("IX", xCoord + 10, yCoord + 355);
            g2.drawString("XII", xCoord + 340, yCoord + 35);

            int xCenter = 380;
            int yCenter = 380;

            double secondHandLength;
            double minuteHandLength;
            double hourHandLength;

            double xSecond = xCenter + secondHandLength; cos(second (2*Math.PI/60));
            double ySecond = yCenter - secondHandLength; sin(second (2*Math.PI/60));

            double xMinute = xCenter + minuteHandLength; cos(2*Math.PI/60);
            double yMinute = yCenter - minuteHandLength; sin(2*Math.PI/60);

            double xHour = xCenter + hourHandLength; cos(2*Math.PI/60);
            double yHour = yCenter - hourHandLength; sin(2*Math.PI/60);

            g2.setColor(Color.blue);
            Line2D.Double secHand = new Line2D.Double(xCenter,yCenter,xSecond,ySecond);
            g2.setStroke(new BasicStroke(1));
            g2.draw(secHand);

            Line2D.Double minHand = new Line2D.Double(xCenter,yCenter,xMinute,yMinute);
            g2.setStroke(new BasicStroke(7));
            g2.draw(minHand);

            Line2D.Double hourHand = new Line2D.Double(xCenter,yCenter,xHour,yHour);
            g2.setStroke(new BasicStroke(13));
            g2.draw(hourHand);
        }
    }

A: This probably isn't what you want:
(second (2*Math.PI/60))

Java is going to treat second as a method call, as it is immediately followed by an open-paren, with some value in it.  Since that function doesn't exist, Java produces that compilation error.
If you were trying to get the product of the two, you have to explicitly provide the multiplication operator.
(second * (2*Math.PI/60))

EDIT:  Now that I've had a moment to look at it, these statements also don't make sense:
double xSecond = xCenter + secondHandLength; cos(second (2*Math.PI/60));

Assuming the call to cos was valid, secondHandLength isn't defined anywhere.  What's more, you're dropping the result of your calculation on the floor, which isn't what you likely intend to do.  I'm not sure what a sane value would be for them, since they seem independent of the cosine of a circle, but those variables need to be defined.

A: I believe you are missing a multiplication symbol in the xSecond and ySecond calculation. Should be this:
        double xSecond = xCenter + secondHandLength; cos(second * (2*Math.PI/60));
        double ySecond = yCenter - secondHandLength; sin(second * (2*Math.PI/60));


text:
Q: How to resolve conflicting linker dependencies? If I have two libraries, A.lib and B.lib, both of which export foo and bar, how do I tell the linker to use the symbol foo from A.lib and the symbol bar from B.lib?

A: You cannot.  For your example you can have definitions from foo.lib or bar.lib but not both (especially if you cannot recompile the libraries and set symbol visibility so that only the symbols you want are exported).  The order you link them against your application will depend on which library's definitions are used (you'll have to use the scientific method, I think the first one linked wins).  Niklas Hansson's answer is a great way to do this dynamically but it seems you don't want to modify the original application, either, to dynamically pick/choose what symbols to take out of the libraries.
If you really wanted to you could mangle the symbol tables with a hex editor so that the symbols you don't want exported have different names (hacky, but it would work).  I know on Linux there is a tool called objcopy that would let you do this (not sure about Windows).

A: You can use LIB.EXE /EXTRACT ... to extract only the object files you want to use, and link those files into your own application.
Or you may use LIB to create one new library containing the elements you need:

*

*First, use /REMOVE on A.LIB to remove bar.obj:
LIB.EXE /OUT:ANOBAR.LIB /REMOVE:bar.obj A.LIB

*Then combine A.LIB and B.LIB, and make sure to use ANOBAR.LIB as the last on the command line to ensure its foo.obj is used instead of B.LIB's:
LIB.EXE /OUT:COMBINED.LIB B.LIB ANOBAR.LIB
Details are found here: Managing a library, especially the paragraph:

You can use LIB [...] To replace a library member with a new object, specify the library containing the member object to be replaced and the file name for the new object (or the library that contains it). When an object that has the same name exists in more than one input file, LIB puts the last object specified in the LIB command into the output library. When you replace a library member, be sure to specify the new object or library after the library that contains the old object.

I didn't test the command lines given, but I've used similar ones extensively in the past.

A: If you are using dynamic libraries, you could use dynamic loading and pick foo from A and bar from B when loading.


text:
Q: Grub issue in 12.04: "Booting in blind mode." I just turned on my PC where I'm dual-booting Ubuntu and Windows 8 and I had the following message at startup:
Invalid video mode 'text'
Booting in blind mode

Fortunately for me the laptop booted up fine anyways in blind mode and I was able to log in, however I've googled around and it turns out that this is an issue with Grub and it can be more serious in some cases.
Any idea on how to fix/correct this in a safe manner? Or what could I do to check that my Grub doesn't have any issues?

A: I found out what the problem was, apparently it has something to do with having Legacy Grub rather than Grub 2. Not sure whether is was UEFi that wasn't playing nice with it, but updating Grub to Grub2 using the following steps solved this issue and my laptop boots normally without the message:

*

*Open a terminal and run: sudo apt-get install grub-pc

*Accept when a pop-up window asks whether to chainload to Grub2 or not:

*I accepted adding all the boot menu entries seeing as my system booted correctly before

*Select the correct drive where to install Grub 2. Selected by using the arrow keys and Spacebar to highlight the drives to install it on, tabbing to the <OK> before pressing enter once done.

    5. Then reboot by using sudo reboot. On reboot you are queried whether to chainload or not:

Once I checked that all my Grub entries worked correctly in Grub2 by rebooting to test each of them I upgraded Grub to Grub2 using sudo upgrade-from-grub-legacy in a terminal window.
I'm not sure if this is just a workaround but at least my problem seems to be solved for the time being.
Sources of information/screenshots:

*

*Ubuntu Community Site on upgrading to Grub2

*UnixNewbie Explanations on how to upgrade to Grub2


text:
Q: Microsoft USD - The newer version of USD comparision I am currently working on USD 1.0 which is of-course a very old version of USD.
We are trying to move to the newest version of USD in my organization, which i believe is USD 4.0
I have tried searching the web but other than the MSDN article i have been able to gather much detail on this version.
I am trying to figure out my possibilities in trying to adapt to this newer version. In light of it, i have a few questions listed below,

*

*Has Microsoft released only the preview/trial version of USD 4.0 yet? Or is it made available for general public which means we can access and start developing in our production environment?

*Is the new version of USD, a web based version? I have heard that
this version is not the desktop application like it was before.

*Will it be safe to migrate from USD 1.0 to USD 4.0?

*Microsoft has also introduced Unified Client Interface, what is it?
Is it available only with USD 4.0?

*Features comparison with USD 1.0?

*If Microsoft have released the preview version only, then when will
they release the stable version? (any tentative date)?
Also, if they have released the preview version just then obviously they might change it in future. Therefore, it will not be wise enough to migrate to it if it is just a preview version.
Looking forward to your answers. Any sort of videos, articles, documentations, press releases, your personal opinions are welcome.
Thanks

A: Most 'manual' based MSDN information has been moved to Microsoft Docs: https://learn.microsoft.com
USD 4.x is still a desktop application that loads MSD components. You can upgrade to a more recent version 3.2 quite easily:
You can upgrade a Unified Service Desk 1.x or Unified Service Desk 2.0 sample application package to Unified Service Desk 3.2 by importing the Upgrade sample application package. The upgrade will not affect the configuration data associated with the existing solution.
Follow the steps here:
https://learn.microsoft.com/en-us/dynamics365/customer-engagement/unified-service-desk/admin/upgrade-unified-service-desk-solution?view=dynamics-usd-3
From there on forward it is much more easy to compare 3.x with 4.x and answer all your remaining questions.
Neil Parkhurst also has a ton of information.
https://neilparkhurst.com/2016/06/20/usd-the-book/


text:
Q: How to hide LOGO using CSS code in Qualtrics Survey? I want to hide my company LOGO from the last page of survey using CSS in LOOK & FEEL of Qualtrics Survey. I'm using the below code:
#Logo{display: none;}

This code hides the LOGO from all the pages of the survey. Is there a way to modify this code to hide the LOGO just from the last page of my survey.
This is how the look & feel of Qualtrics looks like:

A: You add a class next to logo in the last page, like this:

...

and in your css add display: none just to this page like this:
.last-page { display: none; }

or:
.last-page { visibility: hidden }

visibility: hidden hide the logo but consume the space

A: Use a unique ID, e.g. last, in your HTML such that you can target it using CSS like so:

Content

Then, target the last id in your CSS:
#last{
  display:none;
}

A: Remove the CSS that hides the logo from the Look & Feel Custom CSS.  Add the following to the question text of a question on the last page of the survey in HTML View:


text:
Q: Ionic - EACCES (Permission denied) error when uploading video I'm having some difficulties trying upload video file to server using Cordova Camera Plugin and cordova-plugin-advanced-http. The code works like a charm when uploading an image from gallery, but no matter what I do, I always receive EACCES (Permission denied) when uploading a video from gallery:
file url ->  file:///storage/emulated/0/DCIM/Camera/VID_20200908_114957.mp4
post-post-module-es2015.js:240 {status: -1, error: "There was an error with the request: /storage/emulated/0/DCIM/Camera/VID_20200908_114957.mp4: open failed: EACCES (Permission denied)"

Looking only at the error message, we can conclude it's a permission issue, so I tried use cordova-plugin-android-permissions and request READ_EXTERNAL_STORAGE permission. No success, the app has the permission but the error remains the same.
This is part of the code used to upload
private chooseContentUsingCameraPlugin(SOURCE: number) {
    const options: CameraOptions = {
        destinationType: this.camera.DestinationType.FILE_URI,
        mediaType: this.camera.MediaType.ALLMEDIA,
        sourceType: SOURCE
    };
    this.camera.getPicture(options).then((contentUrl: string) => {
        if (contentUrl.indexOf('://') === -1)
            contentUrl = 'file://' + contentUrl;
        const queryIndex = contentUrl.lastIndexOf('?');
        if (queryIndex !== -1)
            contentUrl = contentUrl.substring(0, queryIndex);
        console.log('file url -> ', contentUrl);
        this.startUpload(contentUrl);
    }, (err) => this.onUploadError(err));
}

private startUpload(fileUrl){
    ...
    this.nativeHttp.uploadFile(req.url, null, headers, fileUrl, fileName).then(res => {
        let data = res.data;
        if (res.data && (req.responseType === undefined || req.responseType === 'json'))
            data = JSON.parse(res.data);
        console.log(data)
    }).catch(error => {
        console.log(error)
    });
}

can someone explain what could be causing this issue?

A: It's possible that the file you're trying to upload is not in the scope of your permission. This is what the documentation says:

This is a soft restricted permission which cannot be held by an app it its full form until the installer on record whitelists the permission. Specifically, if the permission is whitelisted the holder app can access external storage and the visual and aural media collections while if the permission is not whitelisted the holder app can only access to the visual and aural medial collections. Also the permission is immutably restricted meaning that the whitelist state can be specified only at install time and cannot change until the app is installed. For more details see PackageInstaller.SessionParams.setWhitelistedRestrictedPermissions(Set).