text:
Q: How to create a socket on a 2nd NIC card? I'm trying to create a server on a secondary network in our office which is connected to a 2nd NIC card in my PC.  I haven't had any luck finding a solution on the internet.
Is there a way to direct Qt to use that NIC card?
In my project, here's the code that starts the server.  If mIP is on the first NIC card, this code works, if on the second NIC card, the listen() errors out.
void MyServer::run()
{
    QHostAddress serverAddr( mIP );
    QTcpServer server;

    mUi->lineEdit_ServerConnectionStatus->setText("Running");

    if (server.listen(serverAddr, mPort))
    {
        ...

Thanks,
Joe B.


text:
Q: Uploading a image to html page using html and javascript I am trying to upload an image in html page using the <input type="file"> element. I want to use the uploaded image to replace another image on the page. However, the control does not pass onto the java script function. Am trying to find out why the control does not pass. Below is the code I am using:
Upload a Picture</label

   <form name="image1"  enctype="multipart/form-data" action="/" method="POST" onsubmit="return UploadPic()">
      <input type="file" name="imgfile"></input>
   </form>

Thanks in advance.

A: You can't intercept a file upload in Java Script. The file has to be uploaded to the server, and then the page has to be rerendered

A: One approach would be using AJAX to query the backend on where the image was uploaded.
Like so
var pullImage = function()
{
  // do ajax work
  return image ? propagateHTML('element', image.uri) : fallback();
}

var propagateHTML = function(id, uri)
{
  document.getElementById(id).innerHTML = uri;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: PL/SQL extract SELECT statement column names from custom query I have a custom query and I need to know how to extract colum names from this. I've already searched for any way to do it:

*

*Regex: I've build this one to get more or less what I want but it won't work (I'm using Toad 12.6.0.53).

This is the code I have tried to test my regex:
DECLARE
  v_SQL VARCHAR2(32767 CHAR);
  v_Result VARCHAR2(32767 CHAR);
BEGIN
  v_SQL := 'SELECT
  ALIASBASE.CDCMPANY,
  ALIASBASE.PAFCODCTR,
  ALIASBASE.PAFDTSCAD,
  NUMFLUSSO.NUMERO,
  ALIASBASE.PAFDESC,
  ALIASBASE.PAFTYPE,
  ALIASBASE.PAFNATURE,
  ALIASBASE.PAFRECEIV,
  ALIASBASE.PAFCAUSAL,
  ALIASBASE.PAFCODDNE,
  ALIASBASE.PAFMATURITY
  FROM ALBSIAE';

  BEGIN
    SELECT
      REGEXP_SUBSTR (v_SQL, '(?:\s*(?=\w+\.|.*as\s+|)(\*|\w+)(?=\s*(?=,|from)))',1, NULL,'i') REGEX_RESULT
    INTO
      v_Result
    FROM DUAL;
  END;

  DBMS_OUTPUT.put_line('v_Result: ' || v_Result);
END;

But ant the end the v_Result is empty.

*

*Another way is to loop between my table columns,as I've seen here and here, but I think is not my case.

So, I want to know if is there any other way to do this, am I wrong with the regex? Is something wrong in it? Does Oracle have other regex syntax?

A: You can parse the statement with DBMS_SQL.parse and get the columns with  DBMS_SQL.describe_columns:
DECLARE
  v_SQL VARCHAR2(32767 CHAR);
  v_Result VARCHAR2(32767 CHAR) := '';
  l_cursor        PLS_INTEGER;
  l_col_cnt       PLS_INTEGER;
  i               PLS_INTEGER;
  l_desc_tab      DBMS_SQL.desc_tab;
BEGIN
  v_SQL := q'[SELECT 1 as "MY_NUMBER", 'z' as "MY_CHAR" from dual]';
  l_cursor := DBMS_SQL.open_cursor;
  DBMS_SQL.parse(l_cursor, v_SQL, DBMS_SQL.native);
  DBMS_SQL.describe_columns(l_cursor, l_col_cnt, l_desc_tab);

  FOR i IN 1 .. l_col_cnt LOOP
    v_Result := v_Result ||' ' || l_desc_tab(i).col_name;
  END LOOP;

  DBMS_OUTPUT.put_line('v_Result: ' || v_Result);

END;
/


text:
Q: PHP MYSQL - UPDATE user profile with SESSION I'm trying to update user profile with session. Suppose, the user profile page will update accordingly to the profile of the logged in user. Here's the sample code of user_profile.php:-
<?php
 session_start();
 ob_start();

 include("../function/dbconnect.php");
 include("header.php");
?>

<?php
if(isset($_SESSION['VALID_USER'])){

if(isset($_POST['submit']))
{
    $username = $_POST['username'];
    $password = $_POST['password'];

    $s=mysql_query("UPDATE tbl_staffs SET username='$username', password='$password' WHERE username='".mysql_real_escape_string($_SESSION["VALID_USER"])."'");

    if ($s)
        { echo ""; }
    else
        { echo ""; }
}

$query1=mysql_query("SELECT * FROM tbl_staffs WHERE username='".mysql_real_escape_string($_SESSION["VALID_USER"])."'  AND user_levels = '".mysql_real_escape_string('1')."'");
$query2=mysql_fetch_array($query1);

?>

<form  action="user_profile.php" method="POST">

Your  Profile

Username:

<input type="text" name="username" value="<?php  echo $query2['username'];  ?>" />

Password:

<input type="text" name="password" value="<?php  echo $query2['password'];  ?>" />

<input type="submit" name="submit" value="Update" />
</form>

<?php
//  close  while  loop
}}
?>

<?php
//  close  connection;
mysql_close();
?>

The page returns blank. There are several other codes that I'm working on for the user_profile.php page too but, the results that I get are the same... I used below codes for admin to update user profile.
include('function/dbconnect.php');
        if(isset($_GET['id']))
        {
            $id=$_GET['id'];
                if(isset($_POST['submit']))
                {
                    $username   = $_POST['username'];
                    $email      = $_POST['email'];
                    $password   = $_POST['password'];
                    $user_type  = $_POST['user_type'];
                    $query3     = mysql_query("UPDATE tbl_staffs
                                              SET username='$username', email='$email', password='$password', WHERE id='$id'");

                    if ($query3)
                        { echo ""; }
                    else
                        { echo ""; }
                }

    $query1=mysql_query("SELECT * FROM tbl_staffs WHERE id='$id'");
    $query2=mysql_fetch_array($query1);

 <form method="post">

    Username:	<input type="text" name="username" style="width:255px" value="<?php echo $query2['username']; ?>" />

    Email:	<input type="text" name="email" style="width:255px" value="<?php echo $query2['email']; ?>" />

    Password:	<input type="text" name="password" style="width:255px" value="<?php echo $query2['password']; ?>" />

        <input type="submit" name="submit" value="Update" />

  </form>
  <?php
    }
  ?>

Apparently, it works fine as it is. Though, when I tried to imply the codes for user so that they can update their own profile, the codes won't work. Where am I doing it wrong?

A: first check your session is exist or not and then replace ".mysql_real_escape_string($_SESSION["VALID_USER"])." in your query by a variable like
$VALID_USER=mysql_real_escape_string($_SESSION["VALID_USER"]);

if(isset($_POST['submit']))
{

$username = $_POST['username'];

$password = $_POST['password'];

$s=mysql_query("UPDATE tbl_staffs SET username='$username', password='$password' WHERE username='$VALID_USER");

if ($s)
    { echo ""; }
else
    { echo ""; }
}

 $query1=mysql_query("SELECT * FROM tbl_staffs WHERE username='$'  AND user_levels = '".mysql_real_escape_string('1')."'");
$query2=mysql_fetch_array($query1);


text:
Q: Populate multiple select box based on selection from a previous select list I have quite a complex problem that I cannot seem to solve.
I have an Input text box field that populates a select list, when the user inputs a certain 'term' in the textbox.
For example:
- If a user inputs the word 'Mercedes' in the text box, the select list will be populated with 'A-class', 'B-class', 'C-class', 'S-class'
- If they enter 'Audi' in the text box, the select list is populated with 'A4', 'A5', 'A6' etc.
This so far behaves the way in which I intended it to. However, I would like to create a
 below that is dynamically populated with the corresponding selected vehicle's accessories, when a user selects a model from the the select list.
Here is the code I have so far:
HTML

Manufacturer:<input type="text" id="car_manufacturer"/>
Model: <select id="car_model"></select>

Vehicle Model Accessories:

Javascript
vehicleModels = {
   "Mercedes": ["A-class", "B-class", "C-class", "S-class", "SLK", "ML", ],
   "Audi": ["A3", "A4", "A5", "A6", "A7", "A8", ],
   "BMW": ["120", "320", "330", "520", "635", "745", ]
}

This function takes the value in the textbox and checks if it is defined in the object above. If it is, the corresponding vehicle models are appended to the select list.
    $('#car_manufacturer').change(function() {
            if(vehicleModels[$(this).val()]) {
                $.each(vehicleModels[$(this).val()], function() {
                    $('#car_model').append('<option>' + this + '</option>');
                 });
            }
});

Here is where the problem begins!How can I now populate the model accessories
 with the corresponding selected model's accessories? Here is how the car accessories are being stored at the moment.
mercedes_accessories = ["Xenons", "Adaptive cruise control", "sunroof"];
bmw_accessories = ["Start/stop", "heated seats", "Leather trim"];
audi_accessories = ["Electric seats", "B&O Sound System", "Leather trim",];

Any help would be greatly appreciated. I'm sorry if the question is a bit vague, it's quite difficult to explain. Thankyou!

A: I'd do something like this :
var vehicleModels = {
       mercedes: ["A-class", "B-class", "C-class", "S-class", "SLK", "ML", ],
       audi: ["A3", "A4", "A5", "A6", "A7", "A8", ],
       bmw: ["120", "320", "330", "520", "635", "745", ]
    },
    vehicleAcc = {
        a3 : ["Xenons", "Adaptive cruise control", "sunroof"],
        a4 : ["Xenons", "Adaptive cruise control", "sunroof"],
        a6 : ["Xenons", "Adaptive cruise control", "sunroof"]
    };

$('#car_manufacturer').on('change', function() {
    if(this.value.toLowerCase() in vehicleModels) {
        $.each(vehicleModels[this.value.toLowerCase()], function(i,e) {
            $('#car_model').append('<option>'+e+'</option>');
        });
    }
});

$('#car_model').on('change', function() {
    if (this.value.toLowerCase() in vehicleAcc) {
        $.each(vehicleAcc[this.value.toLowerCase()], function(i,e) {
            $('#car_model_acc').append('<option>'+e+'</option>');
        });
    }
});

FIDDLE

A: Try this:
var accessories;

accessories.mercedes = ["Xenons", "Adaptive cruise control", "sunroof"];
accessories.bmw = ["Start/stop", "heated seats", "Leather trim"];
accessories.audi = ["Electric seats", "B&O Sound System", "Leather trim"];

$("#car_model").change( function( ) {

    // cache accessories for this manufacturer
    var arr = accessories[ $("#car_manufacturer").val().toLowerCase() ];

    for( var i = 0; i < arr.length; i += 1 ) {
       $("#accessories").append("<option>" + arr[i] + "</option>");
    }
});


text:
Q: How to force inheriting class's method implementation to call base method before invoke own implantation? I wrote some not sealed class that contain 3 virtual public method and one private method.
And i make this class public that all my develop group member could use this class ( include inherits and override the virtual public methods ) .
One of the private method name is 'PrivateMethod77()'.
Each time the public method 'PublicMethod77()' is call => the 'PrivateMethod77' is call in the first line of the method implementation ( after this line there are more implication logic ).
I want to keep this logic and 'force' the inherits and override of the method PublicMethod77 to call the PrivateMethod77 method as the first line of the PublicMethod77
Is there a way to do it ?

A: I don't think that you can enforce the inheriting classes to always first call a method's super implementation, but:
Normally I use a Template method pattern for cases like this:
public abstract class TemplateEnforcer
{
    private void TheSame()
    {
        Console.WriteLine("Everyone calls me;");
    }

    public void TemplateMethod()
    {
        this.TheSame();
        this.NeedsImplementation();
    }

    protected abstract void NeedsImplementation();
}

public class TemplateImplementer : TemplateEnforcer
{
    protected override void NeedsImplementation()
    {
        Console.WriteLine("Implemented in TemplateImplementer");
    }
}

Code output for this call new TemplateImplementer().TemplateMethod():
    //Everyone calls me;
    //Implemented in TemplateImplementer

Template method pattern benefits:

*

*Implementation of abstract method is forced.

*The code is kept DRY.

*Bugs are avoided and devs are guided in their development.


text:
Q: DataGridView and OnDataSourceChanged I have custom class, and I want to override OnDataSourceChanged method to read some information about columns. BUt in this methods, columns are not generated yet. I can only access data source columns, but I need to access auto generated DataGridView columns collection. When these columns are generated?

A: You didn't post your code, but make sure you call the base.OnDataSourceChanged() method before trying to access the column collection of the grid control:
protected override void OnDataSourceChanged(EventArgs e) {
  base.OnDataSourceChanged(e);  // call this first
  // loop through columns here...
}


text:
Q: IE8 throws Unspecified error when using Raphael text() I am using Raphaël 2.1.0. I draw several paths, circles, and rectangles, and everything seems to work fine on both IE9 (SVG) and IE8 (VML). However, when I try to add text to the canvas using text function, IE8 always throws Unspecified error, and the error seems to be on this line, raphael.js, line 5179 character 13, which is
var brect = span.getBoundingClientRect();

I don't see any error on IE7 though. Does anyone has an idea what might be the issue?
Thanks!


text:
Q: TSql to Linq translation how can I translate this to Linq to SQL
I want to get all message responses (mr) but for each number in mr I only want messages that were received after the 1st message (m) was sent
 select mr.*
     from
      (select distinct PhoneNumber, MIN(SentDate) as MinSentDate
        from Messages
        groupby PhoneNumber)m,
        join
        MessageResponses mr on m.PhoneNumber = mr.PhoneNumber

        where mr.ReceivedDate > m.MinSentDate

tks

A: It would look something like this
var query = from m in (from me in context.Messages
                       group me by me.PhoneNumber into mgr
                       select new
                       {
                         PhoneNumber = mgr.Key,
                         MinSentDate = mgr.Select(x => x.SentDate).Min()
                       }).Distinct()
            join mr in context.MessageResponses
            on m.PhoneNumber equals mr.PhoneNumber
            where mr.ReceivedDate > m.MinSentDate
            select mr;


text:
Q: Where do you send the kernel console on an embedded system? I'm developing an embedded system which currently boots linux with console output on serial port 1 (using the console boot param from the boot loader).  However, eventually we will be using this serial port.  What is the best solution for the kernel console output?  /dev/null?  Can it be put on a pty somehow so that we could potentially get access to it?

A: If you just want to read kernel printk messages from the console, and not actually run getty or a shell on it, you can use netconsole.  You can supply the following to your bootloader kernel options (or to modprobe netconsole):
netconsole=4444@10.0.0.1/eth1,9353@10.0.0.2/12:34:56:78:9a:bc

where 4444 is the local port, 10.0.0.1 is the local ip, eth1 is the local interface to send the messages out of.  9353 is the remote port, 10.0.0.2 is the remote ip to send the messages to, and the final argument is your remote (eg: your desktop) system's mac address.
Then to view the messages run:
netcat -u -l -p 9353

You can read more about this in Documentation/networking/netconsole.txt

A: You can access the printk message buffer from a shell using dmesg. The kernel buffer is of finite size and will overwrite the oldest entries with the most recent, so you'd need to either check dmesg periodically or hook up netconsole as @bmdhacks suggests.
If there is no console you'll miss any oops information printed out by a kernel crash. Even using netconsole may not help there, if the kernel dies and begins to reboot before TCP manages to deliver the output to the remote socket. We generally modify kernel/panic.c:panic() to save register contents and other state to an area of NOR flash, so there will be at least some information available for post-mortem debugging.


text:
Q: Create a VIEW that spans 3 tables Sorry if the title is not clear - feel free to improve.
Here are 3 tables (not all data is relevant to the question):
CREATE TABLE `content` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `community_id` int(10) unsigned NOT NULL COMMENT 'The community for whom this URL has special rules',
  `url_id` int(10) unsigned DEFAULT NULL COMMENT 'The URL that has special rules',
  `question_id` int(10) unsigned DEFAULT NULL,
  `banned` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT 'Flags if a URL is banned from the community',
  `featured` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'If this article is to be featured on this site',
  `slider_image` tinytext,
  `weight` int(11) DEFAULT '0',
  `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `content_url_unique` (`community_id`,`url_id`),
  UNIQUE KEY `content_question_unique` (`community_id`,`question_id`),
  KEY `community_index` (`community_id`),
  KEY `content_url_idx` (`url_id`),
  KEY `content_community_idx` (`community_id`),
  KEY `content_question_idx` (`question_id`),
  CONSTRAINT `content_community` FOREIGN KEY (`community_id`) REFERENCES `community` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `content_question` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `content_url` FOREIGN KEY (`url_id`) REFERENCES `url` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=186 DEFAULT CHARSET=utf8;

CREATE TABLE `url_tag` (
  `url_id` int(10) unsigned NOT NULL COMMENT 'The URL to be tagged',
  `tag_id` int(10) unsigned NOT NULL COMMENT 'The tag the url refers to',
  PRIMARY KEY (`url_id`,`tag_id`),
  KEY `FK_urltag_url_idx` (`url_id`),
  KEY `FK_urltag_tag_idx` (`tag_id`),
  CONSTRAINT `FK_urltag_tag` FOREIGN KEY (`tag_id`) REFERENCES `tag` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `FK_urltag_url` FOREIGN KEY (`url_id`) REFERENCES `url` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Allows to tag URLs';

CREATE TABLE `question_tag` (
  `question_id` int(10) unsigned NOT NULL,
  `tag_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`question_id`,`tag_id`),
  UNIQUE KEY `question_tag` (`question_id`,`tag_id`),
  KEY `fk_questiontag_question_idx` (`question_id`),
  KEY `fk_questiontag_tag_idx` (`tag_id`),
  CONSTRAINT `fk_questiontag_question` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `fk_questiontag_tag` FOREIGN KEY (`tag_id`) REFERENCES `tag` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='The tags associated with a given question';

Note that Content is meant to have either a url_id, or a question_id - not both.
I need a way to connect a Content ID to a Tag ID. I was thinking of creating a VIEW, and here are 2 possibilities I came up with so far.
Option 1:
(SELECT content.id AS content_id, url_tag.tag_id AS tag_id
FROM url_tag, content
WHERE url_tag.url_id = content.url_id)
UNION
(SELECT content.id AS content_id, question_tag.tag_id AS tag_id
FROM question_tag, content
WHERE question_tag.question_id = content.question_id)

Option 2:
SELECT content.id AS content_id, COALESCE(url_tag.tag_id, question_tag.tag_id) AS tag_id
FROM `content`
LEFT JOIN url_tag ON content.url_id = url_tag.url_id
LEFT JOIN question_tag ON content.question_id = question_tag.question_id WHERE COALESCE(url_tag.tag_id, question_tag.tag_id) IS NOT NULL

My question is which one is the better approach (or if there is one better)?
Note also that currently some Contents are not tagged at all.
Bonus challenge: a VIEW that connects content_id straight to category_id
CREATE TABLE `category_tag` (
  `category_id` int(10) unsigned NOT NULL,
  `tag_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`category_id`,`tag_id`),
  KEY `FK_categorytag_category_idx` (`category_id`),
  KEY `FK_categorytag_tag_idx` (`tag_id`),
  CONSTRAINT `FK_categorytag_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `FK_categorytag_tag` FOREIGN KEY (`tag_id`) REFERENCES `tag` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

A: There's not really a strong case here for doing this with views.
Of options 1 and 2, option 2 is the only option that is likely to be usable on data of any size, because of the different algorithms MySQL uses for processing views, and the strengths vs. limitations of each.
Unless explicitly declared otherwise, MySQL uses the MERGE algorithm whenever possible, which essentially makes the view into an alias for a more complicated query.  This provides some optimizations especially with the use of indexes in the underlying tables when interpreting the WHERE clause in the outer query.
SELECT * FROM view_option_2 WHERE content_id = 500;

I don't see a reason why MERGE could not be used with this view definition, so the server should process the query above as though you had sent this:
SELECT content.id AS content_id,
       COALESCE(url_tag.tag_id, question_tag.tag_id) AS tag_id
  FROM `content`
  LEFT JOIN url_tag ON content.url_id = url_tag.url_id
  LEFT JOIN question_tag ON content.question_id = question_tag.question_id
 WHERE content.id = 500
   AND COALESCE(url_tag.tag_id, question_tag.tag_id) IS NOT NULL

This could reasonably be expected to use the primary key on content and the leftmost column of the primary key of utl_tag and question_tag.  It seems like a nice, tidy, well-indexed query.
On the other hand, if Option 1 were used for a view definition, the server would not be able to use the MERGE algorithm, because of the UNION... so the server would use the other algorithm, TEMPTABLE, and construct a temporary table and fill it with the union of the two queries and then return only the rows specified by your where clause by eliminating non-matching rows from the temporary table.  But the point you don't want to overlook here is that the temporary table could contain every possible row without regard to the WHERE in your outer query.
You don't have to specify an ALGORITHM when you define a view, and if you don't, then it defaults to UNDEFINED which allows the server to choose.  One advantage of specifying an algorithm is that you always know which one will be used.  Extra bonus, you get a warning if you ask for MERGE and it can't be done.  Merge also doesn't work if there are no tables in the view, so here's a simple example:
mysql> CREATE ALGORITHM=MERGE VIEW test_view AS SELECT UUID_SHORT() AS a_big_number;
Query OK, 0 rows affected, 1 warning (0.05 sec)

We didn't get an error but we did get a warning.
mysql> show warnings;
+---------+------+-------------------------------------------------------------------------------+
| Level   | Code | Message                                                                       |
+---------+------+-------------------------------------------------------------------------------+
| Warning | 1354 | View merge algorithm can't be used here for now (assumed undefined algorithm) |
+---------+------+-------------------------------------------------------------------------------+
1 row in set (0.00 sec)

This is, however, a perfectly legitimate and working view, that returns a different number each time:
mysql> select * from test_view;
+---------------------+
| a_big_number        |
+---------------------+
| 2184556849028661248 |
+---------------------+
1 row in set (0.00 sec)

Define your view with ALGORITHM=MERGE and if the server doesn't like it, then that's not a good candidate for a view in this application.
Note, though, that this doesn't mean the TEMPTABLE algorithm isn't without its benefits also... but if you are going to SELECT from your view WHERE some condition applies to the fields in the underlying tables, TEMPTABLE prevents those conditions from "pushing through" the view definition.  Instead, they're applied to the result after the temporary table is derived, and of course that temporary table has no indexes.

Your "bonus" does not seem unusually complicated, either.
Take the Option 2 query and modify it:
SELECT content.id AS content_id,
       COALESCE(url_tag.tag_id, question_tag.tag_id) AS tag_id,
       category_tag.category_id
  FROM `content`
  LEFT JOIN url_tag ON content.url_id = url_tag.url_id
  LEFT JOIN question_tag ON content.question_id = question_tag.question_id
  LEFT JOIN category_tag on category_tag.tag_id = COALESCE(url_tag.tag_id, question_tag.tag_id)
 WHERE COALESCE(url_tag.tag_id, question_tag.tag_id) IS NOT NULL

If you don't want to eliminate untagged content, remove the WHERE clause.
To select for a specific content.id, put that in the WHERE clause.
If you get duplicate categories because of the relationships between category and tag then you'll need SELECT DISTINCT but don't put that inside the view, because that isn't compatible with MERGE either.


text:
Q: Make page get full size Hello i have a next problem, i wan't my page to stretch in height if content will be more than window height, otherwise just be fullscreen. But now it looks like this:

Here is my HTML:
<!DOCTYPE html>

    <meta content="width=1100" name="viewport">
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">

    <link type="text/css" rel="stylesheet" href="css/style.css">

Sākums

Informācija

Pakalpojumi un cenas

Darba laiks

Kontakti

Izglītība

And here is my CSS:
body{
min-width: 960px;
min-height: 100%;
margin: 0;
padding: 0 0 1px;
position: relative;
display: block;
background: #ff8b10 url(images/main_background.jpg) no-repeat;
font: normal normal 18px Georgia, Utopia, 'Palatino Linotype', Palatino, serif;
color: #000000;
}

.header{
margin-top: 30px;
height: 300px;
}

.header-inner{

height: 300px;
width: 960px;
    margin: 0 auto;
}

.tabs{
margin-top: 30px;
}

.tabs-inner{
width: 900px;
    margin: 0 auto;
}

ul {
width: 100%;
background: transparent none no-repeat scroll left;
margin: 0;
padding: 0;
overflow: hidden;
list-style: none;
line-height: 1.2;
display: table;
table-layout: fixed;
}

li{
border: none;
margin: 0;
padding: 0;
float: left;
text-indent: 0;
display: table-cell;
width: auto;
text-align: center;
}

a{
background-image: url('images/pixel.png');
display: inline-block;
padding: .25em 1em;
font: normal normal 20px Georgia, Utopia, 'Palatino Linotype', Palatino, serif;
border-right: 1px solid transparent;
color: #000000;
text-decoration: none;
}

a:hover {
background-color: #ffb267;
color: #660000;
cursor: pointer;
}

.active{
background-color: #ffd7ae;
color: #660000;
}

.content{
margin-top: 30px;
}

.content-inner{
width: 880px;
    margin-top: 0px;
margin-right: auto;
margin-bottom: 0px;
margin-left: auto;
}

.footer{
margin-top: 30px;
color: #ff8b10;
height: 100px;
background: #000000 url(images/footer.png) repeat scroll top left;
 }

.footer-inner{

}

.home_content{
    background: transparent url(images/content.png) repeat scroll top left;
}

A: You need height: 100% both on html and body.
Here's a similar question: Make full page white.


text:
Q: How to select only the last timestamp of each hour in SQL?
I want to extract hourly reports of a database for each process, but it has entries every second.
Since this is too much data to work with, I would like to get only the latest update of each hour. I am not an expert in SQL and tried already some "simple" solutions which did not work for me.
I hope you can help me out here.
SELECT
    report_id, start_date_local, process,
    productivity, dw_last_updated

FROM table_name

WHERE start_date_local > DATEADD(year,-1,GETDATE())

ORDER BY dw_last_updated, ppr_report_id desc

report_id
start_date_local
process
productivity
dw_last_updated

0001
2021-01-14 00:00:00.0
x
0.0551
2021-02-16 06:16:19.0

0002
2021-01-14 00:00:00.0
y
0.0333
2021-02-16 06:16:19.0

0003
2021-01-14 00:00:00.0
z
0.0164
2021-02-16 06:16:19.0

0004
2021-01-14 00:00:00.0
x
0.0850
2021-02-16 06:23:21.0

0005
2021-01-14 00:00:00.0
y
0.0238
2021-02-16 06:17:27.0

0006
2021-01-14 00:00:00.0
z
0.0542
2021-02-16 06:44:10.0

So in this example I would like to get only report_id = 0004, 0005, 0006

A: What you want is to group entries by process and get the max timestamp. So you need to put your query in GROUP BY clause:
manual:
https://dev.mysql.com/doc/refman/8.0/en/group-by-modifiers.html
SELECT process,
       report_id,
       start_date_local,

       productivity,
       max(dw_last_updated) last_updated

FROM table_name

WHERE start_date_local > DATEADD(year, -1, GETDATE())

GROUP BY process


text:
Q: How do I rotate a polygon around its center on mouse click? I want to find out how I would be able to rotate my polygon around its center when I click a mouse button?
glBegin(GL_POLYGON); //drawing a pentagon and coloring it.(using a polygon GL)
    glColor3f(0, 0, 1);//Blue
    glVertex3f(0.0f, 0.7f, 0.0f);//top point
    glColor3f(1, 0.5, 0);//Orange
    glVertex3f(-0.5f, 0.3f, 0.0f);//left middle point
    glColor3f(0, 1, 0);//Green
    glVertex3f(-0.3f, -0.3f, 0.0f);//bottom left point
    glColor3f(0.53, 0.12, 0.47);//Purple
    glVertex3f(0.3f, -0.3f, 0.0f);//bottom right point
    glColor3f(1, 0, 0);//red
    glVertex3f(0.5f, 0.3f, 0.0f);//middle right point
    glEnd();
    glutSwapBuffers();//Sends the Scene to the window

}

void mouse(int button, int state, int x, int y){
    if (button == GLUT_RIGHT_BUTTON){
        glRotatef(angle, 0, 0, 1);
        }
    }

A: The easiest method is to store the rotation angle in a global variable. This would then look like this:
global:
float angle = 0;

draw:
glRotate(angle, 0, 0, 1);
glBegin(GL_POLYGON);
...

void mouse(int button, int state, int x, int y){
    if (button == GLUT_RIGHT_BUTTON)
        angle += A_VALUE_PER_CLICK;
}

Edit: Note, that that the above rotates whenever you click (as asked). If you want to rotate the object as long as the mouse is pressed you'll have to do it a little bit different:
global:
bool is_mouse_down = false;
float angle = 0;

draw:
if (is_mouse_down)
    angle += ANGLE_PER_FRAME;

glRotate(angle, 0, 0, 1);
glBegin(GL_POLYGON);
...

void mouse(int button, int state, int x, int y){
    if (button == GLUT_RIGHT_BUTTON) {
        if (state == GLUT_DOWN)
            is_mouse_down = true;
        if (state == GLUT_UP)
            is_mouse_down = false;
    }
}

Edit 2: To spin about a specific point (in this case the center of the polygon [0, 0.2, 0]), one always has to translate this point to the origin, then rotate and then translate it back. This means one has to use something like this code (the signs might be flipped):
draw:
glTranslate(0, 0.2, 0);
glPushMatrix();
glRotate(angle, 0, 0, 1);
glPushMatrix();
glTranslate(0, -0.2, 0);

//Draw

glPopMatrix();
glPopMatrix();


text:
Q: Excel Find Specific Instances & Append to the End of URL String I have a column of 16,000 URLs. Some of the items end in "/" that represents "default.htm". I would like to do a Find and Replace but only on items that end with the "/".
For example:
The column may look like this:
/employeeresources/timeattendance/itas/
/employeeresources/pmap/ninpmap/ucm643423.htm
/employeeresources/dmap/srapmap/ucm643521.htm

But it needs to look like this:
/employeeresources/timeattendance/itas/default.htm
/employeeresources/pmap/ninpmap/ucm643423.htm
/employeeresources/dmap/srapmap/ucm643521.htm

What is the most efficient way to do this?
Thanks!

A: Try this formula in a helper column.
=IF(RIGHT(A2,1)="/",A2&"default.htm",A2)

A: Assuming your data is in column "A", then the following should work:

=IF(RIGHT(A1,1)="/",CONCATENATE(A1,"default.htm"),A1)


text:
Q: Combine Multiple Ng-Repeats I have an html structure where each children have different length values:

I dont like multiple ng-repeat.
How to re structure the code?

A: To create DOM nodes for all children of treeView recursively you can create a new component.
Example usage:
<your-directive elements="vm.elements"></your-directive>

Component code:
angular.module('yourApp')
  .component('yourDirective', {
    templateUrl: 'template.html',
    bindings: {
      elements: '='
    },
    bindToController: true,
    controllerAs: 'vm'
  });

Template code:

    <your-directive ng-if="vm.elements.children.length > 0" elements="vm.elements"></your-directive>

Note: I haven't tested this code but with a little tinkering you should get this to work.


text:
Q: Unhandled rejection Error: Can't set headers after they are sent in JavaScript I can not understand asynchority in JavaScript. I think my code should stop at the place I commented on (it goes to if), but it throws a bug:

Unhandled rejection Error: Can't set headers after they are sent.

Sorry for such big code, but I wanted to send everything to make the situation very clear to you.
I think that my method setTransferHistory(...) and sendAuthorizationKey(...) should be async/await and after doing this code, I want to return status 200.
Transaction.findOne({
                where: {
                  id_sender: senderId,
                  id_recipient: recipientId,
                  amount_money: amountMoney,
                  transfer_title: transferTitle,
                  authorization_key: authorizationKey,
                  authorization_status: setAuthorizationStatus(0),
                },
                order: [['date_time', 'DESC']],
              }).then(isAuthorizationKey => {
                if (!isAuthorizationKey) {
                  setTransferHistory(
                    senderId,
                    recipientId,
                    amountMoney,
                    transferTitle,
                    authorizationKey,
                  );
                  sendAuthorizationKey(
                    senderId,
                    recipientId,
                    amountMoney,
                    authorizationKey,
                  );
                  return res.status(200).json({ success: true }); /* it should stop in this place */
                }

All of controller:
exports.register = (req, res) => {
  function getTodayDate() {
    const today = new Date();
    return today;
  }

  function setAuthorizationStatus(status) {
    const authorizationStatus = status;
    return authorizationStatus;
  }

  async function getSenderEmail(id) {
    try {
      const isUser = await User.findOne({
        where: {
          id,
        },
      });
      return isUser.email;
    } catch (e) {
      /* just ignore */
    }
  }

  async function getRecipientName(id) {
    try {
      const isUser = await User.findOne({
        where: {
          id,
        },
      });
      return `${isUser.name} ${isUser.surname}`;
    } catch (e) {
      /* just ignore */
    }
  }

  function setAuthorizationKey() {
    let authorizationKey = '';
    const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

    for (let i = 0; i < 5; i++)
      authorizationKey += possible.charAt(
        Math.floor(Math.random() * possible.length),
      );

    return authorizationKey;
  }

  async function sendAuthorizationKey(
    senderId,
    recipientId,
    amountMoney,
    authorizationKey,
  ) {
    await nodemailer.createTestAccount();
    const transporter = nodemailer.createTransport({
      host: env.nodemailer.host,
      port: env.nodemailer.port,
      secure: false,
      auth: {
        user: env.nodemailer.username,
        pass: env.nodemailer.password,
      },
    });

    const mailOptions = {
      from: "example"`,
      to: `${await getSenderEmail(senderId)}`,
      subject: 'example',
      text: 'example`,
    };

    await transporter.sendMail(mailOptions);
  }

  function setTransferHistory(
    senderId,
    recipientId,
    amountMoney,
    transferTitle,
    authorizationKey,
  ) {
    Transaction.create({
      id_sender: senderId,
      id_recipient: recipientId,
      date_time: getTodayDate(),
      amount_money: amountMoney,
      transfer_title: transferTitle,
      authorization_key: authorizationKey,
      authorization_status: setAuthorizationStatus(0),
    });
  }

  Bill.findOne({
    where: {
      account_bill: req.body.account_bill,
    },
  }).then(isAccountBill => {
    if (isAccountBill) {
      const recipientId = isAccountBill.id_owner;
      const authorizationKey = setAuthorizationKey();
      const senderId = req.body.id_sender;
      const amountMoney = req.body.amount_money;
      const transferTitle = req.body.transfer_title;

      if (recipientId !== senderId) {
        Bill.findOne({
          where: {
            id_owner: senderId,
          },
        }).then(isAvailableFunds => {
          if (isAvailableFunds) {
            const senderAvailableFunds = isAvailableFunds.available_funds;

            if (senderAvailableFunds >= amountMoney && amountMoney > 0) {
              Transaction.findOne({
                where: {
                  id_sender: senderId,
                  id_recipient: recipientId,
                  amount_money: amountMoney,
                  transfer_title: transferTitle,
                  authorization_key: authorizationKey,
                  authorization_status: setAuthorizationStatus(0),
                },
                order: [['date_time', 'DESC']],
              }).then(isAuthorizationKey => {
                if (!isAuthorizationKey) {
                  setTransferHistory(
                    senderId,
                    recipientId,
                    amountMoney,
                    transferTitle,
                    authorizationKey,
                  );
                  sendAuthorizationKey(
                    senderId,
                    recipientId,
                    amountMoney,
                    authorizationKey,
                  );
                  return res.status(200).json({ success: true }); /* it should stop in this place */
                }
                return res.status(400).json({
                  error: 'Authorization key has been sent',
                  success: false,
                });
              });
            }
            return res.status(400).json({
              error: 'Sender does not have enough money',
              success: false,
            });
          }
          return res
            .status(404)
            .json({ error: 'Id sender doesnt exist', success: false });
        });
      }
      return res
        .status(404)
        .json({ error: 'Attempt payment to myself', success: false });
    }
    return res
      .status(404)
      .json({ error: 'Recipient does not exist', success: false });
  });
};

A: Calling return inside a Promise callback won't return from the calling code as well. Here's your code in a simplified example
if (someCondition) {
  doSomethingAsync().then(() =>
    ...
    return res.status(200).json(...);
  });
}
return res.status(400).json(...);

Now given doSomethingAsync is asynchronous, you are passing a callback function (then) in order to be notified when the I/O bound process has finished. However, whilst this call is underway, the current code will still run to completion so will unintentially call return res.status(400).json(...), hich means, by the time the callback fires for the I/O bound operation you have already ended the request and therefore receive the appropriate error.
To fix this, you need to wait on your asynchronous code to finish before you continue, that's exactly what async / await was designed for
if (someCondition) {
  await doSomethingAsync();
  return res.status(200).json(...);
}
return res.status(400).json(...);

Note - you do have a few scenarios in your code where you call async functions but don't await them e.g. sendAuthorizationKey, not sure if that's deliberate but does mean that code more than likely won't complete before the remaining code executes


text:
Q: Android CustomListView OnClick Hello Everyone Iam was Making a AndroidStudio List view app and I noticed custom list view is much better so I decided to switch into custom !
I have problem with the onclick listener of my CustomListView I cant get the position of clicked item so I cant gather info from that

Because :

This is My Listview OnClick ListenerCode (From internet)
 list.setOnItemClickListener(new OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> adapter, View v, int position,
                                long arg3)
        {
            // here the position element of this method will give you the row number on which the click happened.
            //Then you can get individual values like name[position], address[position] and then pass these values through an intent
        }
    });

It Dosent Work And Gives a Error on OnItemClickListener() !
Saying :
 Error:(118, 37) error: incompatible types: <anonymous android.support.v7.internal.widget.AdapterViewCompat.OnItemClickListener> cannot be converted to android.widget.AdapterView.OnItemClickListener
Error:(120, 37) error: cannot find symbol class AdapterView
Error:Execution failed for task ':app:compileDebugJava'.
> Compilation failed; see the compiler error output for details.

I used ALT+ENTER to fix The Error it Creates a
AdapterViewCompat.

Behind the OnItemListClickListener() and Suggest to implent methods so I Do ALT+ENTER and it will be like :
 list.setOnItemClickListener(new AdapterViewCompat.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> adapter, View v, int position,
                                long arg3)
        {
            // here the position element of this method will give you the row number on which the click happened.
            //Then you can get individual values like name[position], address[position] and then pass these values through an intent
        }

        @Override
        public void onItemClick(AdapterViewCompat<?> adapterViewCompat, View view, int i, long l) {

        }
    });

