text:
Q: Generic Attribute Table Between Entities The following is using EF 5.0.0-rc and Code First. In my design, I have an attribute entity:
public class Attribute
{
    public int AttributeId { get; set; }
    public Guid Guid { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }

    /* Used for testing the first fluent statement */
    public virtual ICollection<Customer> Customers { get; set; }
}

I also have multiple entities containing a GUID:
public class Customer
{
    public int CustomerId { get; set; }
    public Guid Guid { get; set; }
}

public class Location
{
    public int LocationId { get; set; }
    public Guid Guid { get; set; }
}

I would like the attribute table to be common to both the customer and location table, with no columns or tables in between. I just can't seem to get the correct mapping in the fluent API to create a FK without a helper table:
        modelBuilder.Entity<Customer>()
            .HasMany(o => o.Attributes)
            .WithMany(o => o.Customers)
            .Map(m => m.MapLeftKey("Guid"));

... will generate a CustomerAttributes table, which it shouldn't need.
        modelBuilder.Entity<Organization>()
            .HasMany(o => o.Attributes)
            .WithOptional()
            .HasForeignKey(o => o.Guid);

... won't compile because

The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role.

How should the relationship be setup? Or is the design not appropriate?
Edit: Success!
On Raphaël Althaus direction, I was ready to give into EF's ways and live with separate tracking tables for each entity, but his suggestion to create a new class that the Cust and Loca entities will inherit set me off on the right direction.
First I created a "parent" class, which also gave me a place to refactor some of the audit data that is stored on most entities:
public class ParentEntity
{
    [Key]
    public Guid Guid { get; set; }

