text:
Q: Маппинг строк из нескольких таблиц на структуру Я использую пакет github.com/go-sql-driver/mysql
У меня есть две таблицы:
create table users (
    id int auto_increment primary key,
    name varchar(256) not null,
    email varchar(256) not null,
    password varchar(255) not null,
    role tinyint(1) default 1 not null
);

create table posts (
    id int auto_increment primary key,
    title varchar(256) not null,
    content text not null,
    user_id int not null
);

и две модели:
type User struct {
    ID       uint64
    Name     string
    Email    string
    Password string
    Role     uint8
}

type Post struct {
    ID      uint64
    Title   string
    Content string
    Author User
}

Вытягиваю посты из базы:
func GetAll() []*models.Post {
    rows, err := core.GetDB().Query("select id, title, content from posts")
    if err != nil {
        fmt.Println(err)
    }
    defer rows.Close()

    posts := make([]*models.Post, 0)
    for rows.Next() {
        post := new(models.Post)
        err := rows.Scan(&post.ID, &post.Title, &post.Content)
        if err != nil {
            panic(err)
        }

        posts = append(posts, post)
    }
    if err = rows.Err(); err != nil {
        fmt.Println(err)
    }

    return posts
}

Как мне получить массив структур Post с вложенной структурой User в поле Author?
Конечно я могу добавить поле userId в структуру и получить пользователей отдельным запросом а потом подставить их туда, но в данном случае мне кажется лучше использовать join, но как мне подставить результаты запроса в нужные поля?

A: Не совсем понятно в чем сложность, попробуйте так:
func GetAll() []*models.Post {
    rows, err := core.GetDB().Query("select p.id, p.title, p.content, u.id, u.name, u.email from posts p inner join users u ON u.id = p.user_id")
    if err != nil {
        fmt.Println(err)
    }
    defer rows.Close()

    posts := make([]*models.Post, 0)
    for rows.Next() {
        post := new(models.Post)
        user = new(models.User)
        err := rows.Scan(&post.ID, &post.Title, &post.Content, &user.ID, &user.Name, &user.Email)
        if err != nil {
            panic(err)
        }
        post.Author = *user

        posts = append(posts, post)
    }
    if err = rows.Err(); err != nil {
        fmt.Println(err)
    }

    return posts
}


text:
Q: echo specific part of array in php I'm still learning php arrays and I'm trying to echo a
array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=> string(5) "title" [3]=> string(11) "description" [4]=> string(4) "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=> string(12) "image:height" } NULL site_name => Playbuzzurl => http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842

array(8) { [0]=> string(9) "site_name" [1]=> string(3) "url" [2]=>
  string(5) "title" [3]=> string(11) "description" [4]=> string(4)
  "type" [5]=> string(5) "image" [6]=> string(11) "image:width" [7]=>
  string(12) "image:height" } NULL site_name => Playbuzzurl =>
  http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personalitytitle
  => What Modern Societal Archetype Fits Your Personality?description => It's 2017, so it's about time we update the books!type => articleimage
  => http://cdn.playbuzz.com/cdn/aef166e1-1574-4d57-9823-3f38f30bcfc4/810f1d3e-0a97-4797-8235-b4c988562a1c.jpgimage:width => 1600image:height => 842

I'm trying to echo just the value for description which is It's 2017, so it's about time we update the books!
I've tried several different things, but nothing works. Any help is greatly appreciated.
echo $array[0]['description'];      // returns nothing
var_dump($key);                     // returns string(12) "image:height"

Current Code
<?php
require_once('OpenGraph.php');

$graph = OpenGraph::fetch('http://www.playbuzz.com/jordonr10/what-modern-societal-archetype-fits-your-personality');
var_dump($graph->keys());
var_dump($graph->schema);

foreach ($graph as $key => $value) {
    echo "$key => $value

";
}
echo "Value Below
";
echo $array['description'];

?>

A: From your code its seems that you can directly get value of description from $graph if key is already there.
 Also you are trying to diplay $array['description'];  here I can see $array is define any where
try to
 echo $graph['description']; // if $graph is array

OR
echo $graph->description; // If its an object

A: Just call
echo $array[3];

Or use associative arrays which can be called
echo $array['description'];

http://php.net/manual/en/language.types.array.php

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP preg_replace with SQL I'm trying to replace a simple command from a basic CMS with a database call.
The user enters
[gallery id=x]

into the CMS, and I want this to go away, find the images included in that gallery, and display them (ready for the jQuery Cycle plugin)
I can get:
$pattern = '/\[gallery id=(\w+)\]/i';
$rpl     = 'Display Gallery ID ${1}';
$bubble  = preg_replace($pattern, $rpl, $bubble);

...which returns "Display Gallery 12" (for example). However I need it to do this:
$sql = "SELECT * FROM galleries INNER JOIN photos ON photos.PhotoGallery=galleries.GalleryID WHERE GalleryID='x'";
$set = mysql_query($sql);
echo '
';
while($row = mysql_fetch_array($set))
{
 echo '';
}
echo '
';

A: You can use the preg_replace_callback function, which takes each match your regular expression finds and replaces it with the string returned from a provided callback.  So you could do something like:
function generateGallery($matches) {
    // generate the string here, $matches[1] will be your gallery id
    return "Gallery Content for Gallery " . $matches[1];
}

$pattern = '/\[gallery id=(\w+)\]/i';
$bubble = preg_replace_callback($pattern, generateGallery, $bubble);

A: Use:
preg_match($pattern, $string, $matches);

After this, the ID is in $matches[1].


text:
Q: Net Core: Code Generation for IEquatable/Equals for Comparing Two Class Models We scaffolded database from Entity Framework to create class models. We have over 1000 classes. Now we're implementing unit tests, to compare classes inserting an Actual class with Expected class. The following website recommends method below to compare all Members.
Do I have to write this for all my 1000+ classes? Or is there a way to use auto code generate in Visual Studio to create all these IEquatable? Maybe with T4?
https://grantwinney.com/how-to-compare-two-objects-testing-for-equality-in-c/
public class Person : IEquatable<Person>
{
    public string Name { get; set; }
    public int Age { get; set; }