it Gives Error on first OnItemClick Funtion I though its a Duplicate of second one so I delete that but when I do it give error on second one too !
Saying :
   Error:(119, 37) error: incompatible types: <anonymous android.support.v7.internal.widget.AdapterViewCompat.OnItemClickListener> cannot be converted to android.widget.AdapterView.OnItemClickListener

SO the code from internet dosent work

Question : OnClickListener For CustomListView maybe?

A: ListView's setOnItemClickListener listener takes android.widget.AdapterView.OnItemClickListener as param and you're trying to set this android.support.v7.internal.widget.AdapterViewCompat.OnItemClickListener there and hence the error.
Change it to right listener type and the error should be resolved.
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){

                     //implement methods
})


text:
Q: TypeError: exe() missing 1 required positional argument: 'self' I am aware there are answers on this website dealing with this issue but all resolutions that I've come across haven't seemed to help in my situation. I'm using Tkinter (and trying to learn how to use it) to make a game. I want a button (Quit Game) to exit out of the Tkinter window but I keep getting this error:

TypeError: exe() missing 1 required positional argument: 'self'

My code:
from tkinter import *
import sys as s, time as t

try: color = sys.stdout.shell
except AttributeError: raise RuntimeError("This programme can only be run in IDLE")

color.write("     | Game Console | \n", "STRING")