    public DateTime? CreatedOn { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? ModifiedOn { get; set; }
    public string ModifiedBy { get; set; }

    [Timestamp]
    public byte[] Version { get; set; }

    public virtual ICollection<Attribute> Attributes { get; set; }
}

Then I inherited the parent class on the Cust and Loca entities:
public class Customer : ParentEntity
{
    public int CustomerId { get; set; }
    public Guid Guid { get; set; }
}

public class Location : ParentEntity
{
    public int LocationId { get; set; }
    public Guid Guid { get; set; }
}

I also modified the Attribute class to support a new FK field, EntityGuid:
public class Attribute
{
    public int AttributeId { get; set; }
    public Guid EntityGuid { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

Which gave me almost everything I needed, except ... it was trying to store every entity in the new ParentEntity table. To fix that I used:
        modelBuilder.Entity<Customer>().ToTable("Customers");
        modelBuilder.Entity<Location>().ToTable("Locations");

And finally the piece that brings it all together:
        modelBuilder.Entity<ParentEntity>()
            .HasMany(e => e.Attributes)
            .WithRequired()
            .HasForeignKey(e => e.EntityGuid);

The only drawback I can tell is the ParentEntity takes over as the primary key, which is a Guid. But I kept my other keys in place though and plan to use those as clustering index.

A: Your mixing object world and rDBMS world.
You're in an ORM, so you shouldn't mind (well, not completeley, but in this case, yes) what's really in your Database.
A rDBMS can't manage a many to many relationship without a "link" (relation) table (how to represent a foreign key which is a list ? Impossible without a relation table).
In the object world, a List<x> in y and a List<y> in x can do that, without any "relational" entity.
EDIT
If you want a common "Relation" table, you could maybe create a new entity (with a Guid) : Customer and Location would inherit from that new entity, and attribute entity would be linked with that new entity.


text:
Q: Formatting objects into strings I'm coming back to c++ after using Java for a long time.  In Java overriding the toString method on an object allows the object to be automatically translated into a string and concatenated to other strings.
class Test {
    public static void main(String[] args) {
        System.out.println(new Test() + " There"); // prints hello there
    }

    public String toString() {
        return "Hello";
    }
}

Is there anything similar that would allow me to stream an object into cout?
cout << Test() << endl;

A: The equivalent is to overload operator<<:
#include <ostream>

class Test
{
  int t;
};

std::ostream& operator<<(std::ostream& os, const Test& t)
{
   os << "Hello";
   return os;
}

You would then use it like this:
#include <iostream>

int main()
{
  std::cout << Test() << " There" << std::endl;
}

See the code in action: http://codepad.org/pH1CVYPR

A: The common idiom is to create an overload of operator<< that takes an output stream as the left-hand operand.
#include <iostream>

struct Point
{
    double x;
    double y;
    Point(double X, double Y)
      : x(X), y(Y)
    {}
};

std::ostream & operator<<(std::ostream & Stream, const Point & Obj)
{
    // Here you can do whatever you want with your stream (Stream)
    // and the object being written into it (Obj)
    // For our point we can just print its coordinates
    Stream<<"{"<<Obj.x<<", "<<Obj.y<<"}";
    return Stream; // return the stream to allow chained writes
}

int main()
{
    Point APoint(10.4, 5.6);
    std::cout<<APoint<<std::endl; // this will print {10.4, 5.6}
    return 0;
}

If you want to support streams with other character types (e.g. wchar_t)/template parameters of the streams you have to write different overloads for the various types of streams you want to support, or, if your code is (more or less) independent from such types, you can simply write a template operator<<.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Foundation Magellan re-init How do I re-init the Foundation Magellan plugin? I need to do that, because the magellan is located inside a tab, and I need to re-init 'magellan-top-offset' once the tab has been opened.
$(document).foundation('magellan', 'init'); doesn't do the trick...

A: OK, so the problem was stupid as ever, actually the full module's name is magellan-expedition, not magellan.
So the correct code that does the trick is this:
$(document).foundation('magellan-expedition','set_expedition_position');


text:
Q: Backup List in Sharepoint 2010 in Shell I want to backup a List of Sharepoint 2010 using the powershell.
I can backup the list using the central Administration and can also backup the whole Site using
Export-SPWeb -Identity http://siteurl:22222/en-us -Path \\public\backup.cmp

But when I try to export a specific List (with the path that is also shown using the Central Administration):
Export-SPWeb -Identity http://siteurl:22222/en-us/Lists/MyList -Path \\public\backup.cmp

I receive the error:

"The URL provided is invalid. Only valid URLs
  that are site collections or sites are allowed to be exported using
  stsadm.exe"

I also tried
Export-SPWeb -Identity http://siteurl:22222/en-us -Path \\public\backup.cmp -ItemURL http://siteurl:22222/en-us/Lists/MyList
getting the same error
Thanks in advance

A: Try to fiddle with the ItemUrl parameter value:
Export-SPWeb -Identity http://siteurl:22222/en-us -Path \\public\backup.cmp
  -ItemUrl /Lists/MyList

or
Export-SPWeb -Identity http://siteurl:22222/en-us -Path \\public\backup.cmp
  -ItemUrl /en-us/Lists/MyList

or
Export-SPWeb -Identity http://siteurl:22222/en-us -Path \\public\backup.cmp
  -ItemUrl "/Lists/MyList"

Different sources show different syntax:

*

*SharePoint 2010 Granular Backup-Restore Part 1

*Failing to export with Export-SPWeb

A: If you have the following kind of setup:
Site Collection e.g.  http://localhost:81
|
|-> Subsite 1 e.g. tools (http://localhost:81/tools)
    |
    |-> Subsite 2 e.g. admin (http://localhost:81/tools/admin)

I found the following worked for lists on the subsite:
Export-SPWeb -Identity http://<site>:<port>/<subsite1>/<subsite2> -ItemUrl /<subsite1>/<subsite2>/<listName> -Path <localpath>/<filename>.cmp -IncludeVersions All

e.g.
Export-SPWeb -Identity http://localhost:81/tools/admin/ -ItemUrl /tools/admin/RequestList -Path C:/Temp/Backup.cmp -IncludeVersions All

To ensure you've got the right url for your list, use the following command (thanks to HAZET here: http://social.technet.microsoft.com/Forums/en-US/sharepoint2010setup/thread/a1f48e70-9360-440f-b160-525fbf2b8412/):
$(Get-SPWeb -identity  http://<site>:<port>/<subsite1>/<subsite2>).lists | ft title,  @{Name="itemURL"; Expression = { $_.parentWebURL + "/" + $_.RootFolder}}

e.g.
$(Get-SPWeb -identity http://localhost:81/tools/admin/).lists | ft title, @{Name="itemURL"; Expression = { $_.parentWebURL + "/" + $_.RootFolder}}

Some examples of various errors I encountered whilst trying to get this to work:

*

*The URL provided is invalid

*Export-SPWeb : <nativehr>0x80070057</nativehr><nativestack></nativestack> At line:1 char:13

*CategoryInfo          : InvalidData: (Microsoft.Share...CmdletExportWeb: SPCmdletExportWeb) [Export-SPWeb], SPException FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletExportWeb
Some things to check:

*

*Check that -Identity has the trailing slash i.e. http://localhost:81/

*Check that you have the complete URL in Identity (if using subsites, include subsites)

*Check that the path where you're trying to store your export file exists

*Check that your ItemUrl is correct (i.e. starts with / and is a directory, not a specific file e.g. is /tools/admin/RequestsList, not /tools/admin/RequestsList/AllItems.aspx

*Check that you have permissions to perform the export

Further info that might be helpful:

*

*Identity: The URL of your SharePoint site

*ItemUrl: The relative URL of your list/document library

*Path:     The target filename and location for the exported list e.g. C:/Temp/backup.cmp

*IncludeVersion: What versions of the document you wish to export.

Export-SPWeb
http://technet.microsoft.com/en-us/library/ff607895.aspx
Export a site, list or document library in SharePoint 2010
http://technet.microsoft.com/en-us/library/ee428301.aspx
Import a list or document library in SharePoint 2010
http://technet.microsoft.com/en-us/library/ee428322.aspx


text:
Q: Embedded linux RSA private key strategy We have an embedded linux board running from an sdcard. The linux board creates some data files which have to be signed using a private key, so it later can be verified using a public key. This ensures that the data was infact created on that specific board and that is has not been tampered with.
Since the sdcard can be removed, it can easily be read and therefore it seems like a bad strategy to store the private key file on the sdcard (rootfs).
Our idea was to generate the private key on boot and store it in ram. The seed for generating the private key could be read from some board chip IDs. Which would ensure that the key could not be read if the sdcard was removed.
But is this a good strategy?

A: Unattended Key Storage is a problem without a solution. It does not matter if your store it on the sdcard, burn it into ROM and blow the fuses, guard it with a smart card, guard it with a SIM, or guard it with a TPM. See Peter Gutmann's Engineering Security.
Seeding a PRNG with a known value and then performing deterministic key generation is just a symptom of the underlying problem.
You have to determine your threats, determine how much risk you are willing to accept and then use a design the agrees with your security posture.


text:
Q: How to assume AWS role in docker container run on Elasticbeanstalk environment? I use elasticbeanstalk with multicontainer version and I have docker container with boto3 inside. I would like to assume role to save files on S3 using python.
Based on this question: Fetching AWS instance metadata from within Docker container?
urlopen('http://169.254.169.254/latest/meta-data/iam/instance-id-credentials/s3access').read().decode('utf-8')
returns 404.
I don't want use hardcoded credentials in my docker image.
Is there a way to somehow assume role?

A: I made this work by starting the container in --net host mode. I.e. use the host's networking stack to make AWS think that you are requesting from the EC2 host.
This was the comment that provided this solution: Fetching AWS instance metadata from within Docker container?


text:
Q: Get value from UIDatePicker before animations stops Does someone know if it is possible to get value from UIDatePicker before its animation stops?
I tried using UIControlValueChanged event but it is fired after the animation, when picker is "settled" on final position.
The result I want to achieve is that when user spins pickers wheel and presses "ok" button while it is spinning, the value that is in the middle of the picker should be selected.
Or if that is impossible maybe there is a way to select when animation started so I can disable "ok" button and force user to pick something before he can accept?


text:
Q: What are the conditions for puncturing? A sharper knife can puncture a surface with less force than a dull knife, presumably because a sharp knife has greater pressure than a dull knife for the same force.
I suspect that pressure alone isn't what we need for puncturing; e.g. if I apply the same pressure as the knife uniformly over a large area, I might not puncture the surface. Presumably I need some sort of minimum tension in the surface for it to tear after deforming under the pressure, or something like that, but I'm not sure what. How would you build a simple model for puncturing?
For a specific example, just imagine puncturing the leather on a couch, I guess.

A: Essentially, with sharper edges, you have to "perturb" less of the material.
A sharper edge can pierce better not only because of the increased pressure, but also because it can penetrate between mesoscopic features of the surface (fibers, layers, etc.).
Also, a sharper edge has to "push aside" less material and dislocate fewer crystal layers in order to penetrate the surface.
You should definitely check the answers to How does a knife cut things at the atomic level? for much more information.
I also wonder if it's perhaps also possible that a sharper edge leads in some cases to a smaller radius of the dent produced on the surface, which would imply higher local stress.


text:
Q: Making UI elements dynamically in android apps in android studio using java I am wondering if it is possible to create UI elements dynamically in android apps without using xml or design? The number of elements and type of elements will be different based on the requirements I get from a json array. So, can I create buttons, textviews, etc in my activityClass file, without actually having them in my xml file??
if yes, then how complicated would it be? can you provide an example please?
Also, are there any libraries for android that I can use that would just dynamically create the fields for me based on types and number of fields as an input?

A: Yes.  You just create the View objects using new, then add them to their parent layouts using .addView(newView).  If necessary, add them with the correct LayoutParams object.
I will say that this is MUCH harder to write and debug than xml, so it should be done only if something absolutely has to be manual.  Even if you are getting things from a JSON blob, its best to make as much of that just deciding what xml to inflate as possible.


text:
Q: HTML Parse and set default drop down list item My code is like this:
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "userfile");       // <- select the file
nvc.Add("preview", "Upload");    // <- push the upload button on website
ImportUtilities.HttpUploadFile("http://www.site.com/", "image.png", "userfile", "image/png", nvc);

But there is also a drop down box with a lot of items and the item always selected is 'English' so as i wrote before nvc.Add("preview", "Upload") pushes the button 'Upload', i want to select this way 'Vietnamese' from the list as default too.
Here is the drop down box html code: http://s17.postimg.org/gzwoamwdb/ccc.png


text:
Q: Erlang: how to profile whether qlc:q does full table scan, key prefix scan or key lookup? How to profile whether qlc:q does full table scan, key prefix scan or key lookup?
For instance, ets of type set with entries like {{KeyPrefix, KeySuffix}, Value} - will
qlc:q([
    {{KeyPrefix, KeySuffix}, Value} ||
    {{KeyPrefix, KeySuffix}, Value} <- ets:table(Table),
    KeyPrefix =:= Something
])

do full table scan or key prefix scan?

A: You can obtain a lot of informations about your QLC expression using qlc:info/1. That may not help you determine whether a given subquery uses a full table scan or whatnot but that does give you back the query plan and the tables related to your query, which you can then pass to ets:info/1 to retrieve their type and keypos.

A: ETS is not implemented in Erlang, it is implemented in the runtime system (presumably in C ?).  As such I don't believe it is possible to do that today.  Even if you figured out a way to do it, your method could break when you upgraded to a new release of Erlang.  A reliable method would require the runtime system to expose some kind of introspection API to the guts of ETS, and I think that's unlikely to happen so long as it is not implemented in Erlang.  Of course you could dig around in the code to get a better idea of what might happen in a given scenario, but I suspect your time would be better spent focusing on your application code.

A: In our experience, sometimes a qlc eval (via list comprehension) is very smart, and sometimes it is very dumb. That is to say, I think your question is valid.
I know of no way to do precisely what you want, but you may be able to get this info via other means. You can certainly look at the source code of the qlc module to see if you can glean any insight from that. Further, you could insert some debug statements inside the qlc functions and recompile your Erlang runtime to get some more feedback.
Good luck

-tjw


text:
Q: Fitting the Size of a WPF unto a Windows Forms User Control Using the elementHost method, I've docked a WPF on a Windows Forms User Control. Both have the same size, yet the WPF is not displayed correctly on the User Control (see picture). What am I doing wrong?
WPF Code Snippet:
<UserControl x:Class="SlideAnalysis.Views.DesignView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:SlideAnalysis.Views"
         mc:Ignorable="d"
         Height="586"
         Width="431">


text:
Q: Use a t function inside of a I18nextProvider? Is it possible? Is there a way to use a t function inside of a I18nextProvider?
The translation works in a children components. I want to pass a translatable elements to a SEO component.
Now i get Uncaught ReferenceError: t is not defined error.
The example makes more clear what I want to achieve:
**index.js**

import SEO from './components/villages/neighborhoods/SEO';
import { I18nextProvider, withTranslation } from 'react-i18next';
import i18n from './i18n';
import {createBrowserHistory} from 'history';
const customHistory = createBrowserHistory();

class App extends React.Component {

  render() {

    var lang = i18n.language;

    return (
      <I18nextProvider i18n={i18n}>

          <SEO
            schema={t("Product")}
            title={t("metatile")}
            lang={i18n.language}
            path={`/${lang}`}
          />
          <Router history={customHistory}>
            <Switch>
              <Route exact path={`/:lng(en|lt)?`} component={LandingPage} />
              <Route path={`/:lng(en|lt)?/test`} component={LandingPage}/>
              <Route component={NoMatch} />
            </Switch>
          </Router>
          <ModalContainer />

      </I18nextProvider>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

Is there a simple way to pass translatable title and schema variables without overwriting whole index.js code?
updated SEO.js
import React from 'react';
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';

import { useTranslation } from 'react-i18next';
const { t } = useTranslation();

const SEO = ({
  schema, lang, title, description, keywords, base, path, contentType
}) => (
    <Helmet
      htmlAttributes={{
        lang: lang,
        itemscope: undefined,
        itemtype: `http://schema.org/${schema}`,
      }}
      title={t("title")}
      link={[
        { rel: 'canonical', href: base + path },
      ]}
      meta={[
        { name: 'description', content: description },
        { name: 'og:title', content: `${title}` },
        { name: 'og:type', content: contentType },
        { name: 'og:description', content: description },
      ]}
    />

  );

SEO.propTypes = {
  schema: PropTypes.string,
  lang: PropTypes.string,
  title: PropTypes.string,
  description: PropTypes.string,
  keywords: PropTypes.string,
  path: PropTypes.string,
  contentType: PropTypes.string,
};

export default SEO;

A: In the App component you can change the schema and title props for SEO as:
<SEO
  schema="Product"
  title="metatile"
  lang={lang}
  path={`/${lang}`}
/>

And then inside your SEO component you can use t either by using the useTranslation hook or by using the withTranslation HOC (both are provided by react-i18next):
By using useTranslation Hook:
import React from 'react';
import { useTranslation } from 'react-i18next';

function SEO(props) {
  const { t } = useTranslation();

  return (

{t(props.title)}

{t(props.schema)}

  );
}

export default SEO;

By using withTranslation HOC:
import React from 'react';
import { withTranslation } from 'react-i18next';

function SEO(props) {
  return (

{props.t(props.title)}

{props.t(props.schema)}

  );
}

export default withTranslation()(SEO);


text:
Q: PHP doesn't display the right result My problem is that how my query result unreadable for humans.
I get this result in browser:
ID: 5 Reg.date: 2016-02-29 18:57:52 C�si

And the name should be 'Cósi'.
The php is in UTF-8, the database is in utf8-hungarian-ci.
So I do the query and after it I put the results into a $user array, and I echo the first 3 item like: echo "ID: " . $user["userID"] . "Reg.date: " . $user["regdate"] . $user["name"];
I tried header('Content-type: text/html; charset=UTF-8'); but it neither works.
I have a innoDB phpmyadmin database, but the server is my father's computer. A xampp, should I search the problem there?
Here is the all php:
$con = mysqli_connect("127.0.0.1", "kxxx", "csxxx", "bxxx");
$password = "asd";
$username = "carrie@gmail.com";
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE email = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);

mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $reg_date, $name, $email, $password, $phonenumber);
$user = array();

while(mysqli_stmt_fetch($statement)){
    $user["userID"] = $userID;
    $user["regdate"] = $reg_date;
    $user["name"] = $name; / which should be "Cósi"
    $user["email"] = $email;
    $user["password"] = $password;
    $user["phonenumber"] = $phonenumber;
}
echo "ID: " . $user["userID"] . "Reg. dátum: " . $user["regdate"] . $user["name"];

echo json_encode($user, JSON_UNESCAPED_UNICODE);

The json_encode is disappears, if empty [] should displayed, but that's not, only the first 3 item of the array.
So I want the C�si to be Cósi. What should I do? I tried to changed meta tag to charset='utf-8', mysql_query("SET NAMES 'utf8'") and the header thing what I mentioned above, all the columns are utf8-hungarian-ci, all the tables and the database is too.... So maybe the server configurations are bed?
When I insert into the database over a php, in the database the 'Cósi' is displays well, everything saved in the database right.
Thank you guys, I resolved it wtih:
mysqli_set_charset($con, 'utf8mb4');

A: You need the proper html tags:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Your Page Title</title>
</head>

<body>

YOUR CONTENT HERE

</body>
</html>

A: Check mb_convert_encoding in php.
$str = mb_convert_encoding($str, "UTF-8", "utf8-hungarian-ci");


text:
Q: For a continuous function $f:\mathbb{R}^{+}\to\mathbb{R}^{+}$ does $(f(x)-f(y)) (f(\frac{x+y}{2}) - f(\sqrt{xy}))=0$ imply that $f$ is constant? Suppose that $f: \mathbb{R}^+ \to \mathbb{R}^+$ is a continuous function such that for all positive real numbers $x,y$ the following is true :
$$(f(x)-f(y)) \left ( f \left ( \frac{x+y}{2} \right ) - f ( \sqrt{xy} ) \right )=0.$$
Is it true that the only solution to this is the constant function ?

A: Yes.  If $f$ were not constant, then (since ${\bf R}^+$ is connected) it could not be locally constant, thus there exists $x_0 \in {\bf R}^+$ such that $f$ is not constant in any neighbourhood of $x_0$.  By rescaling (replacing $f(x)$ with $f(x_0 x)$) we may assume without loss of generality that $x_0=1$.
For any $y \in {\bf R}^+$, there thus exists $x$ arbitrarily close to $1$ for which $f(x) \neq f(y)$, hence $f((x+y)/2) = f(\sqrt{xy})$.  By continuity, this implies that $f((1+y)/2) = f(\sqrt{y})$ for all $y \in {\bf R}^+$.  Making the substitution $z := (1+y)/2$, we conclude that $f(z) = f(g(z))$ for all $z > 1/2$, where $g(z) := \sqrt{2z-1}$. The function $g$ attracts $[1, \infty)$ to the fixed point $z=1$, so on iteration and by using the continuity of $f$ we conclude that $f(z)=f(1)$ for all $z >1$. Similarly, $h = g^{-1}$ defined by $h(z) = (z^2 + 1)/2$ attracts $(0, 1]$ to the fixed point $z = 1$, so by the same argument $f(z) = f(1)$ for $z < 1$, making $f$ constant on all of $\bf R^+$.

A: Trying to make sense of Igor's argument. Assume further that $f$ is defined on 0 and relaxt the continuity assumption by only assuming that the set $A=\{x>0:f (x)\neq f (0)\}$ is open.
It is shown that $A=\emptyset  $ by showing that

*

*$A $ is dense in $A+\mathbb R^+$, and

*$A\cap 2A=\emptyset $.

Proof. (1) Let $(a,b) $ be a connected component of  $A $. For every $0 <r <b-a  $, $b+r\in A $ since the arithmetic average of $b\pm r $ is not in $A $ whereas the geometric is. It follows that the next connected component contains $(b,2b-a) $ and, by applying the same argument on the next component, the elements of $[a,\infty )\setminus A $ are at least $b-a $ apart from one another.
(2) Let $a\in A $. $a $ is the arithmetic average of 0 and $2a $ and 0 is their geometric.

A: if $\mathbb{R}^+$ is the set of non-negative real numbers, your condition implies that
$$(f(x)-f(0)) (f(\frac{x}2)-f(0)) = 0$$ for all positive $x,$ which is pretty convincing (setting $g(x) = f(x) - f(0),$ the function $g$ will be identically $0.$).
Addendum Since the map $(x, y) -> (x+y)/2, \sqrt{x y})$ is surjective onto the set $x>y,$ if your function were real analytic and nonconstant, then the set where your condition held would be a subvariety of $R^+ \times R^+,$ so assuming more regularity makes the problem easy, as pointed out in comments.

A: Yet another solution (to the original question).
Define an equivalence relation on $\mathbb R^+$ by $x\sim y$ iff $f(x)=f(y)$.
Since $f$ is continuous,

*

*every equivalence class is closed.

Let $0<x<y$. Since $y=\frac {x +(2y-x)}{2}$, either $x\sim 2y-x$ or there exists $z\in (x,y)$ such that $z\sim y$. Therefore,

*for every $x<y$, if [$\forall z\in(x,y)$ $z\not\sim y$] then $x\sim 2y-x$.

It suffices to prove the following proposition.

Proposition 1. Every equivalence relation on $\mathbb R^+$ that satisfies (1) and (2) is trivial (i.e., has one equivalence class).

Proof.
Suppose there were a non-trivial equivalence relation "$\sim$" satisfying (1) and (2).
Step 1. Every equivalence class is unbounded and its interior is either unbounded or empty.
Suppose $\langle x\rangle$ were an equivalence class which is either bounded or has a non-empty bounded interior. There exits $\epsilon\geq 0$ such that $\langle x\rangle$ contains an interval of length $\epsilon$, and there exists $x'=\max\{x'': [x'',x''+\epsilon]\subset \langle x\rangle\}$. Take some $y \in (x',\infty)\setminus \langle x\rangle$, and let $y'=\min (
\langle  y\rangle\cap[x',\infty))$. By (2), $[x',x'+\epsilon]'\sim 2y'-[x',x'+\epsilon]$ contradicting the maximality of $x'$.
Step 2. Every equivalence class is an arithmetic sequence.
Let $\langle x\rangle$ be an equivalence class. If $x_0=\inf \langle x \langle >0$, then by (2) the elements of $(x_0,2x_0)$ are not in $\langle x\rangle$. Since $\langle x\rangle$ is unbounded and closed, there is a minimal $r_x\geq x_0$ such that $x_0+r_x\in\langle x\rangle$. By (2), the elements of $(x_0,x_0+r_x)$ are not in $\langle x\rangle$ and $x_0+r_x$ is in $\langle x\rangle$. Applying the same argument inductively on all intervals $[x_0+nr_x,x_0+(n+1)r_x]$, we get $\langle x\rangle=\mathbb R^+\cap (x+r_x\mathbb Z)$.
Suppose $\inf \langle x \rangle = 0$ then, the compliment of $\langle x \rangle$ contains an interval $(a,b)$ such that $a,b\in \langle x \rangle$ and starting from that interval $\langle x \rangle$ is an arithmetic sequence with period $b-a$. Since this is the case for any such intervals, they must all have the same length; therefore $\inf \mathbb R^+\setminus\langle x\rangle >0$. Since $\langle x\rangle$ has a bounded interior it must have an empty interior (by Claim 1); therefore it does not contain a prefix of $\mathbb R^+$, so $\inf \langle x \rangle >0$.
Step 3. For every $x$ and  $y$, $r_y \leq r_x$ with strict inequality for some $x,y$. Contradiction!
Let $x\not\sim y$. There exists $x'\sim x$ such that $\langle y\rangle\cap(x',x'+r_x)\neq\emptyset$. By (2), since $\forall z\in(x',x'+r_x)\ z\not\sim x'+r_x$, $\langle y\rangle\cap(x'+r_x,x'+2r_x)\neq\emptyset$. By induction, $\langle y\rangle\cap(x'+nr_x,x'+(n+1)r_x)\neq\emptyset$, for all $n\in\mathbb N$; therefore $r_y\leq r_x$. Take $x$ and $y=x+\frac 2 3 r_x$. By (2), $y\sim y'=x+\frac 4 3 r_x$. It follows that $r_y\leq |y'-y|<r_x$.


text:
Q: Load JSON File into Robot Framework I am trying to load a JSON file and use the values to perform some actions based on my tests. I tried to load the json value which I think I got right, but when trying to log the output, I got error message:
Resolving variable '${qa["REQUEST_ID"]}' failed: TypeError: list indices must be integers or slices, not str
Not exactly sure what this means since I am new to Robot Framework. This is what I did to load and log the values:
    ${file}     Get File    ${CURDIR}/RequestIDs.json
    ${qa}       Evaluate    json.loads('''${file}''')   json
    Log To Console          ${qa["REQUEST_ID"]}

Json file looks something like:
[
    {
        "REQUEST_ID" : 10513
    },
    {
        "REQUEST_ID" : 48156
    },
    {
        "REQUEST_ID" : 455131
    }
]

So basically I want to get the "REQUEST_ID" value and type that in a text field.

A: Look at the structure of your json - it's a list of dictionaries; so you have to first specify which list member you want, and then its REQUEST_ID field:
Log To Console          ${qa[0]["REQUEST_ID"]

# print the value from all present dictionaries in the list:
FOR    ${member}    IN    @{qa}
    Log To Console          ${member["REQUEST_ID"]
END


text:
Q: does pipe operator modify its input/output? Or is ls aware of pipe? consider the following... when I execute 'ls' without any flags, it returns the results in a single line, like the following:
me@myComp /cygdrive/c/test/
$ ls
folder1/  folder2/  folder3/

now, if I want to grep the results for something, say '2', I get the following:
me@myComp /cygdrive/c/test/
$ ls | grep 2
folder2/

Shouldn't it return the entire line? I would expect this result has I used ls -l | grep 2.
It seems to me that either the pipe operator is changing the input to grep in some way, or that somehow ls is aware of the pipe and changes its own output.
folder1/  folder2/  folder3/ is a single string, is it not? so how then does grep know to only return folder2/, and not folder1/ folder2/ folder3/?

A: See the manpage for ls, namely the flag -1:

-1      (The numeric digit ``one''.)  Force output to be one entry per
               line.  This is the default when output is not to a terminal.

If you want to force multi-column output use

-C      Force multi-column output; this is the default when output is to
               a terminal.

So to answer your question, yes, ls is aware where the output goes and it has well-defined behavior depending on it which you can easily override.


text:
Q: Спойлер в таблице Друзья, прошу помощи! Уверен решение простейшее, но я не силен в js и jquery. В общем необходимо, чтобы по клику по тексту в определенной ячейке, под ней выезжало 2-5 строк таблицы.

            <col width="790">
            <col width="270">
            <col width="270">
            <col width="270">

                    По клику сюда открывались две следующие строки
                    Да
                    Да
                    Да

                            Сейчас должны быть скрыты

                        Да
                        Да
                        Да

                            Сейчас должны быть скрыты

                        Да
                        Да
                        Да

Вот пример. Сначала 2 и 3 строка должны быть скрыты, а при клике на ссылку "выезжать". Заранее спасибо!

A: реализуется довольно просто при помощи jquery $(elem).toggle()
.toggle() переключает свойство display: none; на display: block; и наоборот
Пример на codepen

$('.button-spoiler').on('click', function() {
  $('.item-spoiler').toggle("slow");
});
.item-spoiler {
  display: none;
}

  <col width="790">
  <col width="270">
  <col width="270">
  <col width="270">

      По клику сюда открывались две следующие строки
      Да
      Да
      Да

        Сейчас должны быть скрыты

      Да
      Да
      Да

        Сейчас должны быть скрыты

      Да
      Да
      Да


text:
Q: Centos 7: unexpected SYS WRAP from Intel I350 IGB in syslog I see the following message repeat every 18-19 minutes on syslog on one of my 2 servers running Centos 7:
kernel: igb 0000:03:00.1: unexpected SYS WRAP

The NIC in question is I350 Gigabit built-in on a Supermicro server. It has 1 port dedicated to running PTP4Linux and one port providing the host's main connection. The server that's experiencing the issue runs Centos 7.3 (1611), and the one that isn't experiencing it still runs Centos 7.1. Any ideas?

A: Looks like the older igb drivers had some issues when setting Time Sync Interrupt Cause Register.
From in-kernel Support mailing list and kernel git:

TSAUXC.DisableSystime is never set, so SYSTIM runs into a SYS WRAP
  every 1100 secs on 80580/i350/i354 (40 bit SYSTIM) and every 35000
  secs on 80576 (45 bit SYSTIM).
This wrap event sets the TSICR.SysWrap bit unconditionally.
However, checking TSIM at interrupt time shows that this event does
  not actually cause the interrupt.  Rather, it's just bycatch while the
  actual interrupt is caused by, for instance, TSICR.TXTS.
The conclusion is that the SYS WRAP is actually expected, so the
  "unexpected SYS WRAP" message is entirely bogus and just helps to
  confuse users.  Drop it.

So, seems that it's safe to ignore.
Kernel starting from 4.14 and CentOS 7.5 should be free from it


text:
Q: express.js share routes to render page in different way I have written a page called sponsorCenter, but I need to control it with two routes:
app.get('/sponsorCenter',function(req, res){});

app.get('/sponsorCenter/all',function(req, res){});

The header, footer and the right columns are same.  When I change the URL, only the left column will change.
So my question is can I use just one route to judge the different access and render the page? Because only the left column is different, so I think it is not necessary to render the other parts via another route.

A: Yes you can accept the route parameter as a variable. The same variable will be accessible to the controller in the request req parameter.
app.get('sponsorCenter/:type*?', function(req, res) {
    console.log(req.params.type);
});

This would match all routes like sponsorCenter, sponsorCenter/all, sponsorCenter/admin, sponsorCenter/user1 etc.


text:
Q: Full History from date extracts I have a table of employee's and a record of transactions with employee ID's.
The table of Employee's contains 1 record for each employee for each role change, Team changes, Department Change etc.
I'm trying to allocate the correct Employee information for the right timeframe to the table.
Example Employee A works for Sales 15 days of the month and works for Service for another 15 Days.
2 entries exist in the Employee table, 1 old record for entry into sales Team and then a Team Swap Entry on day 15 of the month.
is it possible to populate the against each days calls the correct department that member of the team would have been working for at the time?


text:
Q: Hibernate WHERE does not work for @Embedded with null member I have a class Posting with an @Embedded:
public class Posting {
  @Embedded
  private BankDetails bankDetails;
}

public class BankDetails {
    private String bankCode;
    private String bankName;
}

Now I want to list all Postings with a bankCode of 123 and a bankName of null.
Query q = entityManager.createQuery("SELECT o from Posting o WHERE bankDetails=?");
q.setParameter(1, new BankDetails("123", null));

However I don't get any results.
Why?
Here's the sql query Hibernate executes:
select posting0_.bank_code as bank_cod6_42_, posting0_.bank_name as bank_nam7_42_
from posting posting0_
where (posting0_.bank_code, posting0_.bank_name)=('123', null)

(Btw, this parentheses syntax is called Row Value Constructors.)
That obviously does not work because is compares null with =.

*

*Is this a bug? If yes, which component generates the SQL statement? (Hibernate? the mysql-connector?)

*Any ideas for a workaround?

Environment: MySQL Server 5.7 on Win10, Spring 4.0.3, Hibernate 4.3.11, mysql-connector 5.1.30

A: Yes there is a workaround, but it requires you to be a bit more verbose with the query.
entityManager.createQuery( "SELECT o FROM Posting o WHERE " +
    " o.bankDetails.bankCode = ? " +
    " AND o.bankDetails.bankName IS NULL" );
entityManager.setParameter( 1, "123" );

I honestly haven't seen a query generated with a tuple value like that, but most of my past experience has been with SQL Server that does not support such a syntax.  If you believe it's a bug, please feel free to open a JIRA issue.

A: This is a bug in Hibernate 4 and 5.
It should be fixed in Hibernate 6: https://hibernate.atlassian.net/browse/HHH-8172
See @Naros answer for a workaround.


text:
Q: changing image colour by CSS3 (Filters) I have a png image which works as a link and I would like to give it an effect on hover. For example its background colour changes to orange.  Can I do it by CSS?
Or any other effect, such as an orange shadow around the shape inside the png image, and not the whole image (including transparent areas).
This is the code so far:

.latestTrack img {
    float:right;
    margin-right:50px !important;
}
.latestTrack img:hover {
    box-shadow: 0 0 10px orange;
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
}

A: You can set a shadow around a shape of a png alpha image with a drop shadow filter.
-webkit-filter: drop-shadow(10px 10px 10px gray);

See this link for + info
drop shadow filter comparison


text:
Q: access RDS through ec2 beanstalk instance I have an RDS instance running and I want to access it from a beanstalk instance. They are both in the same VPC and I have followed the instructions from the amazon documentation link.
Here is my table for the inbound rules I have assigned to the security group of the RDS instance.

The sg-c6...etc is the security group of the beanstalk instance.
When I am trying to run
 mysql -u master -ppass -h rds.instanceid.eu-central-1.rds.amazonaws.com dbname

I am getting
ERROR 2003 (HY000): Can't connect to MySQL server on 'rds.instance.eu-central-1.rds.amazonaws.com' (110)

A: It seems to me like you have an issue with networking restrictions within your VPC.
Please try to login to your AWS account and navigate to the VPC management section. Navigate to Route Table and select your route table. Edit your Subnet Associations and make sure that all subnets are included

A: By default, MySQL server will run on port 3306 but your security group says 3310.  MySQL on RDS will be no different.  I would suggest changing the security group port to 3306.


text:
Q: Issue with Updating in Ubuntu 12.04 Running on Flash Drive I am trying to update the packages on Ubuntu 12.04 LTS, which is running on a flash drive.  I tried in the command: sudo apt-get update and receive the following error:
W: Duplicate sources.list entry cdrom://Ubuntu 12.04.3 LTS _Precise Pangolin_ - Release amd64 (20130820.1)/ precise/main i386 Packages (/var/lib/apt/lists/Ubuntu%2012.04.3%20LTS%20%5fPrecise%20Pangolin%5f%20-%20Release%20amd64%20(20130820.1)_dists_precise_main_binary-i386_Packages)
W: Duplicate sources.list entry cdrom://Ubuntu 12.04.3 LTS _Precise Pangolin_ - Release amd64 (20130820.1)/ precise/restricted i386 Packages (/var/lib/apt/lists/Ubuntu%2012.04.3%20LTS%20%5fPrecise%20Pangolin%5f%20-%20Release%20amd64%20(20130820.1)_dists_precise_restricted_binary-i386_Packages)'

How can I fix this problem so the system can update packages correctly?

A: From experiencing a similar problem in the past it be could be lack of space on the flash drive. It processes then gives that error at the end. Do you have enough space on your flash drive?.


text:
Q: How to get the full link using BeautifulSoap The function get("href") is not returning the full link. In the html file exist the link:

But, the function link.get("href") return:

"navhome.php?lightbox&dpxshig=/iprop_prod=180-slim/tipo=fotolivro/width=950/height=615/control=true/tema=tema_02/nome_tema=Q2wmYWFjdXRlO3NzaWNvIFByZXRv&cpmdsc=MOZAO"

sub_site = "https://www.fotoregistro.com.br/navhome.php?vitrine-produto-slim"

response = urllib.request.urlopen(sub_site)

data = response.read()

soup = BeautifulSoup(data,'lxml')
for link in soup.find_all('a'):

    url = link.get("href")
    print (url)

A: Let me focus on the specific part of your problem in the html:

You can get it by doing:
for link in soup.find_all('a', {'class':'warp_lightbox'}):
    url = link.get("href")
    break

you find out that url is:
'//www.fotoregistro.com.br/\rnavhome.php?lightbox&dpxshig=/iprop_prod=180-slim/tipo=fotolivro/width=950/height=615/control=true/tema=tema_02/nome_tema=Q2wmYWFjdXRlO3NzaWNvIFByZXRv&cpmdsc=MOZAO'

You can see two important patterns at the begininning of the string:

*

*// which is a way to keep the current protocol, see this;

*\r which is ASCII Carriage Return (CR).

When you print it, you simply lose this part:
//www.fotoregistro.com.br/\r

If you need the raw string, you can use repr in your for loop:
print(repr(url))

and you get:
//www.fotoregistro.com.br/\rnavhome.php?lightbox&dpxshig=/iprop_prod=180-slim/tipo=fotolivro/width=950/height=615/control=true/tema=tema_02/nome_tema=Q2wmYWFjdXRlO3NzaWNvIFByZXRv&cpmdsc=MOZAO

If you need the path, you can replace the initial part:
base = 'www.fotoregistro.com.br/'

for link in soup.find_all('a', {'class':'warp_lightbox'}):
    url = link.get("href").replace('//www.fotoregistro.com.br/\r',base)
    print(url)

and you get:
www.fotoregistro.com.br/navhome.php?lightbox&dpxshig=/iprop_prod=180-slim/tipo=fotolivro/width=950/height=615/control=true/tema=tema_02/nome_tema=Q2wmYWFjdXRlO3NzaWNvIFByZXRv&cpmdsc=MOZAO
www.fotoregistro.com.br/navhome.php?lightbox&dpxshig=/iprop_prod=180-slim/tipo=fotolivro/width=950/height=615/control=true/tema=tema_02/preview=true/nome_tema=Q2wmYWFjdXRlO3NzaWNvIFByZXRv&cpmdsc=MOZAO
.
.
.

Without specifying the class:
for link in soup.find_all('a'):
    url = link.get("href")
    print(repr(url))

A: Use select and seems to print fine
import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.fotoregistro.com.br/fotolivros/180-slim?cpmdsc=MOZAO')
soup = bs(r.content, 'lxml')
print([item['href'] for item in soup.select('.warp_lightbox')])

Use
print([item['href'] for item in soup.select('[href]')])

for all links.


text:
Q: Exchanging data between Java and C# application Beside using the socket, is there any better way we can use to exchange data between those two types of applications. They will always run on the same machine.
Thank you.

A: You could create separate a Rest service that hold data in a queue, then clears the queue after the data is  retrieved.


text:
Q: What is the logic to move a paddle left and right automatically on the iPhone? I am just developing a simple iPhone application where a paddle moves left and right automatically.
My logic:
// First to determine the CGPoint of paddle
CGPoint detectXY = CGPointMake(paddle.center.x ,paddle.center.y);

// Second to determine the velocity of paddle
CGPoint paddleVelocity = CGPointMake(1,1);

// Adding velocity with X,Y cordinate
paddle.center = CGPointMake(paddle.center.x + paddleVelocity.x,
                            paddle.center.y + paddleVelocity.y);

But the paddle is not moving...
Any ideas?

A: If you created the UIImageView in Interface Builder, make sure you connect it up to your IBOutlet or it won't respond to you setting the .center property. This has bitten me many times.

A: my updated code

- (void)viewDidLoad {

[super viewDidLoad];

[NSTimer scheduledTimerWithTimeInterval:0.9 target:self selector:@selector(game) userInfo:nil repeats:YES];

}

-(void)game{

CGPoint imgVelocity = CGPointMake(20,1);
CGPoint detectXY = CGPointMake(imgViewPaddle.frame.origin.x , imgViewPaddle.frame.origin.y);

int x1= (int)detectXY.x;

  CGRect rect=imgViewPaddle.frame;

  if(x1>=0)
  {
imgViewPaddle.frame=CGRectMake(imgViewPaddle.frame.origin.x-imgVelocity.x, imgViewPaddle.frame.origin.y, imgViewPaddle.frame.size.width, imgViewPaddle.frame.size.height);

  }
  else  //<0
  {
   imgViewPaddle.frame=CGRectMake(imgViewPaddle.frame.origin.x+imgVelocity.x, imgViewPaddle.frame.origin.y, imgViewPaddle.frame.size.width, imgViewPaddle.frame.size.height);

  }

 rect=imgViewPaddle.frame;
}


text: Q: How to call a function using node.js in my android application when data is added in firebase realtime database I have this project with two applications, an admin and a client application. This project is an SOS application, wherein the admin application is the response to the emergency, and the client application is the user requesting help. What I want to happen is that whenever a user request help(adds data on firebase real-time database), the cloud function will listen to that and calls the notification function in my admin application that will notify all the admin accounts.


text:
Q: How to unset ListView button's onClickListener for a single item - Android I have used a TableLayout to produce the following cart activity output.
 .
So the listview has 3 listviews(Item,Price,quantity) and a button (for delete)
I wanted to give a heading to the cart. So, I initalized the first item of the listview as the title ('Item Name','Price','Quantity','Delete')
Now The problem is, Whenever the user clicks on delete button (as circled in the pic), The title also gets deleted. (Since the onClickListener has been applied to all buttons by default in the adapter class)
How should i remove the onClickListener on the first Button and keep it as it is for the rest of the buttons ?
Extra: If you guys can suggest some awesome way to format this cart so that it doesnt look so naive, It'd be great. :) Happy Diwali and Thanks in Advance.
- Android newBee
cartlayout.xml file
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*"
android:background="#ffffff">
<TableRow>
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/cartlist_layout"
android:orientation="horizontal">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/t1"
    android:textStyle="normal|bold"
    android:padding="5dip"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@+id/t2"
    />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/t2"
    android:padding="5dip"
    android:textStyle="normal|bold"
    android:layout_centerHorizontal="true"
    />

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/t2"
    android:id="@+id/t3"
    android:textStyle="normal|bold" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:id="@+id/button6" />
</TableRow>>
</TableLayout>

The Java Code:
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view=inflater.inflate(R.layout.fragment_mycart,container,false);
    this.getActivity().setTitle("AADESH");

    cartlistview=(ListView)view.findViewById(R.id.listView1);

    db=new DatabaseHelper(this.getContext());
    db.onCreate();
    Cursor res=db.onView();
    int len=res.getCount();

    listCartItems = new ArrayList<CartItems>();
    listCartItems.add(new CartItems("Item Name", "Quantity", "Price","Delete"));

    if(len==0)
    {
        Toast.makeText(this.getContext(),"Cart is Empty.",Toast.LENGTH_SHORT).show();
        statusOfCart=false;
    }
    else {
        while (res.moveToNext()) {
            String itemname = res.getString(1).toString();  // 0 is id, 1 is name, 2 is qty, 3 price
            String itemqty = Integer.toString(res.getInt(2));
            String itemprice = Integer.toString(res.getInt(3)) ;
            Toast.makeText(this.getContext(),itemname,Toast.LENGTH_SHORT).show();
            listCartItems.add(new CartItems(itemname, itemqty, itemprice,"X"));
        }
    }
    CartListAdapter cartListAdapter = new CartListAdapter(getContext(), R.layout.cartlist_layout, listCartItems);
    cartlistview.setAdapter(cartListAdapter);

    return view;
}

}
And the CartAdapter Java Code here:
public class CartListAdapter extends ArrayAdapter<CartItems> {
Context context;
int resLayout;
List<CartItems> listCartItems;
int pos;
public CartListAdapter(Context context,int resLayout,List <CartItems> listCartItems) {
    super(context, resLayout, listCartItems);
    this.context=context;
    this.resLayout=resLayout;
    this.listCartItems=listCartItems;
}

@NonNull
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View v=View.inflate(context,resLayout,null);
    pos=position;
    TextView name=(TextView)v.findViewById(R.id.t1);
    TextView qty=(TextView)v.findViewById(R.id.t2);
    TextView price=(TextView)v.findViewById(R.id.t3);
    Button delete=(Button)v.findViewById(R.id.button6);

    CartItems cartItems=listCartItems.get(position);
    name.setText(cartItems.getItemname());
    qty.setText(String.valueOf(cartItems.getQty()));
    price.setText(String.valueOf(cartItems.getPrice()));
    delete.setText(String.valueOf(cartItems.getDel()));

    delete.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listCartItems.remove(position);
                    notifyDataSetChanged();

                }
            }
    );

    return v;
 }
}

A: execute listCartItems.remove(position); only when position > 0.


text:
Q: Understanding SkiaSharp and Maui Coordinates I understood that the origin for SkiaSharp Rectangles lies in the upper left corner. But after this my understanding fails. I tried it with this tutorial but this did not quite help: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/bitmaps/drawing#copying-and-modifying-bitmaps
Imagine the code at the End i have a destination Bitmap of Size 1080 by 1080. From my understanding when i make my dstination SKRect to have coordinates (0,0,1080,1080) the Canves should draw on the whole destination Bitmap, however, it does not work i get blank white space. When i instead create a Maui.Rect with(0,0,1080,1080) which, from my understanding, should have the same properties with the origin in the upper left corner and then transform it to and SKRect it works.
Next try was to set the origin a bit further into the image like they did on the tutporial. So i created a new SKRect with Coordinates (100,100,980,980) since when i go further into the image i have to reduce the lower right coordinates so that they are not outside the Bitmap. This, however, does not work and produces a blank white space again. The coordinates of the Rectangle declaring the space of the source Bitmap i want to copy stayed the same in both cases. These were (0,0,150,150). I wanted to move enlarge the source Rectangle a bit so i used (100,100,150,150) which i made sure still lies in the source Bitmap, however, this also produces a blank white space. How does this work i do not understand this.
Edit: In the discussion in the Comments in my other Post i got told that the coordinates are based o nthe image control. Which would make sense for me but i do not know how to get the Image Control here as the image just got uploaded and was not displayed anywhere yet.
Edit 2: The Goal of this simple project is to understand how i wou.d set up the source Rectangle and change its coordinates to geth arbitrary specific parts of the image.
Edit 3: An Example of what i do not understand:
When i set the Rectangles up like this:
SKBitmap destination = new SKBitmap(1080, 1080);
        Rect destRec = new Rect(0,0,1080,1080);
        SKRect dest = SkiaSharp.Views.Maui.Extensions.ToSKRect(destRec);
        var height = sourceMap.Height;
        var width = sourceMap.Width;
        SKRect source = new SKRect(0,0,width,height);

The image looks like this:

But when i substract 100, where the height of the uploaded Image is 1332 and the Width 2000, the result looks liek that, which is totally not understandable for me:
SKBitmap destination = new SKBitmap(1080, 1080);
        Rect destRec = new Rect(0,0,1080,1080);
        SKRect dest = SkiaSharp.Views.Maui.Extensions.ToSKRect(destRec);
        var height = sourceMap.Height;
        var width = sourceMap.Width;
        SKRect source = new SKRect(0,0,width+100,height+100);

The View:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
         xmlns:ImageCroppingTry2="clr-namespace:ImageCroppingTry2"
         x:DataType="ImageCroppingTry2:MainPageViewModel"
         x:Class="ImageCroppingTry2.MainPage">

<ContentPage.Resources>
    <ResourceDictionary>
        <toolkit:ByteArrayToImageSourceConverter x:Key="ByteArrayToImageSourceConverter" />
    </ResourceDictionary>
</ContentPage.Resources>

<VerticalStackLayout>
    <Image x:Name="displayImage" Source="{Binding Image, Converter={StaticResource ByteArrayToImageSourceConverter}}"/>
    <Button Command="{Binding UploadImageCommand}"></Button>
</VerticalStackLayout>

Its ViewModel:
[ObservableProperty]
    public byte[] image;

    [RelayCommand]
    public async void UploadImage()
    {
        //Well i pick a photo for convenience
        FileResult im = await MediaPicker.Default.PickPhotoAsync();

        SKBitmap sourceMap;
        using (Stream s = await im.OpenReadAsync())
        {
            using (MemoryStream ms = new MemoryStream())
            {
                await s.CopyToAsync(ms);
                ms.Seek(0, SeekOrigin.Begin);
                sourceMap = SKBitmap.Decode(ms);
            }
        }

        SKBitmap destination = new SKBitmap(1080, 1080);
        Rect destRec = new Rect(0,0,1080,1080);
        //SKRect dest = new SKRect(0,0 , 1080,1080);
        SKRect dest = SkiaSharp.Views.Maui.Extensions.ToSKRect(destRec);
        //Rect sourceRect = new Rect(0,0,destination.Width,destination.Height);
        SKRect source = new SKRect(0,0,150,150);
        //SKRect source = SkiaSharp.Views.Maui.Extensions.ToSKRect(sourceRect);
        using (SKCanvas canvas = new SKCanvas(destination))
        {
            canvas.Clear();
            canvas.DrawBitmap(sourceMap, source, dest);
        }

        SKImage skImage = SKImage.FromBitmap(destination);
        SKData encoded = skImage.Encode();
        using (MemoryStream memory = new MemoryStream())
        {
            encoded.AsStream().CopyTo(memory);
            Image = memory.ToArray();
        }
    }

A: Maui Image is in DIPs (~160 per inch). If Density is 2, then 1800 dips becomes 1800x2 = 3600 pixels.
Doc is unclear, but ToSkRect might be multiplying by Density. Don't use it, unless you intend to take Maui coords and convert them to Skia coords. For example, if you will be drawing to a control with (WidthRequest=400, HeightRequest=320), the size for Skia will be (400 * Density, 320 * Density). I think ToSkRect might do that multiplication for you. But I have not tested.
For your usage, do new SkRect(x, y, w, h).
Re "coords based on image control". Right now, your goal is to manipulate a bitmap. This first step is not affected by what you will do with the bitmap to draw it. Then you  render that to a control. Don't need to consider where the control will be on the screen.
Skia can render bitmaps. An alternative approach is to use Skia's command to draw the bitmap, inside an OnPaint method. Inside that, coordinates are all in pixels.


text: Q: Licensed Seats Self Service we have a managed package listed in the AppExchange which uses the licensed seats licensing model. Frequently, our customers ask us to increase the licensed seats by email and for this we have to manually go to LMA and do it from there. Is there a way where our package subscribers can increase their licensed seats in a self service way?


text:
Q: OpenCV 3.2 gives Select Timeout when grabbing, but fswebcam works I'm having a bit of a weird issue here.
Simply put, I'm trying to grab a frame from a camera (Mercury 2.0 Webcam embedded camera), but it's not going as expected.
I'm running Debian Jessie on a BeagleBone Black.
I've installed OpenCV 3.2 and tested it, my Vision algorithm is working fine with imread(), so it's time to start using the camera.
The first issue I encountered was the camera not working in Ubuntu 16.04 minimal. So I switched to Debian Jessie and now I can grab 1600x1200 frames using fswebcam (fswebcam -r 1600x1200 --jpeg 95 -D 0 test.jpg) in a fraction of a second, as expected.
I was very happy when that worked, so I'm starting to get rather annoyed again now that VideoCapture >> Mat won't work as expected.
Here's the kicker though, if I set the resolution to 800x600, it works fine.
When I set the resolution to 1600x1200, it first gives me Select Timeout, but then immediately a succesful result.
So, it is able to grab the frame, but just not on the first try. Seems to me it's a timing issue. So I tried using grab() and retrieve(), but that doesn't seem to help either.
Anyone else got some good ideas/suggestions/tips or experience with this issue?
Some specs:
$ uname -a
Linux arm 4.9.13-bone4 #1 [date] armv7l GNU/Linux

$ gcc --version
gcc (Debian 4.9.2-10) 4.9.2

$ v4l2-ctl --all
Driver Info (not using libv4l2):
    Driver name: uvcvideo
    Card type: Mercury USB2.0 Camera
    Bus info: usb-musb-hdrc.1.auto-1.1
    Driver version: 4.9.13

$ fswebcam -r 1600x1200 --jpeg 95 -D 0 test.jpg
Opening /dev/video0
Trying source module v4l2...
/dev/video0 opened.
No input was specified, using the first.
Capturing frame...
Captured frame in 0.00 seconds.
Processing captured image...
Setting output format to JPEG, quality 95
Writing JPEG image to 'test.jpg'.

Basic code functionality
VideoCapture cam(0);
cam.set(CAP_PROP_FRAME_WIDTH,width);
cam.set(CAP_PROP_FRAME_HEIGHT,height);

     /*check cam.isOpened()*/

     /*echo some camera properties*/

if(cam.grab()) cam.retrieve(frame);

imwrite(filename, frame);

cam.release();

Also, I tried:
modprobe uvcvideo nodrop=1 timeout=6000

But that didn't help...
I also tried using the old CvCapture class, but that didn't help either.
Been working on it all day and figured a few extra things out:
The BeagleBone seems to have a hard time with plugging in and unplugging USB devices. I wanted to check the pictures I took, so I plugged in my USB Flashdrive, mounted it, unmounted it, took it out, admired the pictures. Then the camera wouldn't work anymore, even with fswebcam. Had to reboot to get it working again.
Also, taking a few 2MP pictures to fast in a row with fswebcam, seems to give issues as well. Sometimes I get to take a few pictures, other times only 1 before I need to reboot again. When I can't take 2MP pictures, I still can take 800x600 pictures though.
Simply replugging the USB doesn't help.

A: For everyone who's dealing with this same issue (Select Timeout). I fixed it for my case, I don't know if this is going to work for everyone, but I'd love if this helped others out there.
The problem is probably because the camera you're trying to use is only semi-UVC compatible. UVC is familiar with products being sold as UVC compatible, when in fact they're not. So they added something called quirks.
Read more about this here: UVC FAQ
So, how to fix the Select Timeout? Well, easy apparently.
First, we close the uvcvideo module
rmmod uvcvideo

Next we enable it again, but with the bandwidth quirk enabled; and just in case add the nodrop and timeout flags as well.
modprobe uvcvideo quirks=128 nodrop=1 timeout=6000

If you want the solution to work after rebooting, add both those lines to your .bash_profile
I tested the BeagleBone Black with my USB2.0 camera after this fix thoroughly:
Average framerate: 4 (highly dependent on light, get 5 FPS with a darker environment)
Average error percentage: 2.4% (1953 succesful pictures out of 2000 read()'s)
Tested by grabbing 100 frames in a loop and doing this 20 times. I rebooted after 10, to make sure my .bash_profile edit worked as well and to see if there was any performance difference after a fresh reboot. There is none ;)


text:
Q: Updating a kubernetes job: what happens? I'm looking for a definitive answer for k8s' response to a job being updated - specifically, if I update the container spec (image / args).
If the containers are starting up, will it stop & restart them?
If the job's pod is all running, will it stop & restart?
If it's Completed, will it run it again with the new setup?
If it failed, will it run it again with the new setup?
I've not been able to find documentation on this point, but if there is some I'd be very happy to get some signposting.

A: The .spec.template field can not be updated in a Job, the field is immutable. The Job would need to be deleted and recreated which covers all of your questions.
The reasoning behind the changes aren't available in the github commit or pr, but these changes were soon after Jobs were originally added. Your stated questions are likely part of that reasoning as making it immutable removes ambiguity.


text:
Q: Display the input when a specific option is selected in laravel I am using Laravel 5.2. I have an input to display when a specific option is selected and it works fine.
But I want to use {{ old('field') }} to have the old results.

*

*When I select Yes, I have to display the input.

*When I select No, I have to hide the input.

When I have validation errors (server side) and I return to the page, then I have the old results (example: value='yes') but the input that was displaying is now hidden and I have to re-click on yes to display it again. I use the change event to display the input.
$("#etat_civil").change(function () {
    if ($(this).val() == "Marié") {
        $("#div_conjoint").show();
    } else {
        $("#div_conjoint").hide();
    }
});

A: You can check the old('field') value for it is set then you can set your element to be visible.
For example, you can do something like this.
<input type="text" name="my-field" value="abc" style="display: {{ old('field') ? 'block' : 'none' }}">

By doing this you are checking if old('field') is set then the field/block/div should be visible otherwise keep it hidden.
So in your case when the validation fails and it redirects you back to the form you will have old('field') value set and the element should be visible to you.
Update:
As suggested by other guys you can also do this by putting the JS code on page onload but I don't prefer that way as it sometimes shows a slight delay in loading the element. Not a great deal but I still prefer doing it the other way that I explained above.


text:
Q: How to use react-window with React Table version 6.10.0? I am following this virtualized-rows example of react table. I know this code is using react and react table latest versions.
How can I use the react-window package with my react table version 6.10.0 and react version is 16.2.0? Also, I am loading data from backend in blocks, for example, the first 500 records, then the next 500 records and so on but the react table is visible to users with first 500 records and after this data is kept on appending, in this case, react-window FixedSizeList function is useful or VariableSizeList is useful?
Code to render React Table:
const columns = this.renderColumn();

<ReactTable
    data={data}
    filterable={true}
    defaultFilterMethod={(filter, row) =>
      matchSorter([row[filter.id]], filter.value).length !== 0
    }
    columns={columns}
    showPagination={false}
    pageSize={data.length}
    minRows={0}
    ref={r => {
      this.selectTable = r;
    }}
    noDataText="No results found"
    defaultSorted={[
      {
        id: 'travelerLastName',
        desc: false,
      },
    ]}
/>

Function to render columns:
renderColumn = () => [
    {
      name: '',
      Header: x => {
        return (

              <input
                type="checkbox"
                onChange={() => this.toggleSelectAll()}
                checked={this.state.selectAll === 1}
                ref={input => {
                  if (input) {
                    input.indeterminate = this.state.selectAll === 2;
                  }
                }}
              />

        );
      },
      Cell: ({ original }) => {
        return (

              <input
                type="checkbox"
                className="checkbox"
                checked={this.state.selected[original.id] === true}
                onChange={() => this.toggleRow(original.id)}
              />

        );
      },
      Filter: ({ filter, onChange }) => (

          <SearchIcon title={''} />

      ),
      sortable: false,
      width: 45,
    },
    {
      id: `travelerFirstName`,
      Header: 'First Name',
      Cell: ({ original }) => {
        return (
          <a
            href={`/client/travelers/${original.traveler_id}?tab=profile`}
            target="_blank"
          >
            {original.travelerFirstName}

        );
      },
      accessor: d => d.travelerFirstName,
      filterMethod: function(filter, rows) {
        return filterIncludedData(
          rows,
          'travelerFirstName',
          filter.value.toLowerCase(),
        );
      },
      filterAll: true,
      Filter: ({ filter, onChange }) => (
        <input
          placeholder="Search First Name"
          value={filter ? filter.value : ''}
          onChange={event => onChange(event.target.value)}
        />
      ),
      className: 'left-aligned',
    },
  ];

Some code snippets will really help.


text:
Q: Injection through Annotations vs injection through XML file in Spring 3. Limitations related to inheritance I have the following abstract class, with a property called portletBaseViewName which is meant to be different for every concrete Controller extending AbstractController.
public abstract class AbstractController {

    private String portletBaseViewName;

    protected String getPortletBaseViewName() {
        return portletBaseViewName;
    }

    @Required
    @Value("")
    public void setPortletBaseViewName(String portletBaseViewName) {
        this.portletBaseViewName = portletBaseViewName;
    }

}

@Controller
@RequestMapping("VIEW")
public class ReservationOfBooksViewController extends AbstractController{}

I know that is possible declaring the injections in a XML, doing so:
<bean id="abstractController" class="es.alcampo.portalweb.portlets.common.controller.AbstractController" abstract="true">
    <property name="portletBaseViewName" value="" />
</bean>

<bean id="reservationOfBooksViewController" class="es.example.portalweb.portlets.reservationofbooks.controller.ReservationOfBooksViewController" parent="abstractController">
    <property name="portletBaseViewName" value="reservationOfBooks" />
</bean>

<bean id="myShopViewController" class="es.example.portalweb.portlets.reservationofbooks.controller.MyShopViewController" parent="abstractController">
    <property name="portletBaseViewName" value="myShop" />
</bean>

Do I need to redefine?:
@Controller
@RequestMapping("VIEW")
public class ReservationOfBooksViewController extends AbstractController{
    @Value("reservationOfBooks")
    public void setPortletBaseViewName(String portletBaseViewName) {
        super.setPortletBaseViewName(portletBaseViewName);
    }
}

I don't like the previous option, which would be the most elegant option if there is to reach the purpose of injecting one value or another depending on the concrete class through annotations?
I know inheritance and annotations sometimes conflict.
Thanks a lot.

A: Do you actually need @Value here?
@Value is useful when it contains some expressions evaluated by Spring at runtime. Otherwise you can replace it with explicit initialization (and keeping the setter method allows you to override this values from XML configuration):
public abstract class AbstractController {
    protected String portletBaseViewName = "";

    public void setPortletBaseViewName(String portletBaseViewName) {
        this.portletBaseViewName = portletBaseViewName;
    }
}

@Controller
@RequestMapping("VIEW")
public class ReservationOfBooksViewController extends AbstractController{
    public ReservationOfBooksViewController() {
        this.portletBaseViewName = "reservationOfBooks";
    }
}

A: As shown by @axtavt in previous answer, you don't need any annotation in AbstractController. In addition, you don't need to define abstractController in XML. In case, you want to configure common properties in all of its subclasses, you can put them in abstract bean (without any class name):
<!-- define common properties in abstract bean-->
<bean id="controllerTemplate" abstract="true" />

<bean id="reservationOfBooksViewController" class="es.example.portalweb.portlets.reservationofbooks.controller.ReservationOfBooksViewController" parent="controllerTemplate">
<property name="portletBaseViewName" value="reservationOfBooks" />

In subclasses, @Value annotation is not required and you can use 'getPortletBaseViewName()' method to get view name.


text:
Q: difference between using this.$emit and this.$root.$emit is there a difference between using $emit directly and $root.$emit ?
=> this.$emit('default-choice', this.choice); & this.$root.$emit('default-choice', this.choice);
`this.$emit('default-choice', this.choice);`
`this.$root.$emit('default-choice', this.choice);

A: I think you don't need to use root emit for any case. It's really good to have emit we can emit to the parent component but when it comes to root emit if you ever think "I need to use root emit" then think again and try to use something else (ex: vuex).
and also in Vue.js 3 they removed $on, $once and $off instance methods
https://github.com/vuejs/rfcs/blob/master/active-rfcs/0020-events-api-change.md

Vue 1.x implemented the component event system similar to that of AngularJS, with $dispatch and $broadcast where components in a tree can communicate by sending events up and down the tree. In Vue 2, we removed $dispatch and $broadcast in favor of a more state-driven data flow (props down, events up). With Vue 2's API, $emit can be used to trigger event handlers declaratively attached by a parent component (in templates or render functions), but can also be used to trigger handlers attached imperatively via the event emitter API ($on, $off and $once). This is in fact an overload: the full event emitter API isn't a part of the typical inter-component data-flow. They are rarely used, and there are really no strong reason for them to be exposed via component instances. This RFC therefore proposes to remove the $on, $off and $once instance methods

A: If you need something global, you'll use a store.
An $emit is meant to be used from parent to child and is the probably the one you'll be using 99% of your time.
On top of that, the documentation doesn't really approach the $root.$emit last time I checked. Hence that one could be ignored.
Keep things simple, it will be easier to debug thanks to Vue devtools.


text:
Q: jQuery fade-in text wraps at first then squishes up during transition Sorry, I know it's not a great Title description but the effect is difficult to describe and sort of needs to be observed.  See the jsFiddle below.
http://jsfiddle.net/eus5R/
    $(document).ready(function(){
        var speed = 2500;
        $("div#leftPane p").hide();

        $("div#leftPane").click(function() {
            $("div#leftPane p").each(function() {
                if ($(this).is(":hidden")) {
                    $(this).show(speed);
                    exit();
                }
            });
        });
    });

Basically, I have a bunch of p's that start hidden and I want to reveal one at a time by mouse click.  I want the reveal to take a half-second, fading the text in.  The problem is that during the fade-in transition, the text juggles around as the browser tries to render it properly.  How can I avoid that "juggling" and just have it fade-in already rendered as it will finally be shown?
Thanks!

A: Using show with a duration animates the width as well.  The smaller width causes the text to wrap. You can use slideDown instead:
http://jsfiddle.net/eus5R/3/

A: Instead of show and hide use fadeOut and fadeIn:
$(document).ready(function(){
            var speed = 2500;
            $("div#leftPane p").fadeOut(0);

            $("div#leftPane").click(function() {
                $("div#leftPane p").each(function() {
                    if ($(this).is(":hidden")) {
                        $(this).fadeIn(speed);
                        return false;
                    }
                });
            });
        });

http://jsfiddle.net/eus5R/2/
Oh and instead of non-existant exit() which breaks the each because it throws an exception, do a return false


text:
Q: Laravel Mix and Webpack: Cannot Load JSON File (Webpack Adding .js to Filename) I am getting the following error from Webpack:
ERROR in ./resources/assets/js/data/vehicles.json.js
Module build failed: Error: ENOENT: no such file or directory, open '/Users/path-to-my-app/resources/assets/js/data/vehicles.json.js'

I'm not surprised that the file fails to load. The JSON file is not called vehicles.json.js. It is called vehicles.json.
The line where the file is imported reads:
import vehicleTypes from '../data/vehicles.json'

However, if I change the filename to vehicles.js (and use an export ststement to make it a module) and change the import statement to read:
import vehicleTypes from '../data/vehicles.js'

Webpack works fine.
I was under the impression that the latest webpack could load JSON files without configuring anything.

A:
Since webpack >= v2.0.0, importing of JSON files will work by default. You might still want to use this if you use a custom file extension.

You might be using an older version of webpack which would explain why
the loader is not working by default.
Try adding it to your webpack.mix.js file as a custom loader.
Install the loader:
npm install --save-dev json-loader

And declare the custom loader:
mix.webpackConfig({
         module: {
           loaders: [{
             test: /\.json$/,
             loader: 'json-loader'
             }]
           }
       });

And you should be able  to import .json files as one would expect.


text:
Q: removing input field value by jquery My problem is that the form automatically loads the value of field company name.
However  this is the required field.
I only want to remove the previous load value to be empty, and let the user to fill the input field.
For example previously when I filled the form I put value tadipar in the field, now  the  value tadipar is occurring for next time form filling also
I haven't tried anything because I dont have any clue what to do with this?
any suggestions so that i can do

'company' => [
                'company_name'    => [
                    'label'       => __( 'Company name', 'wp-job-manager' ),
                    'label_two'       => __( 'Enter the name of the company', 'wp-job-manager' ),
                    'type'        => 'text',
                    'required'    => true,
                    //'placeholder' => __( 'Enter the name of the company', 'wp-job-manager' ),
                    'priority'    => 1,
                    'labelstar' =>  '*',
                ],

the field is coming from the object above, it doesn't have value argument, that makes so difficult to find the code from 100000 files
additional informantion:- i am working on workscout wordpress theme, the from is built in wp-job-mananger plugin

A: I would recommend you to pass empty double-quotes in the placeholder, and value also empty.
'placeholder' => '',
'value' => ''

but due to some other possible functions autofilling this fields, you can always try this hardcore solution
type this in your console.log
document.getElementById("company_name").value=""

and you'l see it working, and that proofs that something else ich mixing the code

A: For me it sounds like that your browser is automaticly completing the field.
Set the parameter autocomplete="off" for the field (or perhaps for the entire form)


text:
Q: Get dynamic value for AMP html page I am trying to write simple product listing page.
I need to deal with real time data since product price and quantity changes.
What is the best way to achieve this?
I tried to use amp-list, but I have to set up endpoints where I can download json data. And it sounds like I need to set up an extra job which updates json data constantly.
I think I have to use iFrame but I want to make sure if iFrame is the only way and there is no workaround.
Is there any workaround or I can use amp-list for this purpose?
Thank you in advance.

A: In your case i see only amp-iframe as a solution. But iframe is not Google friendly for a product shop.
The best way is to find a solution with JSON and amp-list or amp-live-list

A: There is a component called amp-fresh which may solve your problem but it's still under development. You may want to subscribe to the issue to see if there are any updates.


text:
Q: Vim: match next/previous line in search pattern I'm trying to practice my search patterns for ex commands and trying to do stuff I would usually do with macros using them, and I got stuck with one I'm not sure is possible.
I have some code that looks like this:
public myFunc (): any {
    return {};
}

And I'm trying to yank it with this command (with the cursor after the function):
:?\vpublic\s*\w+\s*\(.*\)\s*:\s*\w+\s*\{?;/}$/y
This works as expected and matches the function that I mentioned up there.
What I would like to do but haven't found a way is to ignore the first line and the last one (I just want the contents of the function). I suspect it is possible to do it somehow (maybe +/- search offsets?), but I haven't had any luck yet.
Does anyone know how to do this? Thanks!

A: Yes, this is a simple matter of adding the appropriate offsets (:help search-offset). You basically define a range with two searches (one upwards from the current position, one downwards from there): ?...?;/.../. To exclude the targets, you just add / subtract 1; this is done by appending the offset to the search: ?...?+1;/.../-1. Applied to your example:
:?\vpublic\s*\w+\s*\(.*\)\s*:\s*\w+\s*\{?+1;/}$/-1y

A: To insert carriage return (Enter) like below use Ctrl-v Enter
:normal ?public^Mjwyiw

Explanation
:normal  ............ in normal mode
?public ............. search backward for public
^M .................. Enter
j ................... move to the line below
yiw ................. yank inner word


text:
Q: how do to training a tf object detection api model without using tf records I want to train a mobilenet ssd v2 model using the tf object detection api
to use this api you have to convert your dataset to a tf record and write the path to it in the config file
Whenever I look it up I find answers that include tf records, either one tf record that contains the whole dataset or multiple files with sections of it (but idk how to make the training use all sections of the dataset each epoch)

How do I train the model without loading the whole dataset in memory?
Is there a way to train without using tfrecords ?
If I convert my whole dataset to tfrecords I'll have 15 GBs of duplicated space, or is there a way to not load the whole tf record,loading shards of it at a time but still looping over  the whole dataset very epoch.


text:
Q: Running an if statement and storing the results in a vector I want to run an if statement with three potential outcomes:
   'FTH>FTA = "Home"
   FTH<FTA = "Away"
   FTH=FTA = "Draw"'

FTH & FTA are two integer variables
I want to store the answer in a vector.

A: Problem solved
Win <- ifelse(r1<0,"A", ifelse (r1>0,"H", "D")) # Full-time


text:
Q: Unique normal subgroups of every possible order Can one characterize groups $G$ for which there is a unique normal subgroup of order $d$ for every divisor of the order of $G$? For example must they be solvable?

A: Note: I'm interpreting the assumption on $G$ as: for every $d$ dividing $|G|$, the set of normal subgroups of $G$ of order $d$ has size exactly $1$.
Such a group must be cyclic. If $G$ is such a group, then for each prime $p$ dividing $|G|$, there is a normal Sylow $p$-subgroup of $G$, which is then unique, so $G$ is nilpotent and a product of its Sylow subgroups.
Now let $P$ be a Sylow $p$-subgroup of $G$. Since $P$ is a direct factor of $G$, a subgroup $H \le P$ is normal in $P$ iff it is normal in $G$. Now any maximal subgroup of $P$ is normal in $P$, hence normal in $G$, hence unique (in $G$ or $P$), so $P$ has a unique maximal subgroup, which implies $P$ is cyclic.
Thus all Sylow subgroups of $G$ are cyclic and normal, so $G$ is a product of cyclic groups (of relatively prime order), hence is cyclic. Conversely, cyclic groups do satisfy the hypothesis.
Update: Since it was asked in the comments, and the proof is so simple, let me say why $P$ having a unique maximal subgroup implies $P$ cyclic: if $P$ is not cyclic, but has a unique maximal subgroup $H$, then for every $a \in P$, $\langle a \rangle \subsetneq P$, hence $a \in H$, but then $P \subseteq H$, contradiction. This proof only needs that every proper subgroup is contained in a maximal subgroup, which holds e.g. if the group is finite.


text:
Q: Regex for repeated pattern separated by comma Hey so I would like to generate a regex that repeats a pattern (\w*:\w*) separated by a comma. I will include some valid and invalid patterns to see in the following:
Valid: SomeAlpha:Abc
Valid: Aa:Bb,Cc:Dd,Ee:Ff,Gg:Hh
Invalid: Aa:Bb,Cc:Dd,Ee:Ff,
Invalid: First:oNe:NoComma

I currently setup the regex like this
\(\w*:\w*,\)*

However, as you can see the issue is that the pattern has to end with the comma. I tried putting ?, but it does not validate the fourth example in the above. Is there any pattern expression that I could do in the case?

A: You could write the pattern as:
^\w+:\w+(?:,\w+:\w+)*$

Explanation

*

*^ Start of string

*\w+:\w+ Match : between 1+ word chars

*(?:,\w+:\w+)* Optionally repeat the comma and the previous pattern using a non capture group (?:

*$ End of string

Regex demo


text:
Q: Find and return ex-staff but not current Given the following tables:
Staff
+------------+--------+
| employeeID |  name  |
+------------+--------+
|     100100 | Kelly  |
|     101010 | John   |
|     222222 | Stuart |
+------------+--------+

Academics
+------------+----------+
| employeeID | degreeID |
+------------+----------+
|     100100 | PhD      |
|     101010 | Eng      |
|     222222 | Sci      |
+------------+----------+

Class
+------------+-----------+-----------+
| employeeID | studentID | subjectID |
+------------+-----------+-----------+
|     100100 |       998 | BUS_18_2  |
|     100100 |       921 | BUS_18_2  |
|     100100 |       901 | BUS_18_2  |
|     100100 |       934 | BUS_19_1  |
|     100100 |       964 | BUS_19_2  |
|     100100 |       934 | LED_19_1  |
|     100100 |       964 | LED_19_2  |
|     101010 |       901 | COE_19_2  |
|     101010 |       874 | COE_19_2  |
|     101010 |       823 | COE_19_2  |
|     222222 |       212 | FTR_17_2  |
|     222222 |       102 | FTR_17_1  |
|     222222 |       684 | FTR_18_1  |
+------------+-----------+-----------+

Return a list of name and degreeIDs of all staff not holding a class in 2019
I've tried various methods around constructing nested having statements to detect if a staff member has worked in multiple years (based on counting subjectIDs), but thats more or less 'hardcoding' it and new entries could corrupt such a method (as seen in the example).
Expected result
+------------+------------+
|    name    | degreecode |
+------------+------------+
|   stuart   | sci        |
+------------+------------+

A: Use correlated subquery with not exists
select distinct name, degreeid
from staff a join academics b on a.employeeid=b.employeeid
join class c on a.employeeid=c.employeeid
where not exists
   (select 1 from class c1 where c.employeeid=c1.employeeid and subjectID like '%_19%')

A: The basic idea is not exists.  However, your data model seems to be missing information on what classes are offered in 2019.  Assuming that class has this information:
select s.name, a.degreeid
from staff s join
     academics a
     on s.employeeid = a.employeeid
where not exists (select 1
                  from class c
                  where c.employeeid = s.employeeid and
                        c.year = 2019
                 );


text:
Q: How to subset bigger dataframe into smaller dataframes in order to write them as .csvs? Im trying to create a function which basically splits a data.frame into several smaller dataframes:
  split_save <- function(df){

    dataframes <- vector("list",length(df))

    dates <- unique(df$date)

    for (i in 1:length(dates)){
    dataframes[[i]] <- df[df$date==dates[i],]
    }

    for(i in 1:length(dataframes)){
      write.csv(dataframes[[i]], paste0(i,".csv"))
    }

  }

My problem is that I cant figure out how to split the bigger data.frame into smaller data frames where the split points are based on weeks and write the corresponding week with its name as the smaller data.frame:
Example data:
df <- data.frame(date = seq(as.Date('2016-01-04'),as.Date('2018-01-
 12'), by = 1),
       some_data = length(t))

date    some_data

2016-01-04  2
2016-01-05  2
2016-01-06  2
2016-01-07  2
2016-01-08  2
2016-01-09  2
2016-01-10  2
2016-01-11  2
2016-01-12  2
2016-01-13  2
2016-01-14  2
2016-01-15  2
2016-01-16  2
2016-01-17  2

Desired output after writing .csv into some dir:
data_for_week1.csv
date    some_data

2016-01-04  2
2016-01-05  2
2016-01-06  2
2016-01-07  2
2016-01-08  2
2016-01-09  2
2016-01-10  2

data_for_week2.csv
   date some_data

   2016-01-11   2
   2016-01-12   2
   2016-01-13   2
   2016-01-14   2
   2016-01-15   2
   2016-01-16   2
   2016-01-17   2

Appreciate any insights!

A: Turning my comment into an answer...
Here's how you can split your data by year-week combinations:
dfsplit <- split(df, format(df$date, "%Y-%W"))

Then you can loop over the names of the resulting list and write each table to a csv-file:
lapply(names(dfsplit), function(x)
       write.csv(dfsplit[[x]], paste0("dir/data_for_week_", x, ".csv")))


text:
Q: Import Excel Sheet in Laravel and show the extracted data in UI I am using Angular 4 in my Front end and Laravel 5.2 in my backend.I want to import an Excel sheet from UI, store the values in DB, retrieve the values and show them in UI using Angular.
I am using Maatwebsite/Excel package in laravel for this. My excel sheet has the following structure.

name      | details          | price
expertphp | Online Tutorials | 100
hello     | code             | 200
My laravel code is as below:
Here myFile is the key which has the file path and name as its value.
    $File = $request->file('myFile');
    $path = $request->file('myFile')->getRealPath();
    $real_name = $File->getClientOriginalName();
    $data = Excel::load($path)->get();

    if($data->count()){
        foreach($data as $key => $value){
            $arr[] = ['name' => $value->name, 'details' => $value->details, 'price' => $value->price];
        }
    }

    return response()->success($data);

I get my reponse as below:
     {
        "errors":false,
        "data":[
                {
                   "namedetailsprice":"expertphp\tOnline tutorials\t100"
                },
                {
                   "namedetailsprice":"hello\tfirst code\t2000"
                }
               ]
      }

I am not understanding why is the headers becoming one field.
Appreciate any help.
Thanks.

A: I think if you change your code to this code it will work or it will get you closer to your solution:
$File = $request->file('myFile');
$path = $request->file('myFile')->getRealPath();
$real_name = $File->getClientOriginalName();
$data = Excel::load($path)->get();
$returnData = [];

if($data->count()){
    foreach($data as $key => $value){
        $arr = ['name' => $value->name, 'details' => $value->details, 'price' => $value->price];
        array_push($returnData,$arr);
    }
}

return response()->success($returnData);

If I understand you correctly, then you would want this new $returnData to be returned instead of the raw loaded excel file. One other reason that I changed your code was that you were saving only one row of your data and replacing it with another row in the same array $arr. Now it is pushing new rows every time and saving all.


text:
Q: Revert merges keeping resolutions In our team we are applying git flow without pull request, this is, each one of us develops features in their own branches that start in develop and once finished they get merged into develop. Our workflow is:

*

*Pull develop

*Branch feature/[name] from develop

*Develop that feature in that branch

*Go back to develop, pull develop

*Merge the finished feature

*Resolve possible conflicts

*Push develop

However some times happens that two developers finish a feature at the exact same time. Now, imagine two developers have merge conflicts. The first one who pushes develop will update origin's develop, so when the other tries to push, it will fail, since they have diverged.
Now, we don't want the second developer pulling from develop and merging both... Because it breaks the "beauty" of having only one develop branch with features branching/merging from it but then have 2 develop branches. What we do now is reset local develop to origin/develop and repeat the merge/finish feature, but if the merge conflict was hard to resolve we have to do it again.
In a picture, we have this:

I'd like to repeat that last merge, but with origin/develop without having to resolve manually the conflicts I had. I know I may have new merge conflicts, but I don't want to repeat the ones I have already resolved.
It looks like a rebase --preserve-merged, but that doesn't keep merge resolutions....

A: A tweak to your workflow should solve this problem.  Instead of merging feature into develop, rebase feature onto develop.  If develop creeps forward the work done to rebase the feature branch is still done: they only have to rebase on top of the new branch.  You're always trying to work on the tip of the develop branch.  This makes things much simpler.
Here's an example.  This is the state when both developers are ready to merge.  They've both updated develop.
A - B - F [origin/develop] [develop]
     \
      C - D - E [feature/1]

A - B - F [origin/develop] [develop]
 \
  Z - X - Y [feature/2]

They both git rebase develop.  (This will result in new commit IDs, but I'm taking the liberty in these diagrams of reusing the same IDs to show the continuity of commit content).
         [origin/develop] [develop]
A - B - F - C - D - E [feature/1]

         [origin/develop] [develop]
A - B - F - Z - X - Y [feature/2]

In order to preserve the existence of the branch in history, they both do a merge but with --no-ff. git checkout develop; git merge --no-ff feature/X  This doesn't actually merge, but forms a nice feature bubble which is useful for later code archaeology to understand which series of commits was done together as a single feature.
         [origin/develop]
A - B - F - C - D - E [feature/1] [develop]
        \          /
         ----------

         [origin/develop]
A - B - F - Z - X - Y [feature/2] [develop]
         \          /
          ----------

Then they both push, but the first dev gets there first.  The second one has their push rejected and so the second dev updates develop.
A - B - F - C - D - E [feature/1] [origin/develop] [develop]
        \          /
         ----------

          Z - X - Y [feature/2]
         /
A - B - F - C - D - E [origin/develop] [develop]
        \          /
         ----------

No problem, the second dev repeats the procedure.  They rebase onto develop.  This only requires resolving conflicts with the new commits from feature/1.
A - B - F - C - D - E - Z - X - Y [feature/2]
        \          /  [origin/develop] [develop]
         ----------

Then git checkout develop; git merge --no-ff feature/2; git push.
                      ---------
                     /         \
A - B - F - C - D - E - Z - X - Y [feature/2]
        \          /              [origin/develop] [develop]
         ----------

And finally both developers delete their local branches.  The history bubble and merge points will preserve their information for historical use.
Here's the process.

*

*Update develop.

*

*git checkout develop

*git pull --rebase

*Rebase feature onto develop.

*

*git checkout feature

*git rebase develop

*Create an artificial merge point.

*

*git checkout develop

*git merge --no-ff feature

*Push develop.

*Delete feature.

Steps 1 to 3 can be safely repeated during the feature development process to keep feature up-to-date with what everyone else is pushing.
Here is a blog post further illustrating this technique.

A: rerere is what you are looking for; when enabled, it remembers how you resolved merge conflicts, and when it sees the same conflicts, automatically resolves them for you. Enable it with git config --global rerere.enabled true. You can read more about it here.


text:
Q: How to prove some statements about divisibility and the $\gcd$ function Struggling with some number theory homework. Could use a helping hand. The two statements are as follows

*

*$\gcd(c, ab) \mid \gcd(c,a)\gcd(c,b)$

*If $c \mid ab$ and $\gcd(a,b)=1$, then $c=\gcd(a,c)\gcd(b,c)$
I'm supposed to figure out a proof for each, but cannot even seem to get them started.

A: As a general rule, try Bezout's identity in questions about $\gcd$. In the first case, solve for integers $x,y,z,w$ the equations:
$$ax+cy = (a,c)\\bw+cz=(b,c)$$
Multiply these together and show that there is a solution to:
$$(ab)X+cY = (a,c)(b,c)$$
So $(ab,c)\mid (a,c)(b,c)$.
The other question requires a little more, but you can use the first part to get that $c\mid (a,c)(b,c)$ in the second part.
But we also know that $(a,c)\mid c$ and $(b,c)\mid c$. Use that $(a,c)$ and $(b,c)$ are relatively prime to show that $(a,c)(b,c)\mid c$.

A: HINT
Use the fundamental theorem of arithmetic (FTA). These hints will guide you to a solution to 2.

*

*Write out $a$ and $b$ with the FTA. Do they share any primes?

*In general, what is $\gcd(x,y)$ in terms of the factorizations of $x$ and $y$?

*Put these together to conclude the answer to 2.

A: Let $v_p(x)$ denote the "valuation of $x$ at $p$" -- that is, the number of times the prime $p$ divides the integer $c$ (and $v_p(0) = +\infty$, if we allow zero in our discussion). e.g. $v_2(12) = 2$, because $2^2 | 12$ but $2^3 \!\!\not|\: 12$.
Then $\gcd(a,b) = c$ if and only if, for every prime $p$, $v_p(c) = \min\{v_p(a), v_p(b)\}$.
Similarly, $x | y$ if and only if, for every prime $p$, $v_p(x) \leq v_p(y)$.
Translating your questions into this form will make them rather simple!
Note that this amounts to a systematic way of working algebraically with the unique factorizations of integers.