    public bool Equals(Person other)
    {
        if (ReferenceEquals(other, null))
            return false;

        if (ReferenceEquals(this, other))
            return true;

        return Name.Equals(other.Name) && Age.Equals(other.Age);
    }

https://learn.microsoft.com/en-us/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2019
Teamwork Guy answer below is nice, need to way to implement this kind of method for 1000+ classes.

A: If you are only implementing Equals for test assertions, I would use a library like FluentAssertions to do assertions. The various BeEquivalentTo methods compare object graphs and give detailed error messages (e.g. expected Age to be x but was y) which are often better than what you will get out of implementing your own Equals methods. It integrates with all the major test frameworks out of the box (mstest, nunit, xunit.net).

A: Yes, it appears possible in Visual Studio >=2017 or using ReSharper:
https://stackoverflow.com/a/48441971
https://learn.microsoft.com/en-us/visualstudio/ide/reference/generate-equals-gethashcode-methods?view=vs-2017
This would still be time consuming for 1000+ classes. You might look into Visual Studio's APIs for plugin development to see if you could programmatically trigger this option for a whole list of files.


text:
Q: gluPerspective parameters- what do they mean? I wonder about the gluPerspective parameters.
In all examples I see fovy is set to around 45-60degrees
I've tried to set it to different values and the object just disappears
what's the explanation for it?
The aspect value should always be the ratio? why would one change it?
zNear, zFar - once again the usual values are around 10 and 500+ what does it reflect?

A: The purpose of the 4 parameters is to define a view frustum, like this:

where nothing outside of the frustum should be is visible on screen ( To accomplish this, the parameters are used to calculate a 4x4 matrix, which is then used to transform each vertex into the so-called clip space. There, testing if a vertex is inside the frustum or not is trivial )
The field of view parameter is basically the angle in between a plane passing through the camera position as well as the top of your screen & another plane passing through the camera position and the bottom of your screen. The bigger this angle is, the more you can see of the world - but at the same time, the objects you can see will become smaller.
To observe its influence, I'd suggest coding a simple app where you can gradually increase / decrease the fov via keypress - then render some spheres or other basic objects & see what happens as you change it.
The aspect ratio is your viewport's aspect ratio. ( In the graphic above, the viewport is located at the the near clipping plane ) Being able to define it at will makes sense, since your viewport's aspect ratio may vary.
The zNear & zFar values define the distance between the camera position & the near and far clipping planes, respectively. Nothing that's closer to the camera than zNear or farther away than zFar will be visible. Both values must be > 0, and obviously, zFar > zNear.
zFar should ideally be chosen so that everything you want to render is visible, but making it larger than necessary wastes depth buffer prescision & may lead to flickering effects, called z-fighting. Likewise, setting zNear too close to the camera may cause the same effect - in fact, having a reasonable zNear value is more important than zFar. If you want to know exactly why this happens, you should read some in-depth explanations, like this one or this one


text:
Q: Confused about wildcard generic types in Java I'm a beginner in Java and I'm having a hard time understanding the wildcard generic types. Can anyone help me understand why the following two lines are incorrect?
LinkedList<? extends List> list1 = new LinkedList<ArrayList>();
LinkedList<? super List> list2 = new LinkedList<Collection>();

When I tried to compile them, I got the following error message:
Test.java:13: error: incompatible types: LinkedList<ArrayList> cannot be converted to LinkedList<? extends List>
    LinkedList<? extends List> list1 = new LinkedList<ArrayList>();
                                       ^
Test.java:14: error: incompatible types: LinkedList<Collection> cannot be converted to LinkedList<? super List>
    LinkedList<? super List> list2 = new LinkedList<Collection>();
                                     ^
2 errors

A: if we break down the first, it might make a bit more sense:
LinkedList<? extends List> list1

you declare list1 to be a LinkedList whose element type can be compatable with any subclass of List.
list1 = new LinkedList<ArrayList>();

you then try to instantiate list1 as a LinkedList whose element type is restricted to ArrayList. That's probably why the compiler complains about the incompatable types for that first line. You need to make sure the generic type for the declaration and instantiation of List1 are compatable, like so:
LinkedList<? extends List> list1 = new LinkedList<? extends List>();

I was mistaken. The compiler throws an error for the above line. This line does work though and is probably what you want:
LinkedList<List> list1 = new LinkedList<List>();

check out example code here
As of java 7, you can use the diamond operator to infer the generic type in the instantiation part:
list1 = new LinkedList<>();


text:
Q: Differences between observations of light versus gravity for a satellite traveling by the sun A satellite travels in a geodesic by the sun with sufficient velocity to escape the sun's orbit.  The distance of closest approach is 100 light seconds when the satellite's velocity is perpendicular to the sun as observed by light.  At this point in time, t = 0, the satellite will compare 2 observations: the direction from the satellite to the center of the sun's light with the direction from the satellite to the perceived force of gravity from the sun. Are they perfectly aligned or is there any difference, even if very small? Want to isolate how the sunlight might be affected by the sun's gravitational field versus how propagation of the sun's gravitational field might be affected by the field itself.

A: Answer from Safesphere's link: https://arxiv.org/abs/gr-qc/9909087v2, "Does eqn. (2.4) imply that gravity propagates instantaneously? ...it clearly does not...Indeed, the vector (2.5) does not point toward the "instantaneous"
position of the source, but only toward its position extrapolated from this retarded data...Indeed, it can be rigorously proven that no gravitational influence in general relativity can travel faster than the speed of light"
This resolves how celestial objects are attracted to the instantaneous position of other celestial objects by gravity (i.e. not delayed by propagation at c), but also how massive objects outside our light event horizon are also outside our gravitational event horizon. (See correctly answered Can gravity from a massive object outside our cosmological event horizon have any effect on Earth?) Thank you, Safesphere, for the excellent resource.


text:
Q: change bootstrap grid direction dynamically ( ltr to rtl or reverese) We are making a site which  will work both Rtl and Ltr ( En and Fa ).
We want to use tweeter bootstrap (3.*) .
Our mvc is made upon php .
Is it possible to use bootstrap which it's grid flow order is  Rtl  if the site language is fa , and use Ltr when the language is English ?
By language , I mean this : www.example.com/en   or www.example.com/fa
when it is /en , we must use bootstrap which is Ltr (Left to right )
when it is /fa , we must use bootstrap which is Rtl (Right to left)
I know there are some bootstrap themes that I can use which are Rtl , but how can I use both rtl and ltr and changed within them dynamically ? ( maybe after a page refresh site direction goes Rtl or Ltr !!) ?

A: Simply change float:left; to float:right; in grid system when html tag has dir='rtl'.
Here is the css:
html[dir="rtl"] .row > .col-xs-1, html[dir="rtl"] .row > .col-xs-2, html[dir="rtl"] .row > .col-xs-3, html[dir="rtl"] .row > .col-xs-4, html[dir="rtl"] .row > .col-xs-5, html[dir="rtl"] .row > .col-xs-6, html[dir="rtl"] .row > .col-xs-7, html[dir="rtl"] .row > .col-xs-8, html[dir="rtl"] .row > .col-xs-9, html[dir="rtl"] .row > .col-xs-10, html[dir="rtl"] .row > .col-xs-11, html[dir="rtl"] .row > .col-xs-12 {
  float: right;
}
@media (min-width: 768px) {
  html[dir="rtl"] .row > .col-sm-1, html[dir="rtl"] .row > .col-sm-2, html[dir="rtl"] .row > .col-sm-3, html[dir="rtl"] .row > .col-sm-4, html[dir="rtl"] .row > .col-sm-5, html[dir="rtl"] .row > .col-sm-6, html[dir="rtl"] .row > .col-sm-7, html[dir="rtl"] .row > .col-sm-8, html[dir="rtl"] .row > .col-sm-9, html[dir="rtl"] .row > .col-sm-10, html[dir="rtl"] .row > .col-sm-11, html[dir="rtl"] .row > .col-sm-12 {
    float: right;
  }
}
@media (min-width: 992px) {
  html[dir="rtl"] .row > .col-md-1, html[dir="rtl"] .row > .col-md-2, html[dir="rtl"] .row > .col-md-3, html[dir="rtl"] .row > .col-md-4, html[dir="rtl"] .row > .col-md-5, html[dir="rtl"] .row > .col-md-6, html[dir="rtl"] .row > .col-md-7, html[dir="rtl"] .row > .col-md-8, html[dir="rtl"] .row > .col-md-9, html[dir="rtl"] .row > .col-md-10, html[dir="rtl"] .row > .col-md-11, html[dir="rtl"] .row > .col-md-12 {
    float: right;
  }
}
@media (min-width: 1170px) {
  html[dir="rtl"] .row > .col-lg-1, html[dir="rtl"] .row > .col-lg-2, html[dir="rtl"] .row > .col-lg-3, html[dir="rtl"] .row > .col-lg-4, html[dir="rtl"] .row > .col-lg-5, html[dir="rtl"] .row > .col-lg-6, html[dir="rtl"] .row > .col-lg-7, html[dir="rtl"] .row > .col-lg-8, html[dir="rtl"] .row > .col-lg-9, html[dir="rtl"] .row > .col-lg-10, html[dir="rtl"] .row > .col-lg-11, html[dir="rtl"] .row > .col-lg-12 {
    float: right;
  }
}

A: You can modify CSS rules "on the fly", attached here is a function, it modifies the major classes for Bootstrap 3 like col-(xs|sm|md|lg)-(1-12), col-(xs|sm|md|lg)-push-(1-12), col-(xs|sm|md|lg)-pull-(1-12), col-(xs|sm|md|lg)-offset-(1-12), there are many more classes to be modified but i needed only those.
All you need to do is call the function layout.setDirection('rtl') or layout.setDirection('ltr') and it will change the CSS Rules.
Should work on all browsers (IE>=9).
        var layout = {};
        layout.setDirection = function (direction) {
            layout.rtl = (direction === 'rtl');
            document.getElementsByTagName("html")[0].style.direction = direction;
            var styleSheets = document.styleSheets;
            var modifyRule = function (rule) {
                if (rule.style.getPropertyValue(layout.rtl ? 'left' : 'right') && rule.selectorText.match(/\.col-(xs|sm|md|lg)-push-\d\d*/)) {
                    rule.style.setProperty((layout.rtl ? 'right' : 'left'), rule.style.getPropertyValue((layout.rtl ? 'left' : 'right')));
                    rule.style.removeProperty((layout.rtl ? 'left' : 'right'));
                }
                if (rule.style.getPropertyValue(layout.rtl ? 'right' : 'left') && rule.selectorText.match(/\.col-(xs|sm|md|lg)-pull-\d\d*/)) {
                    rule.style.setProperty((layout.rtl ? 'left' : 'right'), rule.style.getPropertyValue((layout.rtl ? 'right' : 'left')));
                    rule.style.removeProperty((layout.rtl ? 'right' : 'left'));
                }
                if (rule.style.getPropertyValue(layout.rtl ? 'margin-left' : 'margin-right') && rule.selectorText.match(/\.col-(xs|sm|md|lg)-offset-\d\d*/)) {
                    rule.style.setProperty((layout.rtl ? 'margin-right' : 'margin-left'), rule.style.getPropertyValue((layout.rtl ? 'margin-left' : 'margin-right')));
                    rule.style.removeProperty((layout.rtl ? 'margin-left' : 'margin-right'));
                }
                if (rule.style.getPropertyValue('float') && rule.selectorText.match(/\.col-(xs|sm|md|lg)-\d\d*/)) {
                    rule.style.setProperty('float', (layout.rtl ? 'right' : 'left'));
                }
            };
            try {
                for (var i = 0; i < styleSheets.length; i++) {
                    var rules = styleSheets[i].cssRules || styleSheets[i].rules;
                    if (rules) {
                        for (var j = 0; j < rules.length; j++) {
                            if (rules[j].type === 4) {
                                var mediaRules = rules[j].cssRules || rules[j].rules
                                for (var y = 0; y < mediaRules.length; y++) {
                                    modifyRule(mediaRules[y]);
                                }
                            }
                            if (rules[j].type === 1) {
                                modifyRule(rules[j]);
                            }

                        }
                    }
                }
            } catch (e) {
                // Firefox might throw a SecurityError exception but it will work
                if (e.name !== 'SecurityError') {
                    throw e;
                }
            }
        }

A: Have you tried just flipping all float:left; to float:right on the major grid entities and serving that as a Rtl specialized CSS file / override?

A: I'll give you some hint for scripting this in JavaScript until the native support in feature versions of Bootstrap framework.
you can use pull and push features in grid system in Tweeter Bootstrap. for changing the order of grids. here's an example:

.col-md-9 .col-md-push-3

.col-md-3 .col-md-pull-9

You can create a script to check the language and add appropriate push and pull classes to the grids.


text:
Q: PostgreSQL id column not defined I am new in PostgreSQL and I am working with this database.
I got a file which I imported, and I am trying to get rows with a certain ID. But the ID is not defined, as you can see it in this picture:

so how do I access this ID? I want to use an SQL command like this:
SELECT * from table_name WHERE ID = 1;

A: If any order of rows is ok for you, just add a row number according to the current arbitrary sort order:
CREATE SEQUENCE tbl_tbl_id_seq;
ALTER TABLE tbl ADD COLUMN tbl_id integer DEFAULT nextval('tbl_tbl_id_seq');

The new default value is filled in automatically in the process. You might want to run VACUUM FULL ANALYZE tbl to remove bloat and update statistics for the query planner afterwards. And possibly make the column your new PRIMARY KEY ...
To make it a fully fledged serial column:
ALTER SEQUENCE tbl_tbl_id_seq OWNED BY tbl.tbl_id;

See:

*

*Creating a PostgreSQL sequence to a field (which is not the ID of the record)

A: What you see are just row numbers that pgAdmin displays, they are not really stored in the database.
If you want an artificial numeric primary key for the table, you'll have to create it explicitly.
For example:
CREATE TABLE mydata (
   id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
   obec text NOT NULL,
   datum timestamp with time zone NOT NULL,
   ...
);

Then to copy the data from a CSV file, you would run
COPY mydata (obec, datum, ...) FROM '/path/to/csvfile' (FORMAT 'csv');

Then the id column is automatically filled.


text:
Q: What is the use of @namespace in CSS? From the doc, I found the use of namespace like below:
@namespace foo url(http://www.example.com);
 foo|h1 { color: blue }

But I want to know more about this. Why do we use it?

A: In your given example, the color: blue rule will be limited to only h1 elements in the foo namespace (linked by url(example.com)).
To my knowledge, it's regarded as not often needed. And it certainly looks weird.
Here's a nice summary of its application: http://nimbupani.com/spacing-out-on-css-namespaces.html

The only thing it defines is how to declare an XML namespace prefix in CSS. That is needed if you want to use selectors that only match elements in a certain namespace.
For example, SVG shares some common elements (e.g. <a>) and CSS properties with HTML with XML and HTML. If you are using the same stylesheet for both HTML and SVG documents, then it is best to separate out the styles for SVG and HTML to prevent any overlap. …

Here's a nice step-by-step breakdown of its parts:

@namespace declares the default namespace and binds a namespace to a namespace prefix. The default namespace is applied to names that do not have an explicit namespace component. … If you declare an @namespace rule with a prefix, you can use the prefix in namespace-qualified names. …

And finally, here's MDN's doc: https://developer.mozilla.org/en-US/docs/Web/CSS/@namespace

The @namespace rule is an at-rule that defines the XML namespaces that will be used in the style sheet. The namespaces defined can be used to restrict the universal, type, and attribute selectors to only select elements under that namespace. The @namespace rule is generally only useful when dealing with an XML document containing multiple namespaces—for example, an XHTML document with SVG embedded.
The @namespace rule can be used to define the default namespace for the style sheet. When a default namespace is defined, all universal and type selectors (but not attribute selectors, see note below) apply only to elements on that namespace.
The @namespace rule can also be used to define a namespace prefix for a style sheet. When a universal, type, or attribute selector is prefixed with a namespace prefix, then that selector only matches if the namespace (and not just the name in the case of type or attribute selectors) of the element or attribute matches.
When using non-XML HTML, known elements will be automatically be assigned namespaces. This means that HTML elements will act as though they are on the XHTML namespace, even if there is no xmlns attribute anywhere in the HTML document.
Note that in XML, unless a prefix is defined directly on an attribute, that attribute has no namespace. In other words, attributes do not inherit the namespace of the element they're on. To match this behaviour, the default namespace in CSS does not apply to attribute selectors.

A: From MSDN

The HTML namespace is treated specially when browsing XML with CSS. Elements from the HTML namespace are displayed as they would appear in HTML. This allows access to capabilities that are not yet provided by CSS. Some examples of useful HTML elements to embed are <TABLE>, <A>, <IMG>, <SCRIPT>, and <STYLE>.
For example, you can add a link and logo to the following restaurant review sample. First, you must declare the HTML namespace at the top of the document, and then use the HTML prefix on the embedded HTML elements. HTML embedded this way must be well-formed XML, so the <IMG> element needs a minimized end tag.
<story xmlns:HTML="http://www.w3.org/Profiles/XHTML-transitional">
  ...
  <restaurant>
    <name>Red Apple Inn</name>
    <logo>
      <HTML:A href="javascript:alert('Visit the Red Apple Inn!')">
        <HTML:IMG src="red-apple.gif" height="50" width="200"/>
      </HTML:A>
    </logo>
    ...

In Microsoft® Internet Explorer, the prefix must remain HTML or html in order for the elements to be interpreted as HTML elements.
An <HTML:STYLE> block can be used to embed a CSS style sheet within an XML document. This block will augment any style sheets pointed to by style sheet processing instructions. When there is no external style sheet, there still must be a style sheet processing instruction present to indicate that the XML document should be displayed using the CSS style sheet language, even though no href attribute is specified.
The following example shows how the review.css style sheet can be embedded into the XML document using the HTML namespace, the <HTML:STYLE> element, and the style sheet processing instruction without an href attribute.
  HTML
<?xml version="1.0"?>
<?xml-stylesheet type="text/css"?>
<story xmlns:HTML="http://www.w3.org/Profiles/XHTML-transitional">
  <HTML:STYLE>
    story
    {
      display: block;
      font-family: Arial, Helvetica, sans-serif;
      font-size: small;
      width: 30em;
    }
    restaurant
    {
      display: block;
      padding: 1.2em;
      font-size: x-small;
      margin-bottom: 1em;
    }
    ...
  </HTML:STYLE>
  <restaurant>
    ...


text:
Q: Migration from Oracle to MySql I want to migrate from oracle to MySql. I am using MySql Migration tools 5.0.
Something went wrong in Migration wizard.

Error message is
Connecting to source database and retrieve schemata names.
Initializing JDBC driver ...
Driver class Oracle Thin JDBC Driver using Service
Opening connection ...
Connection jdbc:oracle:thin:system/**********@//127.0.0.1:1521/OracleServiceXE
The list of schema names could not be retrieved (error: 0).
ReverseEngineeringOracle.getSchemata :Listener refused the connection with the following error:
ORA-12514, TNS:listener does not currently know of service requested in connect descriptor
The Connection descriptor used by the client was:
//127.0.0.1:1521/OracleServiceXE

Details:
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:280)
oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:328)
oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:361)
oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:151)
oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:595)
java.sql.DriverManager.getConnection(Unknown Source)
java.sql.DriverManager.getConnection(Unknown Source)
com.mysql.grt.modules.ReverseEngineeringGeneric.establishConnection(ReverseEngineeringGeneric.java:141)
com.mysql.grt.modules.ReverseEngineeringOracle.getSchemata(ReverseEngineeringOracle.java:43)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.mysql.grt.Grt.callModuleFunction(Unknown Source)

Both SQL servers are running on localhost.
How can I solve these errors ?

A: You can add the used service name to the oracle database, or modify the entered value 'OracleServiceXE' to the correct value 'XE'. The entered value looks a lot like the default windows service name and could be confused with the Oracle database service name.
To change the current instance service name to OracleServiceXE:
alter system set service_name = 'OracleServiceXE';

lsnrctl services
should also show the service name after wards, unless the database instance is in restricted state, in that case the connection using a service name will fail.

A: It looks to me that your jdbc connection URL for Oracle is wrong. Typically it looks something like this:
jdbc:oracle:thin:@localhost:1521:xe

What happens if you remove the double slashes // and replace the slash / between 1521/OracleServiceXE by a colon : ?


text:
Q: firemonkey xe5 save captured image with specified name In firemonkey xe5 there was sample how to capture image and show it as a bitmap, is it possible to change the image name, right after capturing, with a source code?
I've tried to use this code :
Image.SaveToFile(GetHomePath + PathDelim + 'myimage.jpg')

on this procedure :
procedure TForm2.TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap);
begin

end;

but nothing happened.


text:
Q: Not well-formed error at the end As you can see I tries to make a very simple XML example with PHP. My problem is that at the end, at </users> I get an XML Parsing Error: not well-formed and I do not understand why since I do not use any special characters or any URLs. Does anyone have any ideas what the problem might be?

<?php
    header('Content-type: text/xml');

    $xml = "<?xml version=\"1.0\" ?>\n";
    $xml .= "<users>\n";
    $xml .= "test\n";
    $xml .="</users>";
    echo $xml;
?>

A: Problem solved. The solution was posted in this thread: Extra content at the end of the document PHP and XML
In short, I had to open the file with HexEdit and delete some characters.


text:
Q: Array of pointers using malloc : The code runs into a segmentation fault. Help! Thanks it seems I'm a bit confused here. As with the use of a pointer to an array of pointers. if I could fetch more info regarding the error, I would have. All I received is a code for a segmentation fault. Thanks :)
a program to find the longest input string.
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

int main()
{
 char **array;
 int i, n, *L, maxlen;

 printf("Enter the number of strings that you wish to store : ");
 scanf("%d", &n);

 array=malloc(n*sizeof(char*)); //acquire storage for an array of pointes of size n//
 L=malloc(sizeof(int)*n);// for the length array//
 for(i=0;i<n;i++)
 {
    printf("Enter string %d : ", i+1); //sometimes, prints upto this//
    gets(array[i]); //sometimes skips the first string input and jumps to the second and stops at the third//
    L[i]=strlength(array[i]);
 }
 maxlen=0;
 for(i=0;i<n;i++)
 {
    if(L[i]>maxlen)
        maxlen=L[i];
 }

  printf("The string(s) with the maximum length with length %d are : ", maxlen);
 for(i=0;i<n;i++)
 {
     if(L[i]==maxlen)
    {
        printf("\n%s.", array[i]);
    }
 }
  return 0;
 }

int strlength(char *array)
{
int j=0;
while(array[j]!='\0')
  {

    j++;
  }
return j;
}

A: you allocated memory for pointer to pointer, but forgot to allocate for individual pointers( ie the strings).
it can be modified as,
array=malloc(n*sizeof(char*));

to allocate memory for storing all the pointers for the strings.
and
for( i = 0; i<n; i++)
{
     array[i] = malloc(<max length of string>);
}

then only you will have memory space allocated to store the strings

A: Your memory allocation for:
char **array;
array=malloc(n*sizeof(char*)); //acquire storage for an array of pointes of size n//

only allocates memory for a set of pointers, but none for the space that is needed for the strings the pointers will point to.  A function can be defined to encapsulate these steps:
char **array = Create2DStr(numberOfStrings, maxLengthOfString);

Where Create2DStr can be implemented as follows:
char ** Create2DStr(ssize_t numStrings, ssize_t maxStrLen)
{
    int i;
    char **a = {0};
    a = calloc(numStrings, sizeof(char *));// Creates a set of pointers.
    for(i=0;i<numStrings; i++)
    {
      a[i] = calloc(maxStrLen + 1, 1);//creates space for strings pointed to.
    }
    return a;
}

Caution:
 - If creating memory in a loop using the same pointer, you should be familiar with realloc()
 - maxStrLen in example should contain 1 byte more than the length of the longest string you need to accommodate.
 - Do not forget to free everything you created in the reverse order they were created, i.e. free space for strings first (maxStrLen calls to free()), then free the pointers to each string last (1 call to free())).   See following example:
free2DStr(&array,numStrings);

The implementation of free2DStr can be done many ways, see below for an example.
void free2DStr(char *** a, ssize_t numStrings)
{
    int i;
    if(!(*a)) return;
    for(i=0;i<numStrings; i++)
    {
        if((*a)[i])
        {
            free((*a)[i]);
            (*a)[i] = NULL;
        }
    }
    free((*a));
    (*a) = NULL;
}

Note that in this implementation the address of the object is used in the first argument to provide access to free the pointers residing at that location.


text:
Q: Throughput Shaping Timer, TPS distribution inside the scenario I have a question that has to do with the Throughput Shaping Timer usage. Maybe I have to use another plugin to cover my demand, but anyway I decided at least to investigate it and understand the behavior.
The task - emulate 20 TPS on the platform for the following user scenario:

But with the strict TPS distribution:

*

*Login - 1 TPS

*Get user info - 6 TPS

*Search - 12

*Logout - 1 TPS

Throughput Shaping Timer investigation
I made the following:

*

*Added the "Concurrency thread group" with flexible settings, just to be lazy and delegate the threads set up to the plugin.

*Added the "Throughput shaping timer"

Results/questios:

*

*I got 4.8 TPS on average for all requests (I suppose it's expected for the current flow)

*General TPS time to time is more than 20 TPS set in the test. Is it OK, or some settings are incorrect? from my understanding the peaks are too high..

*Some requests have TPS peaks, looks not very good due to peaks

So the questions:

*

*Is it possible to apply some tunings (or set/change flow) for the current stack of the tools ("Concurrency thread group" with flexible settings and "Throughput shaping timer") to distribute target 20 TPS like described in the task?

*How "Throughput shaping timer" divide the TPS between threads?

*Please suggest the best solution for the current task

Many thanks

A: Different throughputs is not something you can achieve within the bounds of a single Thread Group because according to JMeter threads model JMeter waits for the previous response before starting the next request therefore all your scenarios will act at the speed of the slowest one.
So you need to split your requests and put each one under the separate Thread Group and apply the throughput shaping individually.
If you need to pass some data like cookies or tokens from the "Login" sampler to other thread groups you either need to convert them into JMeter Properties using __setProperty() function in the "Login" thread group and __P() function in other thread groups or go for Inter-Thread Comminucation Plugin


text:
Q: About order of $q \pmod {p^n}.$ How to prove this affirmation:

If $q$ has order $\phi (p^n) \pmod{p^n}$, so $q$ also has order $\phi (p^{n-i+1})\pmod{p^{n-i+1}}$ , $1 \leq i \leq n$, where $\gcd(q,p)=1$ and $\phi$ is the Euler's totient function.

A: If the different powers of $q$ hit every possible (i.e. coprime to $p$) congruence class modulo $p^n$ (which is what it means that $q$ has order $\phi(p^n)$), then they necessarily have to hit every possible congruence class modulo smaller powers of $p$ as well.


text:
Q: Specify order of nunit tests running on teamcity Is it possible to specify the order in which nunit tests are run in teamcity?
If yes, how to do that? These tests are data heavy, and I want to avoid populating the data for them each time. The data is populated in the testfixture, and if ordering works, I don't need to setup my data for each test.

A: To sum up the comments, the tests are executed alphabetically. However, I did not want to rename the tests with prefixes such that they ran in some particular order. And taking into consideration Jon's comment, I moved data setup to test setup from test fixture.


text:
Q: Можно ли вызвать метода класса без вызова конструктора? Можно ли вызвать метода класса без вызова конструктора?
UPD1
Пытаюсь сделать следующее:
 $this->CI->load->library('countrylang');
 $this->CI->countrylang->_getSux(); Где _getSux() статический метод

A: статистические методы класса
static

UPD1
Где _getSux() статический метод - Метод какого класса?


text:
Q: PnPJS Search not returning results when running as SharePoint Add-In I have a NodeJS process using PnPJs library authentified with a SharePoint Add-In (clientId and clientSecret). When executing the following function, I receive no results.
const result = await sp.search({
    Querytext: "contenttype:MYCT 97021520"
  })

But the same request made in SPEditor on chrome, or in a SPFx WebPart return the results expected.
Or my SharePoint Add-In has the following permissions :
<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/taxonomy" Right="Write" />
    <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>

It worked previously and I didn't saw any changes in SharePoint Search API.
Can someone help please?
Thanks


text:
Q: DXF File with text labels not showing in QGIS I convert a CDR. file to SVG. using cloudconvert then i opened the SVG. file in Adobe Illustrator it was a vector map with text labels. I then export the file from Adobe Illustrator in DXF. format. I opened the DXF as vector layer in QGIS but the text labels are gone. What should i do?

A: You can setup labeling manually via layer setting dialog. Select "Text" filed as label source.


text:
Q: how to lock global data and its mutex as a reference object? Can some one explain whats wrong in below code?
struct CSection {
    CSection( pthread_mutex_t* mP )     {
        m_lockPtr = mP;
        pthread_mutex_lock( m_lockPtr );
    }
    ~CSection()     {
        pthread_mutex_unlock( m_lockPtr );
    }

    pthread_mutex_t* m_lockPtr;
};

////////////////MAIN CODE ///////////////////
std::list<ABC> gMap;
pthread_mutex_t gMut;

//MultiThread API call
push(const ABC& obj) {
    pthread_mutex_t& lock = gMut;
    std::list<ABC>& m = gMap;
    {
        CSection CC (lock);
        m.push_back(obj);
    }
}

Above is just a code snippet/sample.
Please explain is it ok to create local reference object and then call crticial section code ?
if not ok then kindly elaborate what will go wrong with above code.

A:
Please explain is it ok to create local reference object and then call crticial section code ?

It's unclear what problem you suppose there might be.  In comments you mention a data race, but it's unclear why you think that accessing either mutex or protected data through a reference would inherently create any more risk of a data race than accessing them directly would present.  A reference, including a reference to a mutex, is a functional stand-in for the object bound to it.


text:
Q: Conditional expectation on more than one sigma-algebra I'm facing the following issue. Let $X$ be an integrable random variable on the probability space $(\Omega,\mathcal{F},\mathbb{P})$ and $\mathcal{G},\mathcal{H} \subseteq \mathcal{F}$ be two sigma-algebras. We assume that $X$ is independent of $\mathcal{G}$, i.e. $\sigma(X)$ is independent of $\mathcal{G}$. Can I say (and can I prove) that $$ E(X \mid \sigma(\mathcal{G} \cup \mathcal{H})) = E(X\mid \mathcal{H}) ?$$
Thank you very much for your help!

A: If you're willing to assume that $\sigma(\sigma(X)\cup \mathcal{H})$ is independent of $\sigma(\mathcal{G})$ and that $X$ is integrable, then the assertion is indeed true. We need to show that
$$
E[X\mid \sigma(\mathcal{G}\cup\mathcal{H})]=E[X\mid\mathcal{H}],
$$
that is, we need to show that $E[X\mid\mathcal{H}]$ can serve as the conditional expectation of $X$ given $\sigma(\mathcal{G}\cup\mathcal{H})$, i.e. show that

*

*$E[X\mid\mathcal{H}]$ is $\sigma(\mathcal{G}\cup\mathcal{H})$-measurable,

*$E[X\mid\mathcal{H}]$ is integrable,

*for all $A\in\sigma(\mathcal{G}\cup\mathcal{H})$: $$\int_A E[X\mid\mathcal{H}]\,\mathrm dP=\int_A X\,\mathrm dP.$$

The first two are obvious. For the third, note that (by linearity, we can assume that $X$ is non-negative)
$$
\sigma(\mathcal{G}\cup\mathcal{H})\ni A\mapsto \int_AE[X\mid\mathcal{H}]\,\mathrm dP
$$
and
$$
\sigma(\mathcal{G}\cup\mathcal{H})\ni A\mapsto \int_A X\,\mathrm dP
$$
are two measures defined on $\sigma(\mathcal{G}\cup\mathcal{H})$ with equal total mass being $E[X]$. Hence, it is enough to show that the two measures are identical on some $\cap$-stable generator of $\sigma(\mathcal{G}\cup\mathcal{H})$. Here, we use that
$$
\{A\cap B\mid A\in\mathcal{G},\,B\in\mathcal{H}\}
$$
is indeed a $\cap$-stable generator of $\sigma(\mathcal{G}\cup\mathcal{H})$ (why?) and hence it suffices to show that
$$
\int_{A\cap B} E[X\mid \mathcal{H}]\,\mathrm dP=\int_{A\cap B} X\,\mathrm dP,\quad A\in\mathcal{G},\,B\in\mathcal{H}.
$$
Try to show this using the independence assumption. I think it will be clear to you that we in fact need the stronger independence assumption.
A counterexample showing that we indeed need the stronger assumption is the following: Let $U$ and $V$ be i.i.d. symmetric Bernoulli variables (i.e. $P(U=-1)=P(U=1)=\tfrac12$), $\mathcal{G}=\sigma(U)$, $\mathcal{H}=\sigma(V)$ and $X=UV$. Now, one can show that $X$ and $U$ are independent by showing that
$$
P(X=a,U=b)=P(X=a)P(U=b)
$$
for every combination of $a,b\in \{0,1\}$. But $\sigma(\sigma(X)\cup\sigma(V))$ is not independent of $\sigma(U)$ since for example
$$
P(X=1,V=1,U=1)\neq P(X=1,V=1)P(U=1),
$$
and hence we do not have the stronger independence assumption. In this case,
$$
E[X\mid \sigma(\mathcal{G}\cup\mathcal{H})]=UV\neq E[U]V=E[X\mid\mathcal{H}].
$$

A: For a general result, the equation holds under the assumption A2 below, and assumption A2 holds when A1 holds. A1 is the condition mentioned in the other answer.
(A1) $X \vee \mathcal H$ and $\mathcal G$ are independent (where we write  $X \vee \mathcal H$ to mean the smallest sub sigma algebra containing both $\sigma(X)$ and $\mathcal H$)
(A2) $X$ and $\mathcal G$ are conditionally independent given $\mathcal H$
(A3) $E(X | \mathcal H \vee \mathcal G) = E(X | \mathcal H)$
In short, A1 ==> A2 ==> A3.
On the other hand, X and $\mathcal G$ being independent does not imply A2 and A2 does not imply independence of X and $\mathcal G$.


text:
Q: PHPExcel save and retrieve MySql I am using PHPExcel to generate a spreadsheet.
If I generate and download at the same time, everything is fine.
But when I save to a MediumBlob in my MySQL and then download it, MSExcel says it is not ok.
I am using the same headers in both situations.
Gera is the function that generates the file:
$agora=date("Y-m-d H:i:s");

$relatorio_rh_xls=$dbHandle->real_escape_string(RelatorioBaseRH::Gera($ciclo,$dbHandle));

$qry="insert into tb_relatorio_rh (id_avaliacao_ciclo,relatorio_base_RH_xls,inicio_vigencia,fim_vigencia) values ( $ciclo,'".$relatorio_rh_xls."','".$agora."',null)";

$result4=$dbHandle->query($qry);

And then to retrieve it:
$query = "SELECT $nomeRelatorio, OCTET_LENGTH($nomeRelatorio) as tamanho " .
                 "FROM tb_relatorio_rh WHERE id_avaliacao_ciclo = '$id_avaliacao_ciclo' and fim_vigencia is null order by inicio_vigencia desc";
$resultadoConsulta= $dbHandle->query($query);

$qtdeLinhas=$resultadoConsulta->num_rows;
        if ($qtdeLinhas>0) {
            $fetBuscaRelatorio = $resultadoConsulta->fetch_assoc();
            $relatorio=$fetBuscaRelatorio[$nomeRelatorio];
            $size=$fetBuscaRelatorio['tamanho'];

            $type= substr($nomeRelatorio, -3, 3);

            if ($type == "xls"){ $type="xlsx";}

            $nomeAvaliado= str_replace(' ','_',$nomeAvaliado);

            $nomeDownload=substr($nomeRelatorio, 0, strlen($nomeRelatorio)-4) .'_' . $nomeAvaliado .'.'. $type;

            header("Content-Length: $size");
            header("Content-Type: $type");
            header("Content-Disposition: attachment; filename=$nomeDownload");

            print $relatorio;
}

A: The problem was with another php file I was including with include_once(anotherfile.php).
That anotherfile.php had blank lines after ?> closing tag.


text:
Q: How do I read from a chosen PHP session file Is there a solution that allows me to create a session file based on the first request(request is not coming from a browser but contains a unique ID that will be maintained for a given period/session) and then read from this session file on subsequent requests coming from this same user (identified by the unique ID in request)?
I thought that when I set a session_id($id) or session_name($name) on the first request and create a session(ie session file), I will be able to on user's subsequent request identify and read this session file and pick values from it.
Note: These requests are not coming from a browser.
In a web browser, the cookie holds the ID that identifies the session files so values can be picked from it on subsequent requests. But I don't have this available.
EDITED TO ADD CODE LOGIC
if($_GET['sequence'] == 0)  // first request
{
    $uniqueID = $_GET['uniqueID'];
    // I thought     this will create a session file with value provided
    session_id("ses$uniqueID");
    session_start();
    $_SESSION['data1'] = $_GET['data'];
}
else // subsequent request
{
    // we should have a session file, so I thought this will fetch it
    $uniqueID = $_GET['uniqueID'];
    session_id("ses$uniqueID");  //;(
    session_start();
    $data = $_SESSION['data1'];
}
// ....`


text:
Q: USB 3.0 PCIe 2.0 card in PCIe 1.0 slot, can I make it work with Ubuntu 14.04? I bought a PCIe 1x USB 3.0 card by Renesas, model µPD720201
to slide into my Dell Optiplex 990 motherboard's PCIe 1x slot.
Card: http://am.renesas.com/products/soc/usb_assp/product/upd720201/index.jsp
Board: http://clascsg.uconn.edu/download/specs/O990.pdf
Now, I know that the card I bought is of a later generation PCIe than my slot. I was not aware of the existence of multiple PCIe generations until after my purchase. Though, from what I can find on the web is that the later generations PCIe just increase the transfer rate. This leads me to believe that I might still be able to use the card I bought but not at full capacity, which is fine by me!
So the problem is that the card is being recognized by my computer, as seen in the following listings:
lspci -v

03:00.0 USB controller: Renesas Technology Corp. uPD720201 USB 3.0 Host Controller (rev 03) (prog-if 30 [XHCI])
Flags: bus master, fast devsel, latency 0, IRQ 18
Memory at e1000000 (64-bit, non-prefetchable) [size=8K]
Capabilities: [50] Power Management version 3
Capabilities: [70] MSI: Enable- Count=1/8 Maskable- 64bit+
Capabilities: [90] MSI-X: Enable+ Count=8 Masked-
Capabilities: [a0] Express Endpoint, MSI 00
Capabilities: [100] Advanced Error Reporting
Capabilities: [150] Latency Tolerance Reporting
Kernel driver in use: xhci_hcd

and
lsusb -v

Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               3.00
  bDeviceClass            9 Hub
  bDeviceSubClass         0 Unused
  bDeviceProtocol         3
  bMaxPacketSize0         9
  idVendor           0x1d6b Linux Foundation
  idProduct          0x0003 3.0 root hub
  bcdDevice            3.16
  iManufacturer           3 Linux 3.16.0-45-generic xhci_hcd
  iProduct                2 xHCI Host Controller
  iSerial                 1 0000:03:00.0
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           31
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0xe0
      Self Powered
      Remote Wakeup
    MaxPower                0mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           1
      bInterfaceClass         9 Hub
      bInterfaceSubClass      0 Unused
      bInterfaceProtocol      0 Full speed (or root) hub
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            3
          Transfer Type            Interrupt
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0004  1x 4 bytes
        bInterval              12
        bMaxBurst               0
Hub Descriptor:
  bLength              12
  bDescriptorType      42
  nNbrPorts             4
  wHubCharacteristic 0x0009
    Per-port power switching
    Per-port overcurrent protection
  bPwrOn2PwrGood       10 * 2 milli seconds
  bHubContrCurrent      0 milli Ampere
  bHubDecLat          0.0 micro seconds
  wHubDelay             0 nano seconds
  DeviceRemovable    0x00
 Hub Port Status:
   Port 1: 0000.02a0 5Gbps power Rx.Detect
   Port 2: 0000.02a0 5Gbps power Rx.Detect
   Port 3: 0000.02a0 5Gbps power Rx.Detect
   Port 4: 0000.02a0 5Gbps power Rx.Detect
Binary Object Store Descriptor:
  bLength                 5
  bDescriptorType        15
  wTotalLength           15
  bNumDeviceCaps          1
  SuperSpeed USB Device Capability:
    bLength                10
    bDescriptorType        16
    bDevCapabilityType      3
    bmAttributes         0x02
      Latency Tolerance Messages (LTM) Supported
    wSpeedsSupported   0x0008
      Device can operate at SuperSpeed (5Gbps)
    bFunctionalitySupport   3
      Lowest fully-functional device speed is SuperSpeed (5Gbps)
    bU1DevExitLat           0 micro seconds
    bU2DevExitLat           0 micro seconds
Device Status:     0x0001
  Self Powered

but when I plug something into the USB ports of the cards, no power is supplied and no connected device is recognized by the computer.
Similar questions like
Should a 2.0 card work on 1.0 PCI Express slot?,
Will a PCI Express x16 2.0 slot work with a PCI Express x16 3.0 graphic card
and
A PCI Express 3.0 Video Card into a PCI-E 1.0 x16 slot
have answers that claim that the card should be functioning, even though my slot is of the first generation.
So is there something else that might be blocking the USB ports? Or do I have an exceptional card that is not backwards compatible?


text:
Q: Requires regex to compare last digit in string Requires regex to compare last digit in string.
// For example:
const reg = RegExp("anythink...5") // expression to check that the last number is 5
reg.test("2fae71c8-a657-41b7-8d8c-3d4da10285fc") => true
reg.test("2fae71c8-fc5") => true
reg.test("2364872368745") => true
reg.test("87415B11-7143-4E5B-9B25-6117571DFEC8") => false

Please help me find a solution.

A: You can use
/5(?=\D*$)/
/5(?!\D*\d)/

See the JavaScript demo:

const reg = /5(?=\D*$)/
console.log(reg.test("2fae71c8-a657-41b7-8d8c-3d4da10285fc")) // => true
console.log(reg.test("2fae71c8-fc5")) //=> true
console.log(reg.test("2364872368745")) //=> true
console.log(reg.test("87415B11-7143-4E5B-9B25-6117571DFEC8"))// => false

The 5(?=\D*$) regex matches

*

*5 - a 5 digit char

*(?=\D*$) - a positive lookahead that requires zero or more non-digit chars till end of string

*(?!\D*\d) - a negative lookahead that fails the match if there is a digit after 5 and any zero or more non-digit chars.

A: Use regexr.com to construct and check your Regular Expressions.
You can even add multiple tests to see if it works for you in a glance.

A: You can match 5 optionally followed by any char except a digit or a newline using:
5[^\d\n]*$

You might also use \D* to match any char except a digit,  but note that it could also match a newline.
See a regex demo.

const reg = /5[^\d\n]*$/; // expression to check that the last number is 5
console.log(reg.test("2fae71c8-a657-41b7-8d8c-3d4da10285fc")); // => true
console.log(reg.test("2fae71c8-fc5")); // => true
console.log(reg.test("2364872368745")); // => true
console.log(reg.test("87415B11-7143-4E5B-9B25-6117571DFEC8")); // => false


text:
Q: Joomla module ReferenceError: jQuery is not defined I created a module for joomla 3 when I load my page JQuery not working It gives following error.
 ReferenceError: jQuery is not defined
 var $K2 = jQuery.noConflict();
 k2.js?v.../gslab/ (line 9, col 4)

Another on
 ReferenceError: jQuery is not defined
 jQuery(window).on('load',
 function() { contact...enstack (line 35)

And
TypeError: document.getElementById(...) is null
document.getElementById('fb-root').appendChild(e);
contact...enstack (line 647, col 2)

I searched a lot not able to solve this issue, as jQuery not working not able to use j Query Date-piker. JavaScript code is working.

A: It is error occur due to fact that the jQuery is not loaded before K2. You can correct this error if the switch jQuery load in K2 parameters.
Go to Component - K2 - Parameters and choose jQuery at "jQuery library handling" selector.


text:
Q: Nodeclipse set path Node and Express I installed node.js on Ubuntu 12.04 using this command
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
sudo npm install -g express

The I installed Nodeclipse to Eclipse Juno. How can I set Node path and Express path ?

A: Click Window -> Preferences -> Nodeclipse.
Node Path
/usr/bin/nodejs

Express Path
/usr/lib/node_modules/express/bin/express


text:
Q: recvfrom: Resource temporarily unavailable. Why? I'm running this piece of code several times (for a non-blocking recvfrom on a UDP socket):
struct timeval read_timeout;
read_timeout.tv_sec = 0;
read_timeout.tv_usec = 1000;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &read_timeout, sizeof read_timeout);
ssize_t n = recvfrom(sockfd, recvline, sizeof(recvline), 0, NULL, NULL);
if (n < 0) {
    perror("recvfrom");
    return -1;
} else // ... normal usage

Sometimes the program stops and I get the following error from perror

recvfrom: Resource temporarily unavailable

What could the issue be?

A: Just modify the code to do what you want. When you get an error, instead of calling perror unconditionally, check if it's a timeout. If it's not a timeout, then call perror and return. If it's a timeout, do whatever it is you want to do when you get a timeout.


text:
Q: Storing files on S3 using CollectionFS I am trying to use Meteor, CollectionFS and S3 to store files. I setup my bucket, set the key ID and secret to, and configure store.S3 as follows:
var fileStore = new FS.Store.S3('files', {
        bucket: Meteor.settings.public.storage.bucket
});

However, whenever I try to upload a file, I receive:
Error storing file to the files store: The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.

Is there any way to set the signature version/authorization mechanism using CollectionFS?

A: Ostrio:files is the best and up to date library for that. It is fully documented and very well supported and you will see that when you look at the response time on their git page. I have an implementation of camera to S3 with that so if you get stuck I can probably help you and as I said the support on the git directly is amazing.


text:
Q: How to access webcam from HTML5? I want access webcam from HTML5 for register and save a video file, for playing later. Is this possible?

A: Apparently, the <device> tag is not part of the HTML5 spec, and therefore there is no currently standard way to access webcams from a browser.  You might be able to get away with using the JavaScript API navigator.getUserMedia(...), but that isn't supported by any browsers, either
You can read up on this here: Which web browsers support the HTML5 <device> tag?

A: I was doing similar research recently and found a working demo: http://gadgets-code.com/taking-webcam-photo-with-opera-browser-new-technology
It requires install of an experimental version of Opera: http://snapshot.opera.com/labs/camera-and-pages/
Happy hacking!

UPDATE [20 May 2012]:
http://www.webrtc.org/running-the-demos - WebRTC - GoogleChromeCanary - about://flags - enableMediaStream + PeerConnection :) Me recommends - Jerome Etienne's blog - http://learningthreejs.com/
UPDATE [13 Sep 2012]:
WebRTC enabled in Chrome 21 by default (change introduced couple weeks ago)
UPDATE [2 Jul 2014]:
WebRTC is mainstream / huge: http://youtu.be/GBAEG_RuqeE?t=50m1s (Google Hangouts, Amazon Mayday, Snapchat)


text:
Q: Парсинг контента (Python, BeautifulSoup, requests) Вот код:
from bs4 import BeautifulSoup

html = requests.get('https://kaliningrad.bankiros.ru/currency/').text
soup = BeautifulSoup(html, 'lxml')

div_tags1 = soup.find_all('td', {'class': 'currency-value'})
img_tags1 = [div.find('span') for div in div_tags1]

image_src1 = [img['data-curse-val'] for img in img_tags1]

valist = list(image_src1)

print(valist)

Я ещё учусь парсить и не понимаю, почему передаётся пустой список на выходе, ведь всё вроде сделал как всегда.
Как мне можно запарсить валюту с сайта https://kaliningrad.bankiros.ru/currency/ ?

A: Добавьте HTTP заголовок User-Agent к Вашему запросу:
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',  # Example
}
html = requests.get('https://kaliningrad.bankiros.ru/currency/', headers=HEADERS).text


text:
Q: How many customers purchase life or health but not auto insurance? An insurance agent sells life, health and auto insurance. During the year she met with 85 potential clients. Of these, 42 purchased life insurance, 40 health insurance, 24 auto insurance, 14 both life and health, 9 both life and auto, 11 both health and auto, and 2 purchased all three. How many of these potential clients purchased (a). no policies; (b) only health policies; (c) exactly one type of insurance; (d) life or health but not auto insurance?
A).
N(L or H or A) = N(L) + N(H) + N(A) – N(L and H) – N(L and A) – N(H and A) + N(L and H and A)
N(L or H or A) =  42+40+24-14-9-11 +2 -> 74
1 – N(L or H or A) = Number who did not get any policies
85 – 74 -> 11 = number without policies
B). N(H) = 40, so subtract overlaps and add back overlap 40 – 14 – 11  + 2 = 17
c). [N(L) – N(L and H) – N(L and A) + N(L and H and A)] + [N(H) – N(L and H) – N(H and A) + N(L and H and A)] + [N(A) – N(H and A) – N(L and A) + N(H and A and L)]
[40-14-11+2] +[42-14-9+2] + [24-9-11+2] = 44
d). (40-14) + (42 - 14) = 54 (my answer) but the book says the answer is 50.
I've done and understand how A,b,c are done but not quite sure about the intuition regarding (d). Would appreciate if someone can point me in the right direction!

A: Venn Diagrams are your friend!

*

*Draw the Venn Diagram for the 3 sets:

*Start in the middle (2 purchase all 3 types of insurance)

*Find other intersections (9 Auto and Life; 11 Auto and Health; 14 Life and Health)

*Complete Insides (42 Life; 40 Health; 24 Auto):

*And the number on the outside (85 clients total):

With this one diagram you can now answer all questions in a flash:
a) No insurance: 11. Proof: See diagram!
b) Only Health: 17. Proof: See diagram!
c) Exactly 1 type: 6+21+17=44 Proof: See diagram!
d) Life or Health but not Auto: 21+12+17=50. Proof: See diagram!

A: Let $|L|$, $|H|$, and $|A|$ denote, respectively, the number of customers who purchased life insurance, health insurance, and auto insurance.  The number of customers who purchase health insurance or life insurance is
$$|H \cup L| = |H| + |L| - |H \cap L| = 40 + 42 - 14 = 68$$
The number of life insurance or health insurance customers who have also purchased auto insurance is
$$|A \cap H| + |A \cap L| - |A \cap H \cap L| = 9 + 11 - 2 = 18$$
Hence, the number of customers who purchase health insurance or life insurance but not auto insurance is
$$|H \cup L| - (|A \cap H| + |A \cap L| - |A \cap H \cap L|) = 68 - 18 = 50$$


text:
Q: Docker timing out in Azure App Service - using Nextjs I'm using a Linux server in azure app service. Previously, I was able to deploy my nextjs app with no problems on app service, and it ran just fine. However, after another deployment the docker image suddenly kept timing out. After hours of being unable to fix this, I deleted the app on azure, recreated it, and deployed and everything worked smoothly once again. After another deployment recently, it happened again and the docker image is timing out, and I'm unable to find what the problem is. Before anyone asks, yes, nextjs is starting on port 8080 and I have the PORT and WEBSITES_PORT app variables set to 8080 in app service, you'll also see this in the logs below. My web.config and server.js files are in the root directory. I also used this tutorial to publish the nextjs app on app service: https://parveensingh.com/next-js-deployment-on-azure-app-service/
Here are the logs:

Here's my server.js:
const next = require("next");

const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    handle(req, res);
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on <http://localhost>:${port}`);
  });
});

Here's my web.config:
<!--
     This configuration file is required if iisnode is used to run node processes behind
     IIS or IIS Express.  For more information, visit:

     <https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config>
-->

<configuration>
  <system.webServer>
    <!-- Visit <http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx> for more information on WebSocket support -->
    <webSocket enabled="false" />
    <handlers>
      <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>
        <!-- Do not interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\\/debug[\\/]?" />
        </rule>

        <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <!-- All other URLs are mapped to the node.js site entry point -->
        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <!-- Make sure error responses are left untouched -->
    <httpErrors existingResponse="PassThrough" />

    <!--
      You can control how Node is hosted within IIS using the following options:
        * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
        * node_env: will be propagated to node as NODE_ENV environment variable
        * debuggingEnabled - controls whether the built-in debugger is enabled

      See <https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config> for a full list of options
    -->
    <iisnode watchedFiles="web.config;*.js"/>
  </system.webServer>
</configuration>

Here's my package.json scripts:
"scripts": {
    "dev": "node server.js",
    "build": "next build",
    "start": "node server.js",
    "lint": "next lint",
    "test": "npx jest"
  },

A: You could try increasing the time allowed for the container to start.
Set WEBSITES_CONTAINER_START_TIME_LIMIT to 1800 (which is the max)


text:
Q: Difference between self.var and simply var What is the difference between using self.var vs. just var in an Objective-C class? Are there benefits or dangers to one or the other?

A: self.var calls the property for var. Behind the scenes, Objective-C automatically generates a getter for properties (or you can make one yourself, if so inclined), so self.var uses that getter. Plain var accesses the instance variable directly (i.e., it doesn't go through the getter to get the value).

A: foo = self.var;
self.var = foo;

is conceptually identical to
foo = [self var];
[self setVar: foo];

So using dot notation, you are really sending messages to self.
foo = var;
var = foo;

is conceptually the same as
foo = self->var;
self->var = foo;

So not using dot notation to access an instance variable is the same as treating self as a pointer to a C struct and accessing the struct fields directly.
In almost all cases, it is preferable to use the property (either dot notation or message sending notation).  This is because the property can be made to automatically do the necessary retain/copy/release to stop memory leaks.  Also, you can use key value observing with a property.  Also subclasses can override properties to provide their own implementation.
The two exceptions to using properties are when setting an ivar in init and when releasing it in dealloc.  This is because you almost certainly want to avoid accidentally using a sub class override in those methods and you don't want to trigger any KVO notifications.

A: Duplicate of

*

*How does dot syntax work without explicit @property in Objective-C?

*self.variable and variable difference

*What's the difference between using obj-c accessors and using dot syntax?

*iVars, With and Without self?

*Is "self" necessary?
and probably about a dozen others that you could've found in about 15 seconds by using the "Search" box up in the top right corner of the site.


text:
Q: How do I add a Batch Normalization layer to my model in Flux.jl I have a simple model which I defined but I want it to use batch normalization so I don't have to calculate and provide the normalizations manually. The model currently looks like:
m = Chain(
  Dense(28^2, 64),
  Dense(64, 10),
  softmax)

How can I edit this model to add a BN layer or define a new one all together?

A: Using Flux.jl's built in Batch Normalization function you can do the following:
m = Chain(
  Dense(28^2, 64),
  BatchNorm(64, relu),
  Dense(64, 10),
  BatchNorm(10),
  softmax)

where  relu is the element-wise activation that takes place after normalization. You can read why we use the relu function in an example like this: https://stats.stackexchange.com/questions/226923/why-do-we-use-relu-in-neural-networks-and-how-do-we-use-it. Find out more about the BatchNorm function in the Flux.jl docs.


text:
Q: iOS (iPhone/iPad) SDK - Tabs in Tab Bar not showing up The Tabs in my Tab Bar don't seem to be showing up. Here is my App Delegate code:
(appname)AppDelegate.h:
    #import <UIKit/UIKit.h>

    @class TwitterViewContoller;

    @interface <appname>AppDelegate : NSObject <UIApplicationDelegate> {
        UIWindow *window;
        UITabBarController *rootController;
        TwitterViewContoller *viewController;
        NSMutableData *responseData;
        NSMutableArray *tweets;
    }

    @property (nonatomic, retain) IBOutlet UIWindow *window;
    @property (nonatomic, retain) IBOutlet UITabBarController *rootController;
    @property (nonatomic, retain) IBOutlet TwitterViewContoller *viewController;
    @property (nonatomic, retain) NSMutableArray *tweets;

    @end

(appname)AppDelegate.m:
    #import "<appname>AppDelegate.h"
    #import "TwitterViewContoller.h"
    #import "SBJson.h"

    @implementation <appname>AppDelegate

    @synthesize window = _window;
    @synthesize rootController;
    @synthesize viewController;
    @synthesize tweets;

    #pragma mark -
    #pragma mark Application lifecycle

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Override point for customization after application launch.
        CGFloat width = self.rootController.view.bounds.size.width;
        CGFloat height = self.rootController.view.bounds.size.height;
        UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, width, height)];
        UIImage *imageView = [UIImage imageNamed:@"TabBarBackground.png"];
        UIColor *kMainColor = [[UIColor alloc] initWithPatternImage:imageView];

        [v setBackgroundColor:kMainColor];
        [kMainColor release];

        [self.rootController.tabBar insertSubview:v atIndex:0];
        [imageView release];
        [v release];

        responseData = [[NSMutableData data] retain];
        tweets = [NSMutableArray array];

        NSURLRequest *request = [NSURLRequest requestWithURL:
                         [NSURL URLWithString:@"http://api.twitter.com/1/statuses/user_timeline.json?screen_name=USER_NAME_ID"]];

        [[NSURLConnection alloc] initWithRequest:request delegate:self];
                NSAssert(nil != self.rootController, @"tab bar controller not hooked up!");

        self.viewController = [[[TwitterViewContoller alloc] initWithNibName:@"TwitterViewContoller_iPhone" bundle:nil] autorelease];
        self.rootController.viewControllers = [NSArray arrayWithObject:self.viewController];

        // this is now the Right Way to set the root view for your app, in iOS 4.0 and later
        self.window.rootViewController = self.rootController;

        [self.window makeKeyAndVisible];
        return YES;
    }

    #pragma mark NSURLConnection delegate methods
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        [responseData setLength:0];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [responseData appendData:data];
    }

    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        [connection release];
        NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        [responseData release];

        NSArray *allTweets = [responseString JSONValue];
        [viewController setTweets:allTweets];

    }

    - (void)dealloc {
        [_window release];
        [rootController release];
        [viewController release];
        [super dealloc];
    }

    @end

I believe the problem is in application didFinishLaunchingWithOptions: as the only recent changes I have made to App Delegate have been these lines:
    NSAssert(nil != self.rootController, @"tab bar controller not hooked up!");

    self.viewController = [[[TwitterViewContoller alloc] initWithNibName:@"TwitterViewContoller_iPhone" bundle:nil] autorelease];
    self.rootController.viewControllers = [NSArray arrayWithObject:self.viewController];

    // this is now the Right Way to set the root view for your app, in iOS 4.0 and later
    self.window.rootViewController = self.rootController;
    [self.window makeKeyAndVisible];

(EDIT: removing the 2nd and 3rd line above fixes the problem but I need to have them). Any ideas?

A: Make a Property of your other ViewControllers and synthesize them in your implementation file (.m). Also import them in your AppDelegate.m file. Here is what your header (.h) file will look like (rootController is your TabBarController):
    #import <UIKit/UIKit.h>

    @class TwitterViewContoller;
    @class OtherViewController;

    @interface <appname>AppDelegate : NSObject <UIApplicationDelegate> {
        UIWindow *window;
        UITabBarController *rootController;
        TwitterViewContoller *viewController;
        OtherViewController *viewController1;
    }

    @property (nonatomic, retain) IBOutlet UIWindow *window;
    @property (nonatomic, retain) IBOutlet UITabBarController *rootController;
    @property (nonatomic, retain) IBOutlet TwitterViewContoller *viewController;
    @property (nonatomic, retain) IBOutlet OtherViewController *viewController1;

    @end

And the first few lines of your implementation (.m) file:
#import "<appname>AppDelegate.h"
#import "TwitterViewContoller.h"
#import "OtherViewController.h"

@implementation <appname>AppDelegate

@synthesize window = _window;
@synthesize rootController;
@synthesize viewController;
@synthesize viewController1;

Add additional allocs and inits for all your ViewControllers:
self.viewController = [[[TwitterViewContoller alloc] initWithNibName:@"TwitterViewContoller_iPhone" bundle:nil] autorelease];
self.viewController1 = [[[SecondViewController alloc] initWithNibName:@"SecondViewController_iPhone" bundle:nil] autorelease];

Then replace this:
self.rootController.viewControllers = [NSArray arrayWithObject:self.viewController];

with this:
self.rootController.viewControllers = [NSArray arrayWithObjects:self.viewController, self.viewController1, nil];

This is so you can add more than one UIViewController to your TabBar Controller.
Then of course, release:
[viewController release];
[viewController1 release];

And under each class for your ViewControllers, under the -initWithNibName method add this inside the if (self) statement:
UITabBarItem *tabBarItem = [self tabBarItem];
UIImage *tabBarImage = [UIImage imageNamed:@"IMAGE NAME.png"];
[tabBarItem setImage:tabBarImage];
[tabBarItem setTitle:@"TITLE GOES HERE"];

Run your application and it should be working now!


text:
Q: Identifying unusual three terminal component I was desoldering some components from a board and found this three terminal device I have no idea what it is. The labels on the PCB were F1, F2,... which is usually reserved for fuses, but I've never seen a fuse that looked like that. My guess is that F stands for filter or something.
That 223 is literally the only label on the package, and it's a small rectangular box about 0.8 x 0.8 x 0.3cm.

A: (joke) 'tis black art stealth technology, and was top secret until spies traded all secrets during star wars era in spite of appearance.  223 is a secret code with underscore
Now commonly known as a Pi Filter or CLC filter which is bidirectional and 22nF for EMI ingress+egress reduction above 0.5 MHz.
--|÷ö|-->--=
The funny part about rusky-yank spy wars was Japanese always banned exports of new technology, as they developed these new components which were not for sale like all other new miniature Japanese technology, for at least 5 years to have an edge on product technology. This was by economic design, as it was gov't funded.
Here is an early 70's technology graph paper I used to solve for 1 unknown making assumptions for other knowns. ( We still used slide rules in EE schools in early 70's and new calculators were not allowed in exams.) I got this graph paper in my 1st job in Aerospace R&D in '75


text:
Q: Snowflake: Aggregating by a sliding window (the past 60 mins) for a dataset where the sampling frequency is non-uniform I have data with non-uniform sampling dist. I want to the aggregate data on a rolling/ sliding basis (the past 60 mins).

In order to achieve an hourly average (partitioned by city), I used to following code which worked.
SELECT *,
       AVG(VALUE) OVER (PARTITION BY CITY, DATE_AND_HOUR ORDER BY TIMESTAMP
FROM
(
SELECT *,
       date_trunc('HOUR', TIMESTAMP) as DATE_AND_Hour

FROM SAMPLE_DATA
)

However, my desired output is as follows:

I know Snowflake doesn't support RANGE and I can't use specify which rows BETWEEN in a windows function as my sampling dist is non-uniform.
I read some potential solutions on this page but they don't work in snowflake: sum last n days quantity using sql window function
Essentially, it's an analogous problem.

A: You can solve this with a self-join:
with data as (
    select *
    from temp_fh_wikipedia.public.wikipedia_2020
    where title in ('San_Francisco', 'Los_Angeles')
    and wiki='en'
    and datehour > '2020-10-13'
)

select a.title, a.datehour, a.views, avg(b.views) avg_previous_5h
from data a
join (
    select *
    from data
) b
on a.title=b.title
and b.datehour between timestampadd(hour, -5, a.datehour) and a.datehour

group by 1, 2, 3
order by 1, 2
limit 100

Just change 'hour' for 'minutes', if you want the last x minutes.

A: Firstly what you show as "average" in your example is the "sum", and you first "Shanghia" result is including a "Beijing" result.
You have two options, build a fixed sized window dataset (build partials for each minute) and then use window frame of fixed size over that, OR self-join and just aggregate those (as Felipe has shown).
If you have very dense data, you might find the former more performant, and if you have sparse data, the later approach should be faster, and is definitely faster to code.
So the simple first:
with data(city, timestamp, value) as (
    select column1, try_to_timestamp(column2, 'yyyy/mm/dd hh:mi'), column3 from values
    ('beijing', '2022/05/25 10:33', 22),
    ('beijing', '2022/05/25 10:37', 20),
    ('beijing', '2022/05/25 11:36', 29),
    ('beijing', '2022/05/26 11:36', 28),
    ('beijing', '2022/05/26 10:00', 21),
    ('shanghai', '2022/05/26 11:00', 33),
    ('shanghai', '2022/05/26 11:46', 35),
    ('shanghai', '2022/05/26 12:40', 37)
)

select a.*
    ,avg(b.value) as p60_avg
    ,count(b.value)-1 as p60_count
    ,sum(b.value) as p60_sum
from data as a
left join data as b
    on a.city = b.city and b.timestamp between dateadd(hour, -1, a.timestamp) and a.timestamp
group by 1,2,3
order by 1,2

gives:

CITY
TIMESTAMP
VALUE
P60_AVG
P60_COUNT
P60_SUM

beijing
2022-05-25 10:33:00.000
22
22
0
22

beijing
2022-05-25 10:37:00.000
20
21
1
42

beijing
2022-05-25 11:36:00.000
29
24.5
1
49

beijing
2022-05-26 10:00:00.000
21
21
0
21

beijing
2022-05-26 11:36:00.000
28
28
0
28

shanghai
2022-05-26 11:00:00.000
33
33
0
33

shanghai
2022-05-26 11:46:00.000
35
34
1
68

shanghai
2022-05-26 12:40:00.000
37
36
1
72

The dense version:
with data(city, timestamp, value) as (
    select column1, try_to_timestamp(column2, 'yyyy/mm/dd hh:mi'), column3 from values
    ('beijing', '2022/05/25 10:33', 22),
    ('beijing', '2022/05/25 10:37', 20),
    ('beijing', '2022/05/25 11:36', 29),
    ('beijing', '2022/05/26 11:36', 28),
    ('beijing', '2022/05/26 10:00', 21),
    ('shanghai', '2022/05/26 11:00', 33),
    ('shanghai', '2022/05/26 11:46', 35),
    ('shanghai', '2022/05/26 12:40', 37)
), filled_time as (
    select city,
        dateadd(minute, row_number() over(partition by city order by null)-1, min_t) as timestamp
    from (
        select
            city, min(timestamp) as min_t, max(timestamp) as max_t
        from data
        group by 1
    ), table(generator(ROWCOUNT => 10000))
    qualify timestamp <= max_t
)
select
    ft.city
    ,ft.timestamp
    ,avg(d.value) over (order by ft.timestamp ROWS BETWEEN 60 PRECEDING AND current row ) as p60_avg
from filled_time as ft
left join data as d
    on ft.city = d.city and ft.timestamp = d.timestamp
order by 1,2;

gives:

CITY
TIMESTAMP
P60_AVG

beijing
2022-05-25 10:33:00.000
22

beijing
2022-05-25 10:34:00.000
22

beijing
2022-05-25 10:35:00.000
22

beijing
2022-05-25 10:36:00.000
22

beijing
2022-05-25 10:37:00.000
21

beijing
2022-05-25 10:38:00.000
21

beijing
2022-05-25 10:39:00.000
21

beijing
2022-05-25 10:40:00.000
21

beijing
2022-05-25 10:41:00.000
21

beijing
2022-05-25 10:42:00.000
21

beijing
2022-05-25 10:43:00.000
21

beijing
2022-05-25 10:44:00.000
21

beijing
2022-05-25 10:45:00.000
21

beijing
2022-05-25 10:46:00.000
21

snip...

And those "extra" rows could be dumped with a qualify
select
    ft.city
    ,ft.timestamp
    ,avg(d.value) over (order by ft.timestamp ROWS BETWEEN 60 PRECEDING AND current row ) as p60_avg
    --,count(b.value)-1 as p60_count
    --,sum(b.value) as p60_sum
from filled_time as ft
left join data as d
    on ft.city = d.city and ft.timestamp = d.timestamp
qualify d.value is not null
order by 1,2;


text:
Q: 2 Business Rules calling at the same time when incident created I am facing an issue in servicenow Business rules. I have 2 business rules which has to trigger when

*

*When an incident created

*When specific fields of an incident updated

While creating an incident I'm setting some default values say State - closed, Urgency - Low. I am expecting that it should only trigger create incident business rule but it's triggering update incident business rule as well to set Urgency and State values.

A: Are you using current.update() in your Business Rule that runs on insert? If so, that is probably triggering the second Business Rule to run.
Also, make sure your Business Rule is set as a before Business Rule instead of an after to help the flow if at all possible.
It's generally not necessary to call current.update() for a before Business Rule since these run before the actual insert happens.
Take a look at the best practices for Business Rules when you have some time https://hi.service-now.com/kb_view.do?sysparm_article=KB0540192
In particular this one may describe the behavior your are seeing.

Best Practice #2: Avoid using current.update() in before or after
  business rules.  Avoid using current.update() to prevent recursions
  that impact system performance. The current.update() triggers business
  rules to run on the same table for insert and update operations. In a
  before or after business rule, this can lead to the rule calling
  itself over and over again.
It is unnecessary to use current.update() in a before business rule
  since these are saved automatically when the database is updated.
  After business rules are not intended to update current objects, so
  this is also not needed.
Unless there is a special case, avoid using current.update()since it
  not only stops business rules, but it also prevents the workflow
  engine from running on the record.


text:
Q: Ubuntu goes slower than windows Hello and thanks for reading, i'm new on this community and i hope you can help me
Long story short, i really like ubuntu, and installed multiple times, but always with the same problem, that in Ubuntu, when i open programs (firefox, even rithmbox) ubuntu freezes like 3 seconds or more and then starts the program, even when using the terminal. And worst, when i try to watch some youtube videos while searching another thing, sometimes ubuntu freezes completely, even if i'm only using firefox, long story short, my problem is that anything i do on ubuntu make's ubuntu freeze for a short time or completely, i really like ubuntu and want to use it, but i can't use my pc normally just to watch a video because it freezes.
My case in windows is different, i don't like windows as much as ubuntu, but on windows i can not joking install one program, while hearing a video (on youtube for example) and searching something on google, i can do everything i want to do on ubuntu (just use my pc normally) on windows and it rarely crashes (i think never happend)
So, sorry if i seem a little mad and just saying ubuntu is just problems, but is not that. I really want to use ubuntu, that's why even thought i tried everything i can't make ubuntu run swiftly, if i can do it i can finally delete windows.
My pc is:
Lenovo sl400 you can watch all if you search that model on google
Intel Core 2 Duo CPU T6570 2.10GHz x 2
1,9 gb  (2 gb)
Graphics unknown (i don't know if this is the problem, but i don't know how to search graphics drivers on ubuntu)
The lenovo sl400 graphics is : Geforce 9300M GS from NVIDIA. with 256MB GDDR3 of video memory
Gnome: 3.26.2
OS type 64 bits
Disk: 356,3 GB (I'm using more memory on ubuntu than in windows and the last goes faster)

I'm dualbooting with windows 10 (Windows 10 should be slower since it have a lot of stuff.. antivirus... etc... etc, but it doesn't).
OK, Finishing, i don't know if i have to move to another version of ubuntu, i don't know, an older version maybe? but well, i'll ask you since you know more than me about ubuntu.
Right know i have Ubuntu 17.10, the latest with has gnome.
Many thanks for reading all of my blog, and sorry if you don't understand me at some point (English is not my first language), and more thanks if you can help me in this


text:
Q: Testing PySide Application using QProcess I have a PySide application that spawns a worker application in a QProcess. The worker performs a simulation and creates result files to be read by the main application. I want to spawn the worker, give time for it to work, and then check the output. In my test function (I'm using py.test, if that helps), I cannot find a way to wait for the worker without blocking the main thread, thus not allowing the worker process to start and run.
def test_worker_thread():
    application = Application()  # Waits for and loads result files
    application.worker.start()  # Runs in a new process

    # How to wait right here without blocking thread?

    <wait_code>

    assert_correct_data(application.worker.results)

For the section called "wait_code", I have tried:

*

*Creating a local object with one attribute called done. I connect the worker.finished signal to setting done to True. I then used a time.sleep loop to block wait for the worker to be done.
class WaitObject:

    def __init__(self):
        self.condition = False

    def set_true(self):
        self.condition = True

wait = WaitObject()
application.worker.finished(wait.set_true)

while not wait.condition:
    time.sleep(1)

*I googled for methods to test asynchronous Qt code, and I came across QTest.qWait, which I could use in place of time.sleep() without blocking the event loop. However, qWait is not included in PySide.

*I have also tried creating a new event loop, like in this thread. However, this seems to block the event loop for application, so we cannot finish the worker.start function and load data while the worker is running.
loop = QtCore.QEventLoop()
application.worker.finished(loop.quit)
loop.exec_()

Any tips?

A: It turns out option 3 actually works. My worker wasn't starting because of an unrelated error. Here is some skeleton code in its entirety:
def test_worker_thread():
    application = Application()  # Waits for and loads result files
    application.worker.start()  # Runs in a new process

    loop = QtGui.QEventLoop()
    application.worker.finished(loop.quit)  # Resume when worker done
    loop.exec_()  # Blocks at this line until loop quits

    assert_correct_data(application.worker.results)

I am going to work on an abstraction of this pattern. I am going to add a timeout using a singleshot QTimer that is connected to loop.quit, in case worker.finished is never called.
EDIT: Here is a blog post explaining in more detail.


text:
Q: Can the default lifestyle of Castle Windsor registered components be changed? The Castle Windsor documentation shows that Singleton is the default lifestyle for registered components.
Is it possible to change the default lifestyle such that by default, a registered component will have a transient lifestyle?

A: Not sure if possible or not but what you can do is add an "IContributeComponentModelConstruction" to set all components to a specific lifestyle.
Check this: http://blog.ploeh.dk/2010/04/26/ChangingWindsorlifestylesafterthefact/


text:
Q: Has Safari stopped forwarding link URLs to system services when using the link's context menu? I seem to recall being able to right-click a link in Safari and use a system service from the context menu in order to send the actual link target URL to the service in question.
Nowadays when right-clicking a link i Safari (13.1) the link's title/text is selected automatically, and when I try to use a service that way it always receives the selected text instead and fails to locate the resource. The services are definitely not receiving the URL since if I use a service with a strict constraint of only accepting URL formatted text, then they don't show up at all in the menu; I have to follow the link and right-click the URL in the address bar before they appear.
I'm wondering if this ever worked like in my first description? If so, what has changed, if anything? Did I change something? Can I get it back?
MacOS Mojave 10.14.6


text:
Q: Infected People finding Algorithm I have a algorithm that solves for 'affected people' in given input.
I have to solve the list of people who are affected. People are denoted by numbers, and two people interact with each other at given time N. If either of the person is affected, the other becomes affected too.
First, N(number of people) and M(total interactions) are given.
and then (P1 P2 time) are given across M lines.
For example,
5 5
2 3 1
1 2 2
3 4 2
1 3 3
2 5 4
is given.
This means that there are 5 people, who have 5 interactions, which followed by 5 lines denoting person 2 and 3 meeting at time 1, 1 and 2 meeting at time 2, 3 and 4 meeting at time 2, and so on.(times may not be ordered).
At the start, person 1 is always infected.
So at time 2, person 1 and 2 meets, making person 2 infected,
person 1 and 3 meets at time 3, making person 3 infected,
and finally, person 2 and 5 meets at time 4, making person 5 infected.
This makes person 1, 2, 3, 5 infected at the end.
Interactions happen by time, and multiple interactions can happen simultaneously, and if that is the case, most people have to be considered
to be affected.
For Example, if person 1 and 3 is infected, and (4 6 3) (3 6 3) is given as inputs, (3 6 3) has to be calculated first to get person 6 infected and person 4 infected as well.
To solve this question, I created this algorithm, and it has terrible running time, and I need help optimizing this algorithm.
inputs = input()
peopleNum = int(inputs.split()[0])
times = int(inputs.split()[1])
peopleMeet = {}
affectedPeople = [1]
for i in range(times):
    occur = input()
    person1 = int(occur.split()[0])
    person2 = int(occur.split()[1])
    time = int(occur.split()[2])
    if not time in peopleMeet:
        peopleMeet[time] = [(person1, person2)]
    else:
        for occur in range(len(peopleMeet[time])):
            if set(peopleMeet[time][occur]) & set((person1,person2)):
                peopleMeet[time][occur] = peopleMeet[time][occur] + ((person1,person2,))
                break
            if occur == (len(peopleMeet[time]) - 1):
                peopleMeet[time].append((person1,person2))
for time in sorted(peopleMeet):
    for occur in peopleMeet[time]:
        if set(affectedPeople) & set(occur):
            affectedPeople.extend(list(occur))
print(' '.join([str(x) for x in set(affectedPeople)]))

I'm very new at stack overflow, and I'm not used to the formatting and the posting guidelines, so I'm sorry if I'm wrong. And thank you in advance.

A: Pseudocode:
affectedPeople = bool array of size N + 1, initialized at false
affectedPeople[1] = True
sort the interactions based on time
iterate interactions and group them by time
for each group x:
    create a graph with interactions from that group as edges
    do a dfs on each affectedPeople present on these interactions. All the reached nodes will be affected
    add these nodes to affectedPeople (set them to True)
count amount of i with affectedPeople[i] = True

A: Yet another way of how one can approach this problem would be by using the union-find algorithm which will have a runtime complexity of O(n*log(n)). The idea is pretty straight forward:

*

*Sort the give input based on the time parameter in the ascending order.

*Group the interactions by time and for every group, iterate over the interactions and union the people involved in the same.

*In the union operation persist the information if the formulated group is infected (see code for better understanding).

*For every person involved in the interaction in this group, check if he belongs to an infected group and mark him as infected as well.

*Reset the union-find state for the persons involved in this group back to original so that we can proceed to process the other group afresh while maintaining information about the currently infected people.
Here's the code for the same:
MAX_N = 1000

parent = list(range(MAX_N))
infected = [False] * MAX_N

def find(x):
    if x == parent[x]: return x
    parent[x] = find(parent[x])
    return parent[x]

def union(x, y):
    parent_x = find(x)
    parent_y = find(y)

    # If either of the two clusters we're joining is infected
    # Infect the combined cluster as well
    infected[parent_y] = infected[parent_x] or infected[parent_y]
    parent[parent_x] = parent_y

def solve(inputs):
    infected[1] = True
    # Sort the input by the time parameter
    inputs.sort(key=lambda x: x[2])
    answer_set = set()

    i = 0
    while i < len(inputs):
        persons = set()
        cur_time =  inputs[i][2]

        # Iterate over interactions belonging to the same group i.e. same time
        while i < len(inputs) and inputs[i][2] == cur_time:
            person_x = inputs[i][0]
            person_y = inputs[i][1]

            persons.add(person_x)
            persons.add(person_y)

            # Union the people involed in the interaction
            union(person_x, person_y)
            i += 1

        for person in persons:
            group = find(person)
            # If the person belongs to an infected group, he's infected as well
            if infected[group]:
                infected[person] = True
                answer_set.add(person)

        # Reset the union-find state as we move to the next time step
        for person in persons:
            parent[person] = person

    return answer_set

print (solve([[2, 3, 1], [1, 2, 2], [1, 3, 3], [2, 5, 4], [3, 4, 2]]))

A: See comment in code:
DATA = [[2, 3, 1], [1, 2, 2], [3, 4, 2], [1, 3, 3], [2, 5, 4]]

# status contains the contamination status for each people in the dataset
# At the begining we will have only [1] contaminated so:
# {1: True, 2: False, 3: False, 4: False, 5: False}
people_status = {}
for people_id in set(x[0] for x in DATA).union(x[1] for x in DATA):
    people_status[people_id] = people_id == 1

# meeting contains DATA grouped by time so with this dataset we will have:
# {1: [[2, 3]], 2: [[1, 2], [3, 4]], 3: [[1, 3]], 4: [[2, 5]]}
meeting = {}
for x in DATA:
    if x[2] in meeting:
        meeting[x[2]].append(x[:2])
    else:
        meeting[x[2]] = [x[:2]]

# now we just have to update people_status while time evolve
for time in sorted(meeting.keys()):
    while True:
        status_changed = False
        for couple in meeting[time]:
            if people_status[couple[0]] != people_status[couple[1]]:
                status_changed = True
                people_status[couple[0]] = people_status[couple[1]] = True
        if not status_changed:
            break

# create the list of infected people
infected_people = []
for people_id, status in people_status.items():
    if status:
        infected_people.append(people_id)

print(infected_people)

will print the result:
[1, 2, 3, 5]


text:
Q: combine and save images in c++ I have some bitmaps and I would like to save them to a single image with a given number of images in a column and row. How do I do that?

A: Create a bitmap the size of the overall total. Load each source bitmap in turn, blit it to the appropriate location in the combined bitmap. Save the combined bitmap.
Saving the composite is probably the most tedious of these steps, (you need to create and fill in a BITMAPFILEHEADER followed by a BITMAPINFOHEADER, BITMAPV4HEADER or BITMAPV5HEADER), but none of it is particularly difficult and Google should turn up lots of examples.


text:
Q: Calculating sum of a column from web service Let me start out by saying I know nothing of C#. I do web design, and am pretty much limited to that with a limited amount of javascript.
I was given a web service, and the goal is to pull the data with that, which I was able to do. Now I'm trying to figure out a way to calculate the total of one of the columns. Everything I've seen has talked about DataTables, which I know nothing of. I'm not sure if DataTables are a required thing, or anything really.
The question is - is there a way to calculate the total of one of the columns? The column is called "total" and I'd like to get the total into a string called "points".
edit -
I'm not the one who made the web service, nor do I have access to editing it. I emailed the guy who made it a few hours ago telling him exactly what was going on, no response. Unfortunately, there's not a whole lot more information I can add.
decimal total = Convert.ToDecimal(t11) + Convert.ToDecimal(t12);

That's the code to add t11 and t12 together, which gets the total, but I need to figure out a way to add up the total for each row.
edit2 -
 decimal GetTotal()
{
    decimal total = 0;
    foreach (XmlNode rec in records)
    {
        total += Convert.ToDecimal(rec.SelectSingleNode("sub_total").innerText);
    }
    return total;
}

A: Without any more information, this is the best I can do to get you started.
Using a WebMethod on a page or web service:
using System.Linq;

[WebMethod]
public static int GetSum()
{
    int nSum = 0;

    // get a reference to the column...
    nSum = columnRef.Sum();

    // or get a reference to the table
    nSum = tableRef.Sum(o => o.oneOfTheColumns);

    // if the values in the column are strings representing numbers.
    nSum = tableRef.Sum(o => int.Parse(o.oneOfTheCollumns));

    // follow the same pattern for other number types

    return nSum;
}