root = Tk()
root.title("Tic-Tac-Toe")
menuFrame = Frame(root)
menuFrame.pack()
buttonFrame = Frame(root)
buttonFrame.pack()
Label(menuFrame, text = ("Tic-Tac-Toe"), font = ("Helvetica 12 bold")).grid(row = 10, column = 5)

def play():
    color.write("Game window opening... \n", "STRING")
    #open new window to game later

def exe(self):
    color.write("Goodbye for now \n", "STRING")
    self.destroy()

playButton = Button(buttonFrame, text = ("Play game"), command = play)
playButton.pack(side=LEFT)

Button(root, text=("Quit Game"), command=exe).pack()
root.mainloop()

I can't seem to find where it means as I've defined it into the function. Thank you in advance for your solutions.

A: In your code you have:
def exe(self):

This means you are requiring the self argument; self is used with instances of a class and as your method does not have a class you can omit the self parameter like so in your method header, like this:
def exe():
    color.write("Goodbye for now \n", "STRING")
    root.destroy()

A: Your method is defined in a way that it asks for a (positional) argument, self. Which is conventionally used as the object reference of a class but since you don't have a class it is just a regular argument right now, that you're not passing. You can pass that argument by, making use of anonymous functions(lambda), replacing:
Button(..., command=exe).pack()

with:
Button(..., command=lambda widget=root: exe(widget)).pack()

You should also better replace:
def exe(self):
    ...
    self.destroy()

with:
def exe(widget_to_be_destroyed):
    ...
    widget_to_be_destroyed.destroy()

for disambiguation.


text:
Q: How to delete an empty folder in my ftp with ruby Net::FTP? The method Net::FTP.delete(filename) works only for files, not directories, and there are no more delete methods in the documentation.
Not much to add to that.. seems like ruby ftp could be better off with a few more methods?

A: The commands to create and delete directories are different from that of files.
To create a directory, use mkdir and to remove one use rmdir.


text:
Q: The latest version of ImageMagick crashed ImageMagick++ I had this simple piece of code in my program that worked great until the newest update of GraphicsMagick:
{
   unsigned char *bitmap = new unsigned char[width*height*3];

   /* code that fills bitmap with the width, height, and depth specifed *\

   Image image(width,height,"BGR",CharPixel,bitmap); \\CODE SEGFAULTS HERE AT CONSTRUCTOR!

   image.write(file);
   delete[] bitmap;
}

Is seems that now if I use the Image constructor it will segfault.  Seemingly, now I cannot declare an Image object with the newest version of Magick++?


text:
Q: Is it possible to prevent regeneration of T4 files when saving an EDMX? In Entity Framework 4, when using a T4 template (.tt) for entities generation, saving the .edmx file automatically regenerates all .tt files in the same project. This is a fine behavior by default, since the Entities T4 is added next to the EDMX file.
We moved this template to another project to keep entities separate. We manually regenerate it when a change is made to the EDMX file. However, we have a bunch of other T4 files in the same project as the EDMX, which are automatically regenerated as soon as we save the model.
Is there a way to prevent this behavior? Those files could take a while to regenerate. We could of course move the model to another project on its own, but that's not an option currently.

A: I don't know how I could have missed this option for months. When nothing is selected in the EDMX designer, there is a property named "Transform Related Text Templates On Save" that can simply be set to false.


text:
Q: CKEditor: How to manually trigger ACF(Advanced Content Filter) With older version of CKEditor, I use following code to manually trigger Advanced Content Filter before submitting the content to server, but this stopped working for Version 4.4. I wonder is there a way to manually trigger the ACF and/or other kinds of content validation in CKEditor?
editor.setData(editor.getData(););

A: Your solution actually worked for me! To be more precise, I used CKEDITOR.instances['instance_name'].setData( CKEDITOR.instances['instance_name'].getData() ) and it worked!
To other people asking: this can be very useful even if you have ACF turned ON; in our app there's a number of situations that we manipulate the DOM inside CKEditor directly using jQuery for some very custom features we have (we actually create some UI inside the editor area), but we don't want that forbidden HTML going to the server and this solution works perfectly.
(Of course we always sanitize on the server as well)

A: For us this
CKEDITOR.instances['instance_name'].setData( CKEDITOR.instances['instance_name'].getData() )
didn't work, but getting the data with 1 in the arguments worked.
CKEDITOR.instances['instance_name'].setData( CKEDITOR.instances['instance_name'].getData(1) )


text:
Q: design for continuation based python web appliction framework There are many continuation based framework for java, ruby etc but none in python. Nagare framework somewhat solves the problem but it do not use standard python and uses stackless python to solve continuation problem.
I was wondering,
what part of standard python constraint to create such continuation web framework in standard python ?
and What are the workaround to it ? and what are standard part in continuation framework architecture ( as model view controller are in MVC ) ?

A: Before you can even begin to consider writing a continuation based framework you need a programming language that has continuations (or at least co-routines which can be used to emulate continuations). Continuation is a control structure like loops or closures or functions, not a design pattern like MVC. Unfortunately the (currently) standard Python does not support continuations. Which is one of the reason people developed stackless python.
Java is a bit of a special case. The language itself does not support continuations but the virtual machine does (in order to support exceptions). I think what they did was to modify the compiled bytecode at runtime and re-order instructions so that it looks like it supports continuations. Kind of like implementing stackless python by monkey-patching.

A: Right, continuation is a property of a language and CPython sadly has not continuations.
The workarounds in pure Python are well known : use callbacks / deferers like Twisted and Tornado for example or use 'yield' everywhere to mimic co-routines, like Diesel. But both approaches force you to change the way you design and code your application. Also a continuation can be "replayed" which is how the continuation based frameworks automatically handle the "back" button problem.
Finally, to be exact, in Nagare we are using the pickling of a freezed tasklet to obtain a continuation object.


text:
Q: Query HDF5 in Pandas I have following data (18,619,211 rows) stored as a pandas dataframe object in hdf5 file:
             date    id2         w
id
100010 1980-03-31   10401  0.000839
100010 1980-03-31   10604  0.020140
100010 1980-03-31   12490  0.026149
100010 1980-03-31   13047  0.033560
100010 1980-03-31   13303  0.001657

where id is index and others are columns. date is np.datetime64. I need to perform query like this (the code doesn't work of course):
db=pd.HDFStore('database.h5')
data=db.select('df', where='id==id_i & date>bgdt & date<endt')

Note id_i, bgdt, endt are all variables, not actual values and need to be passed within a loop. for example:
dates is a Pandas Period index or timestamps index, either way, I can convert to each other.
dates=['1990-01', 1990-04','1990-09',......]

id_list is a list of IDs
id_list=[100010, 100011,1000012,.......]

The loop looks like this (the reason I am doing loop is because the data is huge, there are other datasets I have query in the same time and then perform some operations)
db=pd.HDFStore('database.h5')
for id_i in id_list:
    for date in dates:
        bgdt=date-1 (move to previous month)
        endt=date-60 (previous 60 month)
        data=db.select('df', where='index==id_i & date>bgdt & date<endt')
        ......

This problem have 2 parts:

*

*I don't know how to query index and columns in the same time. The doc in pandas showed how to query based on index conditions OR columns conditions, but no examples on how to query based on them in the SAME TIME.

*

*(BTW, This is very common in Pandas Documentation. The doc usually shows very simple thing like how to do 'A', OR how to do 'B', but not how to do BOTH 'A' and 'B'. A good example is use query on a MultiIndex pandas dataframe. The doc shows based on either level=0 OR level=1, but no example on how to do BOTH in the SAME TIME.)

*I don't know how to pass three variables id_i, bgdt, endt to the query. I know how to pass only on by using %s, but not all of them.

*

*I am also a little confused with the datetime datatype. There seems to be quite a few of datetimes:datetime.datetime, numpy.datetime64, pandas.Period. I am mostly working on monthly data, so pandas.Period is the most useful one. But I can't easily convert a column (not index) of timestamps (the default date type of Pandas when parsed from raw data). Is there any datatype that is simply a 'date', not timestamps, not period, but just a simple DATE with only year,month and day?

A lot troubles, but I really LOVE python and pandas (I am trying to move my workflow from SAS to Python). Any help will be appreciated!

A: here are the docs for querying on non-index columns.
Create the test data. It is not clear how the original frame is constructed, e.g. whether its unique data and the ranges, so I have created a sample, with 10M rows, and a multi-level date range with the id column.
In [60]: np.random.seed(1234)

In [62]: pd.set_option('display.max_rows',20)

In [63]: index = pd.MultiIndex.from_product([np.arange(10000,11000),pd.date_range('19800101',periods=10000)],names=['id','date'])

In [67]: df = DataFrame(dict(id2=np.random.randint(0,1000,size=len(index)),w=np.random.randn(len(index))),index=index).reset_index().set_index(['id','date'])

In [68]: df
Out[68]:
                  id2         w
id    date
10000 1980-01-01  712  0.371372
      1980-01-02  718 -1.255708
      1980-01-03  581 -1.182727
      1980-01-04  202 -0.947432
      1980-01-05  493 -0.125346
      1980-01-06  752  0.380210
      1980-01-07  435 -0.444139
      1980-01-08  128 -1.885230
      1980-01-09  425  1.603619
      1980-01-10  449  0.103737
...               ...       ...
10999 2007-05-09    8  0.624532
      2007-05-10  669  0.268340
      2007-05-11  918  0.134816
      2007-05-12  979 -0.769406
      2007-05-13  969 -0.242123
      2007-05-14  950 -0.347884
      2007-05-15   49 -1.284825
      2007-05-16  922 -1.313928
      2007-05-17  347 -0.521352
      2007-05-18  353  0.189717

[10000000 rows x 2 columns]

Write the data to disk, showing how to create a data column (note that the indexes are automatically queryable, this allows id2 to be queryable as well). This is de-facto equivalent to doing. This takes care of opening and closing the store (you can accomplish the same thing by opening a store, appending, and closing).
In order to query a column, it MUST BE A DATA COLUMN or an index of the frame.
In [70]: df.to_hdf('test.h5','df',mode='w',data_columns=['id2'],format='table')

In [71]: !ls -ltr test.h5
-rw-rw-r-- 1 jreback users 430540284 May 26 17:16 test.h5

Queries
In [80]: ids=[10101,10898]

In [81]: start_date='20010101'

In [82]: end_date='20010301'

You can specify dates as string (either in-line or as variables; you can also specify Timestamp like objects)
In [83]: pd.read_hdf('test.h5','df',where='date>start_date & date<end_date')
Out[83]:
                  id2         w
id    date
10000 2001-01-02  972 -0.146107
      2001-01-03  954  1.420412
      2001-01-04  567  1.077633
      2001-01-05   87 -0.042838
      2001-01-06   79 -1.791228
      2001-01-07  744  1.110478
      2001-01-08  237 -0.846086
      2001-01-09  998 -0.696369
      2001-01-10  266 -0.595555
      2001-01-11  206 -0.294633
...               ...       ...
10999 2001-02-19  616 -0.745068
      2001-02-20  577 -1.474748
      2001-02-21  990 -1.276891
      2001-02-22  939 -1.369558
      2001-02-23  621 -0.214365
      2001-02-24  396 -0.142100
      2001-02-25  492 -0.204930
      2001-02-26  478  1.839291
      2001-02-27  688  0.291504
      2001-02-28  356 -1.987554

[58000 rows x 2 columns]

You can use in-line lists
In [84]: pd.read_hdf('test.h5','df',where='date>start_date & date<end_date & id=ids')
Out[84]:
                  id2         w
id    date
10101 2001-01-02  722  1.620553
      2001-01-03  849 -0.603468
      2001-01-04  635 -1.419072
      2001-01-05  331  0.521634
      2001-01-06  730  0.008830
      2001-01-07  706 -1.006412
      2001-01-08   59  1.380005
      2001-01-09  689  0.017830
      2001-01-10  788 -3.090800
      2001-01-11  704 -1.491824
...               ...       ...
10898 2001-02-19  530 -1.031167
      2001-02-20  652 -0.019266
      2001-02-21  472  0.638266
      2001-02-22  540 -1.827251
      2001-02-23  654 -1.020140
      2001-02-24  328 -0.477425
      2001-02-25  871 -0.892684
      2001-02-26  166  0.894118
      2001-02-27  806  0.648240
      2001-02-28  824 -1.051539

[116 rows x 2 columns]

You can also specify boolean expressions
In [85]: pd.read_hdf('test.h5','df',where='date>start_date & date<end_date & id=ids & id2>500 & id2<600')
Out[85]:
                  id2         w
id    date
10101 2001-01-12  534 -0.220692
      2001-01-14  596 -2.225393
      2001-01-16  596  0.956239
      2001-01-30  513 -2.528996
      2001-02-01  572 -1.877398
      2001-02-13  569 -0.940748
      2001-02-14  541  1.035619
      2001-02-21  571 -0.116547
10898 2001-01-16  591  0.082564
      2001-02-06  586  0.470872
      2001-02-10  531 -0.536194
      2001-02-16  586  0.949947
      2001-02-19  530 -1.031167
      2001-02-22  540 -1.827251

To answer your actual question I would do this (their is really not enough information, but I'll put some reasonable expectations):

*

*Do't loop over queries, unless you have a very small number of absolute queries

*Read the biggest chunk into memory that you can. Usually this is accomplished by selecting out the biggest ranges of data that you need, even if you select MORE data than you actually need.

*Then subselect using in-memory expressions, which will generally be orders of magnitude faster.

*List elements are limited to about 30 elements in total (this is current an implementation limit on the PyTables side). It will work if you specify more, but what will happen is that you will read in a lot of data, then it will be reindexed down (in-memory). So user needs to be aware of this.

So for example say that you have 1000 unique ids with 10000 dates per as my example demonstrates. You want to select say 200 of these, with a date range of 1000.
So in this case I would simply select on the dates then do the in-memory comparison, something like this:
df = pd.read_hdf('test.h5','df',where='date=>global_start_date & date<=global_end_date')
df[df.isin(list_of_ids)]

You also might have dates that change per ids. So chunk them, this time using a list of ids.
Something like this:
output = []
for i in len(list_of_ids) % 30:
    ids = list_of_ids[i:(i+30)]
    start_date = get_start_date_for_these_ids (global)
    end_date = get_end_date_for_these_ids (global)
    where = 'id=ids & start_date>=start_date & end_date<=end_date'
    df = pd.read_hdf('test.h5','df',where=where)
    output.append(df)

 final_result = concat(output)

The basic idea then is to select a superset of the data using the criteria that you want, sub-selecting so it fits in memory, but you limit the number of queries you do (e.g. imagine that you end up selecting a single row with your query, if you have to query this 18M times that is bad).


text:
Q: Is there a work arround on this code that generates a NotSupportedException from NHibernate? The following is the code:
list = query.Where(x => ((string)x.GetType()
    .GetProperty(propertyName).GetValue(this, null))
        .EndsWith(filterValue)).ToList();

This code is a refactored code that if I break it to its object and property level it would take me repeating it hundred times all around my code project. According to my research in this site it has something to do with the SQL translation. But is there any work around where this code or its variant will work fine?

A: The solution is to create an Expression that returns the specified property and pass that expression to Where:
var query = session.Query<YourType>();
list = query.Where(GetExpression<YourType>(propertyName, filterValue)).ToList();

GetExpression looks something like this:
public static Expression<Func<T, bool>> GetExpression<T>(string propertyName,
                                                  string filterValue)
{
    var parameter = Expression.Parameter(typeof(T));
    var property = Expression.Property(parameter, propertyName);
    var method = typeof(string).GetMethod("EndsWith", new [] { typeof(string) });
    var body = Expression.Call(property, method,
                               Expression.Constant(filterValue));
    return (Expression<Func<T, bool>>)Expression.Lambda(body, parameter);
}


text:
Q: Prove $2^{2n+7} \equiv 2 (mod 3)$ for all integer and non-negative number n. Originally, I want to prove this problem:
for all integer and non-negative number $n$,
$$\frac{1}{3}\times2^{2n+7}+\frac{37}{3} \equiv 0\quad(\text{mod}\space3)$$
I tried like this:
$$\frac{1}{3}\times2^{2n+7}+\frac{37}{3} = \frac{1}{3}(2^{2n+7}+37)$$
therefore $2^{2n+7}+37$ must be $\equiv0\space(\text{mod}\space3)$ and greater than or equal to $3$.
Since $2^{2n+7}+37$ is bigger than $37$(for all $n$), we can ignore the latter.
By the way, $37 \equiv 1(\text{mod}\space3)$.  Therefore $2^{2n+7} \equiv 2(\text{mod}\space3)$.
I stuck here. is there any way to prove this?
and following calculation correct?
$$2^{2n+7} =  2^7\times 2^{2n}\quad \text{and}\quad 2^7 \equiv 2 (\text{mod}\space3)$$Therefore,
$$2^{2n+7}  =2^7\times 2^{2n} \equiv  2\times 2^{2n} (\text{mod}\space3)$$

A: Thanks Will199 and Evariste.
for all integer and non-negative number $n$,
$2^{n}\equiv (-1)^{n} \equiv -1($when n is odd$)$ or $1$(when n is even) $(mod \quad3)$
$2n+7$ is always odd because $2n$ is even and $7$ is odd and even+odd=odd.
So, $2^{2n+7}\equiv (-1)^{2n+7} \equiv -1 \equiv 2 \quad(mod \quad3)$.


text:
Q: ImportError: No module named pyqt_ui.qt_translator I'm attempting to package a python application (Mnemosyne) using py2app (I didn't write the software; I am only attempting to package it).
I have built the application with py2app:
sudo python setup.py py2app
and copied the qt_menu.nib directory into the Resources directory.
When I then attempt to launch the application:
./dist/Mnemosyne.app/Contents/MacOS/Mnemosyne
I get this error:

ImportError: No module named pyqt_ui.qt_translator

I haven't been able to figure out what to add to the "includes" to ensure qt_translator is included.
I read the list of PyQT modules but I couldn't find which module I need to include to get qt_translator.  I learned that there is a QTranslator class in the QtCore module, but including PyQt4.QtCore doesn't help, nor does PyQt4*.
The line in the code that seems to be causing this is:
mnemosyne.components.insert(0,
                            ("mnemosyne.pyqt_ui.qt_translator",
                             "QtTranslator"))

A: The class you are missing is part of the package that you download when you download the Mnemosyne tarball it is in the folder mnemosyne/pyqt_ui file name qt_translator.py you need to extract the entire tarball and cd into it in terminal then use py2app.


text:
Q: Feeding image data in tensorflow for transfer learning I am trying to use tensorflow for transfer learning. I downloaded the pre-trained model inception3 from the tutorial. In the code, for prediction:
prediction = sess.run(softmax_tensor,{'DecodeJpeg/contents:0'}:image_data})

Is there a way to feed the png image. I tried changing DecodeJpeg to DecodePng but it did not work. Beside, what should I change if I want to feed decoded image file like a numpy array or a batch of arrays?
Thanks!!

A: The shipped InceptionV3 graph used in classify_image.py only supports JPEG images out-of-the-box. There are two ways you could use this graph with PNG images:

*

*Convert the PNG image to a height x width x 3 (channels) Numpy array, for example using PIL, then feed the 'DecodeJpeg:0' tensor:
import numpy as np
from PIL import Image
# ...

image = Image.open("example.png")
image_array = np.array(image)[:, :, 0:3]  # Select RGB channels only.

prediction = sess.run(softmax_tensor, {'DecodeJpeg:0': image_array})

Perhaps confusingly, 'DecodeJpeg:0' is the output of the DecodeJpeg op, so by feeding this tensor, you are able to feed raw image data.

*Add a tf.image.decode_png() op to the imported graph. Simply switching the name of the fed tensor from 'DecodeJpeg/contents:0' to 'DecodePng/contents:0' does not work because there is no 'DecodePng' op in the shipped graph. You can add such a node to the graph by using the input_map argument to tf.import_graph_def():
png_data = tf.placeholder(tf.string, shape=[])
decoded_png = tf.image.decode_png(png_data, channels=3)
# ...

graph_def = ...
softmax_tensor = tf.import_graph_def(
    graph_def,
    input_map={'DecodeJpeg:0': decoded_png},
    return_elements=['softmax:0'])

sess.run(softmax_tensor, {png_data: ...})

A: The following code should handle of both cases.
import numpy as np
from PIL import Image

image_file = 'test.jpeg'
with tf.Session() as sess:

    #     softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
    if image_file.lower().endswith('.jpeg'):
        image_data = tf.gfile.FastGFile(image_file, 'rb').read()
        prediction = sess.run('final_result:0', {'DecodeJpeg/contents:0': image_data})
    elif image_file.lower().endswith('.png'):
        image = Image.open(image_file)
        image_array = np.array(image)[:, :, 0:3]
        prediction = sess.run('final_result:0', {'DecodeJpeg:0': image_array})

    prediction = prediction[0]
    print(prediction)

or shorter version with direct strings:
image_file = 'test.png' # or 'test.jpeg'
image_data = tf.gfile.FastGFile(image_file, 'rb').read()
ph = tf.placeholder(tf.string, shape=[])

with tf.Session() as sess:
    predictions = sess.run(output_layer_name, {ph: image_data} )


text:
Q: Distributed notification no longer working in Catalina I transfer data between a safari extension app and MacOS app by using Distributed Notification Center.
I use DistributedNotificationCenter.default().addObserver with a specific notification name and I post a notification from the MacOS App using the same name DistributedNotificationCenter.default().postNotificationName
I keep getting attempt to post distributed notification 'nameofnotification' thwarted by sandboxing.
I saw in the apple documentation that

Sandboxed apps can send notifications only if they do not contain a
  dictionary. If the sending application is in an App Sandbox, userInfo
  must be nil.

My user Info is not nil, but this worked perfectly on previous versions of Mac. What am I missing ? Is this relatively new ?
What's the alternative to communicate between extension and app? Would an XPC service work ?
UPDATE
I have implemented an XPC Service following apple's documentation, but when I call it from the safari extension I get this error Couldn't communicate with a helper application. I can call it without any problems from the application that's embedding The XPC Service.
I have tried to :

*

*copy the service to the extension's Contents/XPCServices

*add an app group, and use let connectionXPC = SXPCConnection.init(serviceName:"XXXXXXX.com.bundlename.XPCService") instead of just let connectionXPC = NSXPCConnection.init(serviceName: "com.bundlename.XPCService") where XXXXXXX is the app group.

Any idea on how to properly use The XPC Service from the extension app, or any other way to communicate and send data between sandboxed extension and app.

A: The XPC will not work in this case. Communication with new type Safari Extensions should be performed via SFSafariExtensionHandler subclass.
It is recommended to create Safari Extension via Xcode corresponding template, all important settings, Info.plist fields, and infrastructure will be set up for you.
Please see good documented details at official Building a Safari App Extension


text:
Q: Exception has occurred: ImportError cannot import name 'Rescaling' I am trying to train deep learning models but having these error in following line:
 from tensorflow.keras.layers.experimental.preprocessing import Rescaling
Exception has occurred: ImportError
cannot import name 'Rescaling'

I am using these versions-
python 3.6.10 on Miniconda3
tensorflow-gpu=2.1.0
keras-gpu=2.2.4
cuda 11
cuDNN=8.0.1

help regarding this issue will be appreciated.

A: Not familiar with tensorflow, however, tensorflow states for GPU it is a single package.
https://www.tensorflow.org/install/gpu
For releases 1.15 and older, CPU and GPU packages are separate. The version you are using looks newer.
pip install tensorflow  # stable
pip install tf-nightly  # preview

In your case the requirements.txt would be updated to have tensorflow in there instead of tensorflow-gpu.
I would start with their example:
https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/Rescaling
import tensorflow as tf
tf.keras.layers.experimental.preprocessing.Rescaling(
    scale, offset=0.0, name=None, **kwargs
)


text:
Q: Solution of the following equation: $ (x-y)(2dy-dx)=3dx-5dy$ When rearranged, I got: $\dfrac{dy}{dx} = \dfrac{3-y+x}{2x-2y+5}$. How do I proceed?

A: hint:Put $u = y-x \implies y' = (u+x)' = u'+1 \implies u'+1 = \dfrac{3-u}{5-2u}$. Can you take it from here?

A: Hint
Start defining $$2x-2y+5=z \implies y=\frac{1}{2} (2 x-z+5)\implies y'=\frac{1}{2} \left(2-z'\right)$$ The equation becomes $$z'+\frac{1}{z}=1$$ which looks to be separable.


text:
Q: Asp.net Identity + Unit of Work: Getting duplicated entries I am using the newest version of ASP.NET Identity, using the sample project as a base template.
My changes are simple: Adding a FIRM Properyt to the application user.
Thus, the application User looks like this:
   public class ApplicationUser : IdentityUser
    {
        /// <summary>
        /// Gets or sets the firm.
        /// </summary>
        /// <value>
        /// The firm.
        /// </value>
        public virtual Firm Firm { get; set; }

        /// <summary>
        /// Generates the user identity asynchronous.
        /// </summary>
        /// <param name="manager">The manager.</param>
        /// <returns>A claims identity</returns>
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            //// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            //// Add custom user claims here
            return userIdentity;
        }
    }

Also, I do have a Unit Of Work implented, which is responsible for Firm and other entities.
 /// <summary>
    /// This contains a Unit of Work pattern Implementation. Provides access to all Elements used in this Application.
    /// </summary>
    public class UnitOfWork : IDisposable, IUnitOfWork
    {
        /// <summary>
        /// The database context
        /// </summary>
        private PriorityDBContext dbContext = new PriorityDBContext();

        public UnitOfWork(ApplicationDbContext dbContext)
        {
            this.dbContext = (PriorityDBContext)ApplicationDbContext;
        }

        private GenericRepository<Firm> firmRepository;

        public IGenericRepository<Firm> FirmRepository
        {
            get
            {
                if (this.firmRepository == null)
                {
                    this.firmRepository = new GenericRepository<Firm>(this.dbContext);
                }

                return this.firmRepository;
            }
        }
    }

Now to my problem: I have an Account Controller, which can create new Users (among other things). When a new User is created, the Firm is silently doubled. E.g. I had a Firm called "Example1" in the database before. Now I create a new User and suddenly the Database contains "Example1" two times.
As far I can tell, the root cause is that Asp.net Identity uses one DbContext, my UnitOfWork another. I am unsure why, I tried to set up Ninject in a way that the same DbContext is used in all parts. But it simply have enormous problems getting the same db Context into the UserManager and the unit of work :(
[Authorize]
public class AccountController : Controller
{
/// <summary>
/// The Unit of Work
/// </summary>
private IUnitOfWork uoW;

/// <summary>
/// The _user manager
/// </summary>
private ApplicationUserManager userManager;

public AccountController(IUnitOfWork uow)
{
    this.uoW = uow;
}

/// <summary>
/// Gets the user manager.
/// </summary>
/// <value>
/// The user manager.
/// </value>
public ApplicationUserManager UserManager
{
    get
    {
        if (this.userManager == null)
        {
            this.userManager =  HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }

        return this.userManager;
    }

    private set
    {
        this.userManager = value;
    }
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    bool success = true;

    if (ModelState.IsValid)
    {
                var firm = this.uoW.FirmRepository.GetRaw().Where(f => f.FirmName == newUser.Firm).First();
                var user = new ApplicationUser { FirstName = newUser.FirstName, LastName = newUser.LastName, Email = newUser.Email, UserName = newUser.Email, PreferredLanguage = newUser.Language, Firm = firm };

                var password = Guid.NewGuid().ToString();
                var result = await this.UserManager.CreateAsync(user, password);
                if (result.Succeeded)
                {
                    this.logger.Info("Created user for {0} successfully", newUser.Email);
                }
            }
        }
    }
}

}
Ninject, registering the Bindings:
private static void RegisterServices(IKernel kernel)
{
    /// loading the ApplicationDbContext here because the UserManager uses it from the OwinContext and if the
    /// Unit of Work defines it's own DBContext, bad things happen, e.g. duplicated objects when working with users AND our own pocos here.
    kernel.Bind<IUnitOfWork>().To<UnitOfWork>().WithConstructorArgument("dbContext", ninjectContext => HttpContext.Current.GetOwinContext().Get<ApplicationDbContext>());
    kernel.Bind<IGenericRepository<Firm>>().To<GenericRepository<Firm>>();
    //kernel.Bind<ApplicationUserManager>().To(HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>());
}

The ApplicationUserManager:
  public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            //// Konfigurieren der Überprüfungslogik für Benutzernamen.
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // snipped

            return manager;
        }
    }


text:
Q: How can I use an fstream object as a member variable? Previously, I would pass the address of fstream objects to any functions, including the constructor, that do I/O operations. But I want to try making fstream objects available as member variables so that all subsequent I/O operations can use those variables instead of having them passed as arguments.
Consider the following Java program:
public class A {
    Scanner sc;

    public A(Scanner read) {
        sc = read;
    }
}

What would be the C++ equivalent of this? I tried doing this
class A {
    ofstream *out;

    public:
        A (ofstream &output) {
            out = output;
        }
};

But this gives me a compilation error:

[Error] invalid user-defined conversion from 'std::ofstream {aka std::basic_ofstream}' to 'std::ofstream* {aka std::basic_ofstream*}' [-fpermissive]

A: I suggest use of a reference type as the member variable of the class.
class A {
    ofstream& out;

    public:
        A (ofstream &output) : out(output) {}
};

It is cleaner than using a pointer.
If you want objects of type A to read data from a stream (like the name Scanner suggests), use a std::istream.
class A {
    std::istream& in;

    public:
        A (std::istream &input) : in(input) {}
};

A: You probably want
class A {
    ofstream *out;

    public:
        A (ofstream &output) : out(&output) {
                                // ^ Take the address
        }
};

Since std::ofstream is specialized for files, the even better interfacing would be:
class A {
    ostream *out;

    public:
        A (ostream &output) : out(&output) {
        }
};

Thus you could use your class transparently for non file oriented output targets as well, like
A a(std::cout); // writes to standard output rather than using a file


text:
Q: custom AlertDialog view.onClickListener does not work properly I'm adding the colors.xml to the AlertDialog and want it to respond, when one of its views is clicked. The dialog is displayed properly and when I do performClick() on one of the views it works. But when I try to run it on my phone and click by hand the listener does not get triggered although it should be.
Here's my code:
My MainActivity.java
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("pick a color");
builder.setCancelable(true);
FlexboxLayout fl_colors = (FlexboxLayout) layoutInflater.inflate(R.layout.colors,null);
builder.setView(layoutInflater.inflate(R.layout.colors,null));

final AlertDialog alert = builder.create();

for(int i=0;i<fl_colors.getChildCount();i+=1){
    View v_color = fl_colors.getChildAt(i);
    Log.d("DEBUG",v_color.toString()); // logs the element like: android.view.View{a7d0c87 V.ED..... ......I. 0,0-0,0 #7f0d00a6 app:id/btn_6}
    v_color.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            String color = (String) v.getTag();
            Log.d("DEBUG",color);

            alert.dismiss();
        }
    });
}

builder.show();

And my colors.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.flexbox.FlexboxLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:flexWrap="wrap"
    android:id="@+id/fb_colors">

    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/btn_0"
        android:background="@drawable/circle"
        android:backgroundTint="#16a085"
        android:tag="#16a085"
        android:layout_margin="5dp"/>
    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/btn_1"
        android:background="@drawable/circle"
        android:backgroundTint="#27ae60"
        android:tag="#27ae60"
        android:layout_margin="5dp"/>
    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/btn_2"
        android:background="@drawable/circle"
        android:backgroundTint="#2980b9"
        android:tag="#2980b9"
        android:layout_margin="5dp"/>

    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/btn_3"
        android:background="@drawable/circle"
        android:backgroundTint="#8e44ad"
        android:tag="#8e44ad"
        android:layout_margin="5dp"/>

    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/btn_4"
        android:background="@drawable/circle"
        android:backgroundTint="#f39c12"
        android:tag="#f39c12"
        android:layout_margin="5dp"/>
    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/btn_5"
        android:background="@drawable/circle"
        android:backgroundTint="#d35400"
        android:tag="#d35400"
        android:layout_margin="5dp"/>
    <View
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/btn_6"
        android:background="@drawable/circle"
        android:backgroundTint="#c0392b"
        android:tag="#c0392b"
        android:layout_margin="5dp"/>
</com.google.android.flexbox.FlexboxLayout>

A: Because you do not use inflated view.
Replace
builder.setView(layoutInflater.inflate(R.layout.colors,null));

with
builder.setView(fl_colors);


text:
Q: How to include a custom SASS file in a Vaadin 14 application? I'm developing a Vaadin 14 app on Maven, so I'm using vaadin-maven-plugin which, according to Vaadin's v14 starter app:

Takes care of synchronizing java dependencies and imports in package.json and main.js files. It also creates webpack.config.js if not exists yet.

After running the app I got the package.json file and the node-modules on the root dir. I performed npm install bootstrap afterwards and created a custom SCSS file inside src/main/webapp/frontend/, with a few handpicked @import instructions to get my own Bootstrap build.
Vaadin's documentation about Including Style Sheets doesn't mention anything regarding SCSS. How can I get Vaadin's Maven plugin to compile my SCSS file so I can import the resulting CSS file into my app?

A: In vaadins theming documentation it mentions that

Vaadin 14 itself isn't using Sass, but you can of course use it for your own application theming if you want to. You'll have to setup the sass-compiler workflow yourself, but there are Maven Plugins available for this.

After a quick search I found this sass-maven-plugin which will probably do what you need; compile your sass/scss files to css before packaging.
As pointed out in comments, there is also the libsass-maven-plugin.
I myself have not used this yet (will try to, once I get some time) so I can't tell you how to best configure said plugin. But I'm sure that once it's configured correctly, this is the way to use SCSS/SASS with Vaadin 14

A: Following @Kaspar Scherrer's answer, I was able to generate a custom build of Twitter Bootstrap to include as CSS on my Vaadin 14 app by performing the following steps:

*

*Include Bootstrap's source Sass and JavaScript files via npm, running npm install bootstrap on the CLI in the project's root dir;

*Setup libsass-maven-plugin on my project's pom.xml:
<!-- SASS compiler -->
<plugin>
  <groupId>com.gitlab.haynes</groupId>
  <artifactId>libsass-maven-plugin</artifactId>
  <version>0.2.21</version>
  <executions>
    <execution>
      <phase>generate-resources</phase>
      <goals>
        <goal>compile</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <inputPath>${basedir}/src/main/webapp/frontend/sass/</inputPath>
    <includePath>${basedir}/node_modules/</includePath>
    <outputPath>${basedir}/src/main/webapp/frontend/css/</outputPath>
    <failOnError>true</failOnError>
  </configuration>
</plugin>

*Created the custom SASS file, named webapp-bootstrap.scss in this example, inside the dir set on inputPath:

html {
  box-sizing: border-box;
  -ms-overflow-style: scrollbar;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}

// Required
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";

@import "bootstrap/scss/mixins/breakpoints";
@import "bootstrap/scss/mixins/clearfix";
@import "bootstrap/scss/mixins/deprecate";
@import "bootstrap/scss/mixins/grid-framework";
@import "bootstrap/scss/mixins/grid";
@import "bootstrap/scss/mixins/hover";
@import "bootstrap/scss/mixins/screen-reader";
@import "bootstrap/scss/mixins/text-emphasis";
@import "bootstrap/scss/mixins/text-hide";
@import "bootstrap/scss/mixins/text-truncate";

// Optional
@import "bootstrap/scss/grid";
@import "bootstrap/scss/utilities/align";
@import "bootstrap/scss/utilities/clearfix";
@import "bootstrap/scss/utilities/display";
@import "bootstrap/scss/utilities/flex";
@import "bootstrap/scss/utilities/float";
@import "bootstrap/scss/utilities/position";
@import "bootstrap/scss/utilities/screenreaders";
@import "bootstrap/scss/utilities/sizing";
@import "bootstrap/scss/utilities/spacing";
@import "bootstrap/scss/utilities/text";

*Included the generated stylesheets on my app by using an annotation @StyleSheet("css/webapp-bootstrap.css").


text:
Q: how do I solve $y -\sin y= 1$ I am trying to use trigonometric equations to solve $y - \sin y = 1$, such as solving for $y$ but it is not working out, I have found $\cos y = \sqrt{-y^2 + y}$ but it does not lead to anywhere useful. I have used wolfram for the answer, but I am not sure how they got it

A: As has already been said in the comments, there is no closed form solution.
Wolfram gives the following solution (which you can find using the various numerical methods out there, a few of which are taught in highschool).
We can numerically find that $y \approx 1.93456$.


text:
Q: Android ble scan list update I would like to make my BLE scan list to update if I turn off one of the devices.
For instance :

*

*devices turning on

*Apps detect 3 devices via BLE at the first time

*Turn off one device

*Apps can detect 2 devices via BLE

When it comes to the implementation, Apps cannot get the updated list , still detects 3 devices at the first time. Would you please tell me how to modify the handler so that the LeDeviceListAdapter can clear and update if procedure 3 is done and goes 4 ?
The below is my code
OnCreate:
final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        private boolean useDiceOne;
        @Override
        public void run() {
            if(deviceFound){
                System.out.println("2");
                iv.setImageResource(R.drawable.pairing_d);
                mLeDeviceListAdapter.notifyDataSetChanged();
                if(screenHeight < 1800){
                    if(mLeDeviceListAdapter.getCount() > 2 ){

                        iv.setImageResource(R.drawable.pairing_d2);
                    }
                }else{
                    if(mLeDeviceListAdapter.getCount() > 3 ){

                        iv.setImageResource(R.drawable.pairing_d2);
                    }
                }
            }else{
                if (!useDiceOne) {
                    iv.setImageResource(R.drawable.pairing_b);
                } else {
                    iv.setImageResource(R.drawable.pairing_bn);
                }
                useDiceOne = !useDiceOne;
                handler.postDelayed(this, 400);
            }
        }
    } , 50);

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void scanLeDevice(final boolean enable) {
    if (enable) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        }, 10000);

        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
}

private BluetoothAdapter.LeScanCallback mLeScanCallback =   new BluetoothAdapter.LeScanCallback() {

    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
        runScan= new Runnable()
        {
            public void run()
            {
                reverseByte(scanRecord);
                byte [] serviceBytes = new byte[16];
                System.arraycopy(scanRecord, 41, serviceBytes, 0, 16);

                if(checkService(asd , serviceBytes)){

                    iv.setImageResource(R.drawable.pairing_d);
                    deviceFound = true;
                    mLeDeviceListAdapter.addDevice(device);
                    mLeDeviceListAdapter.notifyDataSetChanged();
                    if(screenHeight < 1800){
                        if(mLeDeviceListAdapter.getCount() > 2 ){

                            System.out.println("z5");
                            lblCalibrate.setText(resultUiString.get(16));
                            iv.setImageResource(R.drawable.pairing_d2);
                        }
                    }else{
                        if(mLeDeviceListAdapter.getCount() > 3 ){

                            System.out.println("z5");
                            lblCalibrate.setText(resultUiString.get(16));
                            iv.setImageResource(R.drawable.pairing_d2);
                        }
                    }
                }else{

                }
            }
        };
        handler.postDelayed(runScan, 500);
    }
};

A: In order to achieve your goal, you have to restart scanning after you turn off the device. The experiments I have done show that I have to follow the procedure below to update the result of scanning:
Start scanning → stop scanning → start scanning → stop scanning …


text:
Q: Tab Bar Controller items run from the right item I'm developing an iOS App for an Right-to-left language by using Tab Bar. Normally, when I try to start the application, the application will start from the left bar item.
My prblem is, I'm trying to let the application start from the right bar item.
I mean, for example, there are 4 items in the application, like [1 - 2 - 3 - 4]. When I run the application, it will open item "1". But, I'm trying to let the application run by opening item "4".
I'm using Xcode 6 and Objective C.

A: Tab bars will, by default, set the first item as the selected one unless you specify otherwise (either in code or in your storyboard / xib file). You can programmatically select the current item on your tab bar. For example:
[tabBar setSelectedItem:[tabBar.items objectAtIndex:4]];

Just keep in mind that the indices start at 0 so the indices are 0-1-2-3 and not 1-2-3-4.


text:
Q: Can't convert frozen model file .pb to .tflite import tensorflow as tf

path = "C:/Users/LAWSSSS/Desktop/convert_pb_2_tflite/frozen_inference_graph-SteelRoll.pb"

inputs = ["image_tensor"]
outputs = ["detection_boxes"]

converter = tf.lite.TFLiteConverter.from_frozen_graph(path, inputs, outputs, input_shapes={"image_tensor":[1,640,360,3]})
converter.post_training_quantize = True
tflite_model = converter.convert()

open("frozen_inference_graph-SteelRoll.tflite", "wb").write(tflite_model)

I'm new to Tensorflow in general. I tried to use the code above to convert a .pb to .tflite. However, I am getting an error:
array.data_type == array.final_data_type Array "image_tensor" has mis-matching actual and final data types (data_type=uint8, final_data_type=float).
Fatal Python error: Aborted

How do I solve this problem?

A: Change your model input (the image_tensor placeholder) to have data type tf.float32.


text:
Q: BarcodeRecognize can read Chinese,but why BarcodeImage can't make Chinese characters to QR image? For example:
Import["http://www.image-share.com/upload/2735/230.jpg"]
BarcodeRecognize@%

can give a String "别看我,我会害羞..."
but if I go on using BarcodeImage on the output:
BarcodeImage@%

It will throw a warning:

BarcodeImage called with 1 argument; 2 or 3 arguments are expected.

So how could I use BarcodeImage to make Chinese characters to QR image?

A: The problem seems to be a mixture of three things

*

*You didn't put all the necessary arguments for BarcodeImage

*BarcodeImage is limited on text encoding (against standards)

*The documentation is poor and does not describe the existing limitation

The good
img = Import["http://www.image-share.com/upload/2735/230.jpg"];
str = BarcodeRecognize@img

"别看我,我会害羞..."

Or as an image for poorly configured devices

So far so good
The bad
Now BarcodeImage needs to be called with two arguments, as the error you got explained.
Then do:
BarcodeImage["text", "QR"]

But not

The second arguments can be any of these:
1D: "UPC", "EAN8", "EAN13", "Code39", "Code128", "ITF", "Codabar"
2D: "Aztec", "DataMatrix", "QR", "PDF417"
The ugly
We get an error even for proper use, and the clue is in the error message
BarcodeImage[str, "QR"]

BarcodeImage::qr: Expecting a string of characters defined in ISO/IEC 8859-1 of length up to 2953, a string of alphanumeric characters of length 4296, or a string of digits of length up to 7089 instead of 别看我,我会害羞.... >>

I guess Chinese characters are not encoded in ISO/IEC 8859-1.
Shamefully the documentation says nothing about encoding limitations.
This is very unfortunate implementation from Mathematica, QR codes are supposed to accept various encodings .
Workaround
Wolfram alpha doesn't seem to have that limitation
WolframAlpha["QR code \"别看我,我会害羞...\""]

So you can get a clean output by
chineseQR[str_String] :=  WolframAlpha["QR code \"" <> str <> "\"", {{"QRCodeBarcode", 1}, "Content"}]

And for future use:
chineseQR[str]

A: yes, we can do this way:
 barcodeImage[x_String] :=ImageCrop@Image@Rasterize@WolframAlpha["QR code:" <> x,{{"QRCodeBarcode", 1}, "Content"}];

and then
barcodeImage@"中文"
BarcodeRecognize@%(*Chinese*)

will return the result!


text:
Q: Scraping data from individual results in a list of providers I'm trying to get addresses of all the therapists by given zip code. I want to input a zip code and get a list of result. Then, go into individual result and scrape the address of the provider.
I'm new to python. I've been trying to use requests and BeautifulSoup. Maybe using Selenium might be better?
import requests
from bs4 import BeautifulSoup

url = 'https://www.psychologytoday.com/us/therapists/60148'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}

page = requests.get(url, headers=headers)

print(page.content.decode())
soup = BeautifulSoup(page.text, 'html.parser')

myclass = soup.find_all(class_='result-row normal-result row')
print(myclass)

I'm stuck now. Not sure how to proceed.
PS. I am taking a python course as we speak. Please be kind.

A: Try this, you will get addresses of all the therapists by given zip code:
But this provides only 1-page number address list if you want to get all pages of the address then you should use selenium, will resolve your problem.
import requests
from bs4 import BeautifulSoup
from bs4.element import Tag

url = 'https://www.psychologytoday.com/us/therapists/60148'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}

page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.text, 'html.parser')
result = soup.find(class_='results-column')

addressArray = []

for tag in result:

    if isinstance(tag,Tag):
        _class = tag.get("class")

        if _class is None or _class is not None and "row" not in _class:
            continue

        link = (tag.find(class_='result-actions')).find('a',href=True)

        _href = link['href']

        address_link = requests.get(_href, headers=headers)
        soup1 = BeautifulSoup(address_link.text, 'html.parser')

        address = (soup1.find(class_='address')).find(class_="location-address-phone")

        text = ''
        for index,data in enumerate((address.text.strip()).split('\n')):
            if not data.strip():
                continue

            if not text:
                text = data.strip()
            else:
                text = text+","+data.strip()

        if text:
            addressArray.append(text)

print(addressArray)

O/P:
['Lia Reynolds, LCSW,Lombard, Illinois 60148,(630) 343-5819', 'Clarity Counseling and Wellness, LLC,477 Butterfield Road,#202,Lombard, Illinois 60148,(630) 656-9713', '450 East 22nd St.,Suite 172,Lombard, Illinois 60148,(773) 599-3959', '10 E 22nd Street,Suite 217,Lombard, Illinois 60148,(630) 517-9505', 'Ron Ahlberg & Associates,477 E Butterfield Rd,Suite 310,Lombard, Illinois 60148,(630) 451-8653', 'Health Transitions Counseling,477 Butterfield Road,Suite 310,Lombard, Illinois 60148,(630) 785-6642', 'Way Beyond Counseling and Coaching,477 E Butterfield Road,Floor 3 - Wellness Center - Office 7,Lombard, Illinois 60148,Call Mr. Larry Westenberg,(630) 556-8484', 'Chicago Area Behavioral Health Services,150 W St Charles Road,Lombard, Illinois 60148,Call Augustus Edeh. Chicago Area Behavioral Health Services,(630) 599-8032', 'Adult Children Center, Ltd,2 East 22nd Street,Suite 302,Lombard, Illinois 60148,(630) 387-9750', 'Midwest Center for Hope & Healing, Ltd.,1165 S Westmore-meyers Rd,Lombard, Illinois 60148,(630) 765-5355', 'Madrigal Consulting and Counseling, LLP,450 E. 22nd Street,Suite 150,Lombard, Illinois 60148,Call Cesar Madrigal,(630) 413-9942', '477 E Butterfield Rd,Suite 202,Lombard, Illinois 60148,(630) 560-6920', 'Lombard,Lombard, Illinois 60148,(630) 796-7904', 'Dupage Clinical Counseling Services,450 E 22nd St,150,Lombard, Illinois 60148,(630) 313-4990', '2200 S Main St,Suite 316,Lombard, Illinois 60148,(630) 426-7819', 'Institute for Motivational Development,10 E 22nd Street, Suite 217,Lombard, Illinois 60148,(309) 723-8170', 'Michele DeCanio Counseling Services,2200 S. Main Street,Suite 305,Lombard, Illinois 60148,(630) 560-6926', 'A New Day Counseling Center,450 E 22nd St,Suite 150,Lombard, Illinois 60148,(630) 748-8261', '477 E Butterfield Rd,Suite 310,Lombard, Illinois 60148,(630) 426-6878', 'Bricolage Wellness,477 Butterfield Road,Suite 202,Lombard, Illinois 60148,(630) 426-7823']

where 'result-actions' is action view button class to open new page, so it's required to make one more request to get full address.
"location-address-phone" is new address page class to scrape address.
Documentation link:
https://selenium-python.readthedocs.io/
https://www.crummy.com/software/BeautifulSoup/bs4/doc/


text:
Q: Identify if only the commit message has changed I have Gerrit working with Jenkins and I need to perform some actions in Jenkins but only if the CR sent to Gerrit did no change any file, i.e. an amend-last-commit action was made that only changed the commit message. Is there a way to collect this information with a git command, or any other mean?
Thanks