text:
Q: Ember.js anchor link I have a login box on homepage that I need to link to. The login box has id="login" in html and I have a link to it like this
Login
 so on click it takes me to that login div but when I hit refresh or go directly to the link with anchor I get Uncaught Error: No route matched the URL 'login'
Anybody has any ideas how I can accomplish this simple task in Ember? Thanks.
Update
Here's how my code looks like:
The navigation

Signup

{{#linkTo 'about'}}About{{/linkTo}}

and somewhere below on the page I have

 -- some content

A: The problem is that Ember used the hash part in the URL to store the current state of your application. Spontaneously i see two possible solutions.
1 - *Don't let Ember use the hash part of your URLs.* Therefore use the HTML5 history location implementation of Ember. This will result in URLs like yourdomain.com/users/1/ without #.
App.Router.reopen({
  location: 'history'
});

2 - Don't use this technique. Instead use jQuery to do the scrolling to the relevant part. This could look like this:

Signup

{{#linkTo 'about'}}About{{/linkTo}}

And in the corresponding view:
App.YourView = Ember.View.extend({
  jumpToLogin : function(){
    $('html, body').animate({
        scrollTop: $("#login").offset().top
    }, 2000);
  }
});

This may seem a lot of code for this small feature, but i guess this is a nicer user experience right? Actually you can improve this approach by extracting this logic into a mixin, so you don't have to repeat it over and over:
App.ScrollToMixin = Ember.Mixin.create({
  scrollDuration : 2000, //default
  scrollTo : function(selector){
    $('html, body').animate({
        scrollTop: $(selector).offset().top
    }, this.get("scrollDuration");
  )
});
// mix it into your View
App.YourView = Ember.View.extend(App.ScrollToMixin, {});

And use it in your template:

Signup

{{#linkTo 'about'}}About{{/linkTo}}

PS: I haven't tested the code with the mixin. I am not absolutely sure wether the String "login" gets passed to the action handler exactly like that. So you would have to test :-)

A: I use a component, which could also be extended to support query params via an action.
var ScrollToComponent = Ember.Component.extend({
  tagName: 'a',
  anchor: '',

  scrollTo: function () {
    var anchor = this.get('anchor'),
      $el = Ember.$(anchor);

    if ($el) {
      Ember.$('body').scrollTop($el.offset().top);
    }
  }.on('click')
});

This is how you'd use it:
{{#scroll-to anchor=anchor}}Jump To Anchor{{/scroll-to}}

Where anchor is #my-id.
Edit
Here's an ember-cli addon that does this https://www.npmjs.com/package/ember-scroll-to

A: Query Params
Updated answer based on the Query Params approach (currently featured flag as of Dec 21 2013)
Based on alexspellers original JSFiddle, complete demo can be found here: http://jsfiddle.net/E3xPh/
In your Router, add support for query params
App.Router.map ->
  @resource 'index', path: '/', queryParams: ['anchor']

Using the Route of your choice, setup a property for the anchor query param in the setupController method.
App.IndexRoute = Em.Route.extend
  setupController: (controller, context, queryParams) ->
    controller.set 'anchorLocation', queryParams.anchor

Finally in your Controller make an observer for the anchorLocation property.
App.IndexController = Em.ArrayController.extend
  showAnchor: (->
    $elem = $(@anchorLocation)
    $scrollTo = $('body').scrollTop($elem.offset().top)
  ).observes 'anchorLocation'

Now you can use the following code in your templates to scroll to an anchor or point your browser to /#/?anchor=#login for example.
{{#linkTo anchor='#login'}}Show login{{/linkTo}}

Simple action approach
Possible answer based on what you wrote in the comments to the first answer. Hacked together something simple here.
http://jsbin.com/osEfokE/11
Clicking the Index link takes you to the IndexRoute and scrolls you to the login box, however the URL is not reflecting this change and typing #login will not work either.
App.ApplicationRoute = Ember.Route.extend({
    events: {
        goToLink: function(item, anchor) {
            var $elem = $(anchor);
            var $scrollTo = $('body').scrollTop($elem.offset().top);

            this.transitionToRoute(item.route).then($scrollTo);  //.transitionTo is depricated
        }
    }
});

Instead of using linkTo, you will use goToLink in your template when you want to scroll to an anchor.

Index

{{#linkTo about}}About{{/linkTo}}

{{#linkTo contact}}Contact{{/linkTo}}

A: I got this working in Ember with the simple action approach from kroovy's answer.
Since Ember has changed its API I had to alter kroovys approach at little bit.
Two things have changed:

*

*Events in an Ember.Route are deprecated and replaced by actions in Ember.Controller

*instead of transitionTo you have to use transitionToRoute

Here is how I got it working in Ember Version 1.7.0
Ember Handlebars-Template new.hbs
{{!-- Navigation --}}

Part 1

Part 2

{{!-- content --}}

...

...

Ember App.Controller NewController.js
App.NewController = Ember.ArrayController.extend({

 actions: {

    goToLink: function(item, anchor) {
        console.log('NewController > goToLink');
        var $elem = $(anchor);
        var $scrollTo = $('body').scrollTop($elem.offset().top);

        this.transitionToRoute(item.route).then( $scrollTo);
    }
}
});

A: The problem with most of the previous answers is that if the route does not change when clicking on a "link" with a "href hash/fragment/id" in it then the ember router will not fire the hooks necessary to perform most of previous solutions.
This is evident in pages with multiple "headings" where you want to allow a user to jump from a "nav/index or list of links" to the relevant section of the page (like on terms of service or about pages).
In these situations ember requires that you "opt into a full transition" so that the router will fire it's hooks even though the route has not changed but the query params have. See "opting into a full transition" for more information.
NOTE: The only documented hook that will be fired when using this "opt in" is the model hook.
I believe that this "full transition" opt-in was only intended to be used when refreshing models on query param change for things like sorting or filtering.
Admittedly this seems like a bit of a hack, but the above "opt-in" can be used for scrolling to our div /anchor tag in question. In the future the opt-in might be able to fire other more appropriate hooks as well (setupController specifically would be nice).
Also In case anyone else is googling. I also tried using the "willTransition" and "didTransition" actions on the route as well. While they did get fired when transitioning from other routes sadly they also fail to fire when transitioning from the same route to itself.
Finally it should be obvious to some (but wasn't for me  at first) that in order to get the browser to scroll to the id in question the dom will need to be fully loaded. So we have to perform the scroll inside the Ember.run.schedule('afterRender', callback.
FYI I am using the latest ember-cli, ember.js and ember-data generally available at the moment:

*

*ember-cli: 1.13.7

*ember: 1.13.6

*ember-data: 1.13.7

app/router.js
  this.route('about', {
    queryParams: ['anchor']
  });

routes/about.js
import Ember from 'ember';

export default Ember.Route.extend({
  queryParams: {
    anchor: {
      refreshModel: true
    }
  },
  model: function(params) {
    var aboutController = this.controllerFor('about');
    aboutController.set('anchorLocation', params.anchor);
  }
});

app/controllers/about.js
import Ember from "ember";
export default Ember.Controller.extend({
  queryParams: ['anchor'],
  anchor: '',
  showAnchor: function() {
    var _this = this;
    Ember.run.schedule('afterRender', function scrollToAnchor(){
      var elem = Ember.$(_this.anchorLocation);
      elem.get(0).scrollIntoView(true);
    });
  }.observes('anchorLocation'),
});

app/templates/footer.js

              {{#link-to "about" (query-params anchor='#contact')}}Contact{{/link-to}}

              {{#link-to "about" (query-params anchor='#support')}}Support{{/link-to}}

              {{#link-to "about" (query-params anchor='#team')}}Team{{/link-to}}

A: My problem was that if I clicked on the destination link from another page, it would go to the destination but not scroll down to the correct portion of the page. After a few hours here was my fix:
note: I'm using ember-cli, and emblem and ember 1.8
link in my navigation bar (in application.emblem)
li
 a#concept-link click=jumpToConcept
  | Le Concept

then if I'm already on page I just scroll up. If I'm not already on page then I go to that page with query params concept=true
action in application controller
scrollToConcept: function() {
  Ember.$(document).ready(
    Ember.$('html, body').animate({
        scrollTop: Ember.$("#concept").offset().top
    }, 750)
  )
},

 //allow clicking of link with specific id to go to that part of page
jumpToConcept : function(){
  if (this.get('currentPath') === 'index') {
    this.send('scrollToConcept');
  } else {
    this.transitionToRoute('index', { queryParams: {concept: true}});
  }
}

in index controller I then add the concept query params
export default Ember.Controller.extend(

  queryParams: ['concept'],
  concept: null
}

I then add a scrollToConcept event in index view (the page I just went to) that listens for page loading and checks the concept queryParam. If concept=true I then scroll to the concept part of the page.
index view
scrollToConcept: function() {
    if (this.controller.get('concept') === 'true') {
        Ember.$('html, body').animate({
        scrollTop: Ember.$("#concept").offset().top
    }, 750);
    }
}.on('didInsertElement')

then for normal index links, I add an action that sets concept=null so that the concept query param doesn't show up in the url.
link in nav bar
a click=goToIndex
  h3 id={logoClass} Happy Dining

then in application controller I go the the index route, set the concept query param to null (so it doesn't show up in the url) and scroll to the top (just incase it was lower on the page)
actions: {
 goToIndex: function() {
  this.transitionToRoute('index', { queryParams: {concept: null}});
  Ember.$(window).scrollTop(0);
 }
}

Hope that helps people in the future!!!

A: If anyone's trying to solve this problem with Ember 3, I've got a solution. It makes use of the same queryParams approach as others have mentioned, but I couldn't get anything to work on the controller. The only approach that I found worked was to use the route + jQuery.ready function.

// route/application.js
import Route from '@ember/routing/route';
import $ from 'jquery';

export default Route.extend({
  queryParams: {
    anchor: null
  },

  setupController: function(controller, context, params) {
    let anchor = params.queryParams.anchor;

    // On ready, find the anchor offset and go there
    $().ready(function() {
      let anchorOffset = $("#" + anchor).offset().top
      window.scrollTo(0, anchorOffset);
    });
  }
});

Then in the template, use your queryParams as usual:

{{#link-to "path.to.page" (query-params anchor="my-anchor")}}My Link{{/link-to}}

Only issue here is that it's reloading the page every time, but apart from that seems to work - hope it helps someone.


text:
Q: fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 7864320 bytes) in wp-db.php I've been receiving the following error each time I attempt to update the menu in the dashboard:

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried
  to allocate 7864320 bytes) in
  /var/sites/p/[sitename].com/public_html/wp-includes/wp-db.php
  on line 1369

Going off previous advice, I have deactivated all plugins one-by-one to see if one of them was causing the error, though the error remains despite deactivating all plug-ins.
Having gone into wp-db.php to line 1369, this is what it reads:
$error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );

To expand, this is what lines 1342 to 1407 reads:
 * Print SQL/DB error.
 *
 * @since 0.71
 * @global array $EZSQL_ERROR Stores error information of query and error string
 *
 * @param string $str The error to display
 * @return false|void False if the showing of errors is disabled.
 */
public function print_error( $str = '' ) {
    global $EZSQL_ERROR;

    if ( !$str ) {
        if ( $this->use_mysqli ) {
            $str = mysqli_error( $this->dbh );
        } else {
            $str = mysql_error( $this->dbh );
        }
    }
    $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );

    if ( $this->suppress_errors )
        return false;

    wp_load_translations_early();

    if ( $caller = $this->get_caller() ) {
        /* translators: 1: Database error message, 2: SQL query, 3: Name of the calling function */
        $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
    } else {
        /* translators: 1: Database error message, 2: SQL query */
        $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
    }

    error_log( $error_str );

    // Are we showing errors?
    if ( ! $this->show_errors )
        return false;

    // If there is an error then take note of it
    if ( is_multisite() ) {
        $msg = sprintf(
            "%s [%s]\n%s\n",
            __( 'WordPress database error:' ),
            $str,
            $this->last_query
        );

        if ( defined( 'ERRORLOGFILE' ) ) {
            error_log( $msg, 3, ERRORLOGFILE );
        }
        if ( defined( 'DIEONDBERROR' ) ) {
            wp_die( $msg );
        }
    } else {
        $str   = htmlspecialchars( $str, ENT_QUOTES );
        $query = htmlspecialchars( $this->last_query, ENT_QUOTES );

        printf(
            '

%s [%s]
%s

',
            __( 'WordPress database error:' ),
            $str,
            $query
        );
    }
}

Awaiting further advice.

A: Through the advice found here by user Ewout, I have gone into wp-config.php and edited

define( 'WP_MEMORY_LIMIT', '96M' );

to a much higher number. It was originally set to 256 when I tried raising it in the past. This wasn't enough, so I have chosen a number 10000 and this fixed the problem. I hope I don't run into any future issues by raising it to such a number, though it did fix the problem. I hope this helps fellow novices out a bit who are receiving the same error message.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grid with clicable irregular shapes I'm having a bit of trouble here to develop this functionality since it must work on IE9+ so css clip-path is not an option ( http://caniuse.com/#feat=css-clip-path ).
The issue:

*

*I need to create a grid composed of 6 elements.

*Each element is an image.

*The images can be different according to user answers before getting to the grid page.

*Eeach element / image must be clicable and will acquire a "selected" class that will overlay div with text and background image.

image:

What is the best way to achieve this?

A: One way to do this could be to save out each combination of the six images you require into one big image. Then, depending on the user's answer combination, you insert the corresponding image as a background-image of a div. You then overlay click-able hotspots within the same div that roughly correlate to the dividing edges.
This may however not be the most practical solution and largely depends on how many answers/images you are dealing with.
Alternatively you could draw SVG shapes and set their fills to the images you require.
I can recommend Raphael.js as a starting point. You should be able to find what you need in the documentation
Another option would be to use HTML5 canvas:
http://jsfiddle.net/julienbidoret/GKP7X/1/
(credit goes to julienbidoret for the jsfiddle)
Javascript:
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');

img.onload = function () {

    ctx.save();
    ctx.beginPath();
    ctx.moveTo(20, 0);
    ctx.lineTo(240, 0);
    ctx.lineTo(220, 240);
    ctx.lineTo(0, 240);
    ctx.closePath();
    ctx.clip();
    ctx.drawImage(img, 0, 0);
    ctx.restore();
}

img.src = "http://upload.wikimedia.org/wikipedia/commons/2/2b/Clouds.JPG";

HTML:
<canvas id="c" width="300" height="300" ></canvas>

Both SVG and canvas are supported in IE9.


text:
Q: launchArgs in PushPlugin (Cordova and Windows Universal app) I'm trying to develop the Windows Universal App version of an app already developed for Android and iOS.
I'm using the PushPlugin for notification, but I don't understand where to find the launchArgs parameters sent inside the Toast package.
This is the xml:
<toast activationType="background" launch="{"type":"toast":"param1":"12345":"param2":"67890"}">
        <visual>
            <binding template="ToastGeneric">
                <text id="1">'.$subject.'</text>
                <text id="2">'.$message.'</text>
            </binding>
        </visual>
    </toast>

In the push.on("notification") method I expected to find "data.additionalData.foreground" (if my app is foreground - this works perfectly for Android and iOS), but this property in Windows is always undefined. Where is the error?
Thanks for every suggestion,
bye

A: Just in case someone else is having this question, the launch string is retrieved from the data.launchArgs variable on the client side.
https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#callback-parameters-2
However, it seems these arguments will be ignored when the app is in foreground, because thie launch parameter was intended only to launch the app when it's closed or in the background.


text:
Q: Range of A and null space of the transpose of A So I'm complete stuck with something. I know it the following statements are true (or at least the seem to be from the results that I got from messing around with it a bit on MATLAB), but I don't understand why they are true or how to show so.
Let $A$ be and $m$X$n$ matrix. Show that:
a) if $x \in N(A^TA)$ then $Ax$ is in both $R(A)$ and $N(A^T)$.
For this one I messed around with it with my own examples and I got $Ax=0$, therefore satisfing the statement, but I don't understand what's actually going on.
b) $N(A^TA)=N(A)$
again, makes sense when I see the results in MATLAB, but don't undestand why it works.
c) $A$ and $A^TA$ have the same rank
d) If $A$ has linearly independent columns, the $A^TA$ is nonsingular.
For the last two I have no idea on how to even start showing the relationship. I feel like I'm missing some crucial relationship between $A$ and $A^TA$, but I'm just not seeing it.
I would greatly appreciate any help of sugestions on how to show that these statements are true.
Thank you very much.

A: a) By definition $Ax\in R(A)$; on the other hand, $A^TAx=0$, by assumption, so $Ax\in N(A^T)$.
b) It is clear that $N(A)\subseteq N(A^TA)$. Suppose $x\in N(A^TA)$; then $x^TA^TAx=0$ as well, so $(Ax)^T(Ax)=0$, which implies $Ax=0$.
c) The rank-nullity theorem says that, if $B$ is an $m\times n$ matrix, then $\dim R(B)+\dim N(B)=n$. Let $A$ be $m\times n$ and apply the rank nullity theorem to $A$ and $A^TA$:
\begin{align}
n&=\dim R(A)+\dim N(A) \\
n&=\dim R(A^TA)+\dim N(A^TA)
\end{align}
Since by part b we have $\dim N(A)=\dim N(A^TA)$, we conclude $\dim R(A)=\dim R(A^TA)$.
d) If $A$ has linearly independent columns, its rank is $n$; so also $A^TA$ has rank $n$, hence it is invertible.

A: Let us show that (c) and (d) are both consecuences of (b):
Let $A\in R^{nxm}$ and $nul(A) = nul(A^TA)$

$ \dim nul(A)
= \dim nul(A^TA) $
$ n-rank(A) = n-rank(A^TA)$
$rank(A)=rank(A^TA)$

and, if $A$ has linearly independent columns, $nul(A)=\{0_{R^m}\} = nul(A^TA)$; and thus is proven that $\det(A^TA) \neq 0$
As for the proof of (b), and a more rigorous proof of $rank(A) = rank(A^TA)$, I'll post it after dinner.
EDIT:
$\dim col(A) + \dim nul(A) = n$
This property is what I had left unproven in my proof that (c) is consequence of (b), so there:
Let $A =
    \left( \begin{array}{ccc}
        - & v_1 & -\\
        & \ldots &\\
        - & v_n & -
    \end{array} \right)$ then:

$Ax = 0$ iff $v_ix = 0, \forall i$
$x \perp v_i, \forall i$

$x$ is perpendicular to every column of $A^T$, so it follows that

$x \in nul(A)$ iff $x \in (col(A^T))^\perp$

And so:

$\dim nul(A) = \dim col(A^T)^\perp$
$ = n- \dim col(A^T) = n-rank(A^T) = n-rank(A)$

EDIT:
Proof of (b):
Let $A \in R^{nxm}$:

$nul(A^TA) = \{ x \in R^m   |   A^TAx = 0_{R^m} \}$
$= \{ x \in R^m   |   Ax = 0_{R^n}   \quad$ or $\quad   Ax \in nul(A^T) \}$
but we have proven that $x \in nul(A^T)   \quad$ iff $\quad   x \in (col(A))^\perp$
There can be no $Ax \neq 0_{R^m}$ such that $A^TAx = 0_{R^n}   \quad$ !
and thus: $\quad   nul(A^TA) = \{ x \in R^m   |   Ax = 0_{R^n} \} = nul(A)$


text:
Q: Calculating percentage of increased and decreased values between factors I'm looking for a way to calculate the change of scores between factors (for example, questionnaire scores between Pre and Post treatment). I want to figure out what percentage of participants improved and what percentage did not between Pre and Post.
I have looked at some dplyr solutions but I think I am missing a line of code from it but I am not sure.
    ID<-c("aaa","bbb","ccc","ddd","eee","fff", "ggg","aaa","bbb","ccc","ddd","eee","fff", "ggg")
    Score<-sample(40,14)
    Pre_Post<-c(1,1,1,1,1,1,1,2,2,2,2,2,2,2)
    df<-cbind(ID, Pre_Post, Score)
    df$Score<-as.numeric(df$Score)
    df<-as.data.frame(df)

    #what I have tried
    df2<-df%>%
    group_by(ID, Pre_post)
    mutate(Pct_change=mutate(Score/lead(Score)*100))

But I get error messages. As well, I wasn't confident that the code was right to begin with.
Expected outcome:-
What I want to achieve is getting the percentages of ID's that have improved. So in the case of the mock example that I have provided, only 42.86% of ID's have improved from Pre to Post, while 57.14% actually worsened between Pre and Post.
Any suggestions would be welcome :)

A: you have several typos that is why you get an error.
You can do something like this to get old and new scores side by side:
library(tidyverse)

df %>%
  spread(Pre_Post, Score) %>%
  rename(Score_pre = `1`, Score_post = `2`)

   ID Score_pre Score_post
1 aaa        19         24
2 bbb        39         35
3 ccc         2         29
4 ddd        38         15
5 eee        36          9
6 fff        23         10
7 ggg        21         27

To get the number of improvements you have to convert Score to numeric first:
df %>% as_tibble() %>%
  mutate(Score = as.numeric(Score)) %>%
  spread(Pre_Post, Score) %>%
  rename(Score_pre = `1`, Score_post = `2`) %>%
  mutate(improve = if_else(Score_pre > Score_post, "0", "1")) %>%
  group_by(improve) %>%
  summarise(n = n()) %>%
  mutate(percentage = n / sum(n))

# A tibble: 2 x 3
  improve     n percentage
  <chr>   <int>      <dbl>
1 0           3      0.429
2 1           4      0.571

A: Another option with dplyr assuming you always have two values with Pre as 1 and Post as 2 would be to group_by ID and subtract the second value with first value and calculate the ratio for positive and negative values.
library(dplyr)

df %>%
  arrange(ID, Pre_Post) %>%
  group_by(ID) %>%
  summarise(val = Score[2] - Score[1]) %>%
  summarise(total_pos = sum(val > 0)/n(),
            total_neg = sum(val < 0)/ n())

# A tibble: 1 x 2
#  total_pos total_neg
#      <dbl>     <dbl>
#1     0.429     0.571

data
ID <- c("aaa","bbb","ccc","ddd","eee","fff", "ggg","aaa","bbb",
      "ccc","ddd","eee","fff", "ggg")
Score <- sample(40,14)
Pre_Post <- c(1,1,1,1,1,1,1,2,2,2,2,2,2,2)
df <- data.frame(ID, Pre_Post, Score)


text:
Q: Maven: How to Add JPA Project in EAR using Pom.xml How can I add JPA Project in the EAR pom.xml file? I don't see the JPA Module in the Maven.
    <build>
    <plugins>
        <plugin>
            <artifactId>maven-ear-plugin</artifactId>
            <version>2.10</version>
            <configuration>
                <earSourceDirectory>EarContent</earSourceDirectory>
                <generateApplicationXml>false</generateApplicationXml>
                <version>6</version>
                <defaultLibBundleDir>lib</defaultLibBundleDir>
                <modules>
                    <jarModule>
                        <groupId>artifactGroupId</groupId>
                        <artifactId>artifactId</artifactId>
                        <bundleDir>APP-INF/lib</bundleDir>
                    </jarModule>
                </modules>
            </configuration>
        </plugin>
    </plugins>
</build>


text:
Q: How can I use something stored in a DataBase? SQLite / Python So, I am new at DataBases and I have a question. I first made a re-search in the internet but could not find anything or actually I could not understand correctly what they were explaining. Before starting with my question I want to say that I am currently working in a Discord Bot in Python as Main Language and I am trying to create a per-server-prefix system. I have already made it once but in .JSON format. Then I heard that using .JSON to save this kind of Data is not actually good so I moved to DataBases. Now, my question is:
I have stored the guild_id and prefix in my DB, how could I use that for a per-server-prefix system? I have not tried anything yet except writing the Code to store both Texts. I would really love if anyone could explain to me not just tell me the Code! Any answer will be appreciated <3.
Main.py:
def get_prefix(client, message):

    db = sqlite3.connect("main.sqlite")
    cursor = db.cursor()
    cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = {message.guild.id}")
    result = cursor.fetchone()
    if result is None:
        return "/"
    else:

client = commands.Bot(command_prefix = get_prefix)

Prefixes.py (COGS):
    @commands.command()
    @commands.has_permissions(administrator=True)
    async def prefix(self, ctx, prefix=None):

        db = sqlite3.connect("main.sqlite")
        cursor = db.cursor()
        cursor.execute(f"SELECT prefix FROM prefixes WHERE guild_id = ?", ctx.guild.id)
        result = cursor.fetchone()
        if result is None:
            sql = ("INSERT INTO prefixes(guild_id, prefix) VALUES(?,?)")
            val = (ctx.guild.id, prefix)
            await ctx.channel.send(f"{prefix}")
        elif result is not None:
            sql = ("UPDATE prefixes SET prefix = ? WHERE guild_id = ?")
            val = (prefix, ctx.guild.id)
            await ctx.channel.send(f"update `{prefix}`")
        cursor.execute(sql, val)
        db.commit()
        cursor.close()
        db.close()

That is pretty much the whole code. If you think anything should be changed or have any suggestions, answer in the comments!

A: All you need to do is, after the else, put return result. For example:
result = cursor.fetchone()
if result is None:
    return "/"
else:
    return result

cursor.fetchone() returns a tuple with each element requested in the row, as you only requested the prefix, it will contain just that (e.g: ("!",)) which is permitted as your command_prefix callable can return a string or tuple of strings.
Warning:
You may want to add a check to ensure that someone doesn't specify an empty string (A zero length string with nothing in it) as their prefix, otherwise your bot will attempt to run every message it sees as a command
References: discord.ext.commands.Bot.command_prefix


text:
Q: Android Appium WebDriverWait throws NoSuchMethodError I'm working on automated tests for an Android app which loads content from a web database. Since the connection and result from the database may take some time, I tried to use the following code to wait until a button (which only appears when content is loaded) is visible.
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOf(driver.findElementById(ID))).click();

With driver being instantiated as AndroidDriver driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
When I run the test that uses this code, I get the following error:
java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.WebDriverWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object;

at Actions.Action1.main(Action1.java:47)
at Cases.Case1.main(Case1.java:43)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:645)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:851)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1177)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:756)
at org.testng.TestRunner.run(TestRunner.java:610)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)

Does someone know what is the problem?
I already added Guava 21.0 and 24.1-Android to Maven XML file, but neither of them changed anything in the results.

A: It might be a chicken-and-egg thing, since instead of checking for the existence of the element, you're assuming that it's in the DOM but not visible.  I would advise checking to see if it exists instead.
You could instead do a loop using findElements():
    while (true) {
        if (driver.findElements(By.id("com.oi.codigital:id/main_refresh_button")).size() == 0)
            break;
    }


text:
Q: Iterating over pandas Series only executes once I have more than 8000 items in the "index", but the for loop only does the job for the first item.
from datetime import datetime
from pandas import Series
from pandas import DataFrame

series = Series.from_csv('something.csv', header=1)
index = DataFrame(series.index)

for item in index:
    dt = datetime.strptime(item, "%Y-%m-%d %H:%M:%S.%f")
    dt = dt.time().isoformat()
    print(dt)

So the items in index column look like this: 1998-02-14 19:30:54.052000
And the for loop does this 19:30:54.052000, but only for the first line. Any idea why?

A: That's not how you loop over a series's items. What you did iterates over the columns, and in a series, there's only one. That's why it executes only once. Use Series.iteritems if there's no way to achieve your goal by vectorized operations.
for idx, item in index.iteritems():
    dt = ...

But in this case, you can use Series.apply instead of a for-loop.
index.apply(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S.%f").time().isoformat())


text:
Q: How to connect output layers to the input layer of another neural network? The Actor-network has 5 input neurons representing the state values and will produce one output value held by one output neuron.
The Q Network has 6 input neurons: 5 representing the state values and 1 representing the output of Actor-network.
I'll do gradient descent to train the Actor-network seperately, holding Q network's weights as constant.
My question is:
How should I structure to plug the output layer of Actor-Network into the input layer of the Q network, with TensorFlow 2.x?

A: You can just use the ŧf.keras.Model API:
actor_model = tf.keras.Model(inputs=...,outputs=...)
Q_model = tf.keras.Model(inputs=actor_model.outputs, outputs=...)


text:
Q: Setting Up Scopes with a HABTM Relationship in Rails I have a has_and_belongs_to_many relationship between Categories and Posts. I'm setting up a scope to query all Posts in a specific category. The scope below works, but it seems fairly verbose. Is there a better way this could be refactored?
In the Post model:
scope :in_category, ->(category) { joins(:categories).where(categories_posts: {category_id: category.id} ) }

A: I don't know any other way to this in Post model.
But create this scope is unnecessary. Assuming that you already has a Category instance, this works:
category.posts

Edit:
If you're looking for a method to call on the Post class, use this scope (but I think this is reinvent the wheel, since the Rails already provide the method above):
class Post
  scope :in_category ->(category) { category.posts }
end

A: Instead of using a scope, you can use a class method:
class Post < ActiveRecord::Base
  def self.in_category(category)
    category.posts
  end
end

Post.in_category(Category.first)

A: def self.in_category(category_id)
    category_id.blank? ? all : joins(:category_id).where(:categories_posts => {category_id: category_id})
end

This approach has some benefits

*

*You can call Post.in_category(id) and get specific posts in that
category as you asked.

*Post.in_category(nil) will return all posts, this is helpful if you want to concatenate this scope with other scopes.

*Post.in_category([id1, id2]) will return posts in both categories, id 1 and id2 (in this case it might be nice to rename the scope as in_categories)


text:
Q: Slow query on counting items I have a list with filters and I have to count how many items are in each one filter, but the following query gets slower and much slower when multiple filters are set
SELECT COUNT(*) FROM (
    SELECT itf.`filter_id`
    FROM `item_to_filter` AS `itf`
    JOIN `item_to_inventory` AS `iti` ON (itf.`item_id` = iti.`item_id` AND iti.`quantity` > 0)
    WHERE 1 = 1
    AND (
        (itf.`filter_group_id` = 2 AND itf.`filter_id` IN (1))
        OR (itf.`filter_group_id` = 4 AND itf.`filter_id` IN (55)) //gets slower
        OR (itf.`filter_group_id` = 1 AND itf.`filter_id` IN (107, 108)) //gets much slower
    )
    GROUP BY itf.`item_id`
    HAVING COUNT(DISTINCT itf.`filter_group_id`) = 3
) AS `total_items`

Is there any other way to write the query to count items from each filter
Here you can see the tables structure and data (are the indexes correctly sets?)

A: Try this one: Wrap the conditions into a UNION ALL subquery. Then join it with your tables.
SELECT COUNT(*) FROM (
    SELECT itf.filter_id
    FROM (
        SELECT 2 as filter_group_id 1   as filter_id UNION ALL
        SELECT 4 as filter_group_id 55  as filter_id UNION ALL
        SELECT 1 as filter_group_id 107 as filter_id UNION ALL
        SELECT 1 as filter_group_id 108 as filter_id
    ) f -- filters
    JOIN item_to_filter AS itf USING(filter_group_id, filter_id)
    JOIN item_to_inventory AS iti ON itf.item_id = iti.item_id
    WHERE iti.quantity > 0
    GROUP BY itf.item_id
    HAVING COUNT(DISTINCT itf.filter_group_id) = 3
) AS total_items

You should define an index on item_to_filter(filter_group_id, filter_id). But as I wrote in the comment, it's possible that the engine can do the same optimization if that index is present.
To make a better use of the given indexes you could rewrite your query to
SELECT COUNT(*) FROM (
    SELECT item_id
    FROM item_to_inventory AS iti
    JOIN item_to_filter AS itf2 USING(item_id) -- itf2: group_id = 2
    JOIN item_to_filter AS itf4 USING(item_id) -- itf4: group_id = 4
    JOIN item_to_filter AS itf1 USING(item_id) -- itf1: group_id = 1
    WHERE iti.quantity > 0
      AND itf2.filter_group_id = 2 AND itf2.filter_id IN (1)
      AND itf4.filter_group_id = 4 AND itf4.filter_id IN (55)
      AND itf1.filter_group_id = 1 AND itf1.filter_id IN (107,108)
) AS total_items

But even here an index on item_to_filter(filter_group_id, filter_id) should improve the performance.


text:
Q: Android Studio 1.3.1 windows7 emulator x64 download I have Android Studio 1.3.1 on windows 7 x64.   I notice all the emulators are running on x86.  I can not get the emulator to run.  Can someone help me solve this problem or help me find a download, x64 emulator for Android Studio 1.3.1 on windows 7 x64?
I am new to the app game. So please dumb down your answers!  Great community thanks all for your help!


text:
Q: Open Office org Calc (spreadsheet): limit of 64k rows? I was using a not-so-up-to-date version of OOo.calc (Open Office Spreasheet component, version 2.04, default for RHEL 5), and bumped into a nasty surprise. When trying to import a csv file (with about 100k row), it said that there is a limitation of max 64k rows, and that remaining rows would just be discarded.
I was planning to have users use OOo for client-side processing of large sample sets, to be uploaded to server for processing (and possibly returning results as a spreadsheet), but such a limitation would effectively kill that approach.
Does anyone know if a later versions might have lifted this limit? If not, I will need to consider alternative spreadsheet apps; so if anyone knows of good alternatives beyond Excel (which I am aware of :) ), feel free to share.
EDIT: after downloading and testing OOo 3.1, I found out that unfortunately this limit still exists in its original form.
OOo spreadsheets can not have more than 65536 rows, even with version 3.1

A: This article on the OpenOffice wiki says:

As of DEV300_m84 the number of rows was increased to 1048576 (1M).
Regard this article as historical...

So, maybe grab a dev version of OO.org and try it out?  The DEV300_m84 version number seems like it would be 3.0.0, but it's not working for me in 3.1 either.

A: No, this is a pretty common limit.  Excel 2007 was the first version of Excel to increase this limit to about 1 million.  Quattro Pro can handle about a million as well.
With what you're talking about, though, a database would be a better approach.

A: According to Wikipedia, the limit is still 64K rows.  In case you are leery of Wikipedia, that article does have a link to an OpenOffice.org FAQ, which (1) does corroborate the 64K figure, but (2) is marked as obsolete, and automatically redirects you to the general FAQ wiki.  Make of that what you will, but as tesseractor points out, Excel 2007 has a vastly higher limit.  (This of course does not help you if you must use RHEL.)

A: This is something I've encountered with folks in our marketing department who use Excel (pre-2007, clearly). One solution is to simply divide the CSVs into 64K or fewer line files. A CSV file is easily divided according to lines with a few bits of script. Then your end users can import the CSV files into different workbooks in each spreadsheet.
It might not catch all your use cases, but it's worked OK for us so far.

A: Download the last openoffice version from www.libreoffice.org,
this supports 1 millon++ rows with macro references to each cell,
and works very very well..
libreoffice is a nice fork from openoffice,
and supports the same platforms,
including Mac OS X, MS-Windows, Linux, etc..

A: As stated in http://wiki.openoffice.org/wiki/Documentation/FAQ/Calc/Miscellaneous/What's_the_maximum_number_of_rows_and_cells_for_a_spreadsheet_file%3f, the limit for rows in OpenOffice.org 3.x Calc is 65 536... :(


text:
Q: Should I create a parent page with no content? From an SEO perspective, should I ever have a blank parent page on my website?

A: Your question is a bit out of the scope of this site, but according to Google, creating any URL without content would not be beneficial for SEO. It would likely work better SEO-wise to create a custom post type that has no archive, so you have the parent slug you're wanting in the URL without actually having an accessible URL at that parent level.


text:
Q: how to clear form after submit in next js? here I have a contact form and i want all the values of form should be empty after submitting the form.
I have written following code.but this is not working after submitting the values of form remains same.
what is the problem here and how to solve it.
export default function contact() {

  const[name,setName]=useState("")
  const[phone,setPhone]=useState("")
  const[email,setEmail]=useState("")
  const[query,setQuery]=useState("")
  const [submitted, setSubmitted] = useState(false)

const  handleSubmit=(e)=>{
    e.preventDefault()
    console.log(e);
    let data = {
      name,
      email,
      phone,
      query
    }
    console.log(data);
    axios.post('http://127.0.0.1:8000/api/create/',data).then((res)=>{
      console.log(res);
      setSubmitted(true)
      setName('')
      setPhone('')
      setEmail('')
      setQuery('')
    })
  }
    return (
    <>

Contact Page

           <form action="contact" method="post">
              <input name="name"  onChange={(e)=>{setName(e.target.value)}} placeholder="Name" / >

              <input name="phone" onChange={(e)=>{setPhone(e.target.value)}} placeholder="Phone" />

              <input name="email" onChange={(e)=>{setEmail(e.target.value)}} type="email" placeholder="E-mail" / >

              <textarea name="text" onChange={(e)=>{setQuery(e.target.value)}} placeholder="How can we help you?" ></textarea>

              <button onClick={(e)=>{handleSubmit(e)}} value="Send" >Submit </button>
          </form>

    </>
    )
  }

A: Currently you are missing value prop in your inputs so your inputs are uncontrolled components that's why you are not able to clear them after form submit.
Try to add value prop like below:-
<input name="name" value={name} onChange={(e)=>{setName(e.target.value)}} placeholder="Name" / >

<input name="phone" value={phone} onChange={(e)=>{setPhone(e.target.value)}} placeholder="Phone" />

<input name="email" value={email} onChange={(e)=>{setEmail(e.target.value)}} type="email" placeholder="E-mail" / >

<textarea name="text" value={query} onChange={(e)=>{setQuery(e.target.value)}} placeholder="How can we help you?" ></textarea>

A: Add value prop your inputs then your form shall be cleared after submit:
<form>
    <input name="name" value={name} onChange={(e)=>{setName(e.target.value)}} placeholder="Name" / >

    <input name="phone" value={phone} onChange={(e)=>{setPhone(e.target.value)}} placeholder="Phone" />

    <input name="email" value={email} onChange={(e)=>{setEmail(e.target.value)}} type="email" placeholder="E-mail" / >

    <textarea name="text" value={query} onChange={(e)=>{setQuery(e.target.value)}} placeholder="How can we help you?" ></textarea>

</form>

A: First, make sure that your api-call ends successfully, according your code, you clean form only when request passed successfully :)

A: I think a better way to do this is to rest the form using the .reset() method.
Like this:
document.getElementById("postCodeForm").reset();


text:
Q: Dynamically assigned UIFont does not show immediately in slow simulator I have a UIView with a UILabel for which, I'd like allow the user to dynamically change the font size.  The code below almost works, but the problem is that after the new UIFont is assigned to the label, it doesn't immediately show in the UI.  Instead, some other UI activity is required to make it show up.
What I'm looking for is a technique where the font change will show up immediately after the gesture is over.
Starting with the technique shown in this tutorial, I added a gesture recognizer to the UIScrollView.  In the associated UIViewController, I implemented handlePinch(UIpinchGestureRecognizer).
Inside that function, I take action only when the gesture begins and ends (no attempt to animate).  If the user indicated zoom, I increase the font by 4 points.  If the user indicated a shrink, I decrease the font by 4 points.  This all works, except for the fact that the screen does not reflect the change until another UI function is executed.  I have only tested this on the simulator, but I presume it would be the same on a real device.
I have tried setNeedsDisplay and setNeedsLayout and several other odd things on both the UILabel as well as the view that was passed to the handlePinch() function.
@IBAction func handlePinch(_ gesture: UIPinchGestureRecognizer) {
  guard let gestureView = gesture.view else {
    return;
  }

  gestureView.transform = gestureView.transform.scaledBy(x: gesture.scale, y: gesture.scale)

  if (gesture.state == UIPinchGestureRecognizer.State.began) {
    pinchD = gestureView.transform.d
    print("pinch started ", pinchD)
  }

  if (gesture.state == UIPinchGestureRecognizer.State.ended) {
    print("pinch ended ", gestureView.transform.d)
    print("compare:", pinchD, gestureView.transform.d)
    let larger = gestureView.transform.d > pinchD
    let fontSize = multiLineLabel.font.pointSize
    if (larger) {
      if (fontSize < 28) {
        let calculatedFont = UIFont(name: multiLineLabel.font.fontName, size: fontSize + 4)
        print("bigger fontSize", fontSize + 4);
        multiLineLabel.font = calculatedFont
      }
    } else {
      if (fontSize > 12) {
        let calculatedFont = UIFont(name: multiLineLabel.font.fontName, size: fontSize - 4)
        print("smaller fontSize", fontSize - 4);
        multiLineLabel.font = calculatedFont
      }
    }
  }
}

What needs to be done after the calculatedFont is applied to the UILabel to make it show immediately in the app?
ADDITIONAL CLARIFICATION:
handlePinch() runs as expected; every time a pinch gesture ends, I see bigger fontSize... or smaller fontSize... logged.
After the logging, the simulator screen font size remains the same until I do one of several things.  One thing that causes the font size to change is if I swipe to the next item.  Before the animation starts, the font increases.  The font changes also if I hit the back button (the font change shows briefly before the other view appears).

A: It turns out that my presumption was incorrect:

I have only tested this on the simulator, but I presume it would be the same on a real device.

I believe that was NOT correct.
I'm testing on a very, very old iMac and the simulator is bogged down such that it takes 15 or 30 seconds to update the screen!
So I conclude that the code is working fine after all.


text:
Q: Meteor google map display markers depending on checkbox filter I have a map that currently displays all markers. I would like to update the markers on the map when a checkbox is clicked.
To load the markers I do
Caves.find({$or: [{ backmount: {$exists: false}},{backmount: true}]}).observe({

And if the checkbox is clicked it should change the filter to
Caves.find({ backmount: false}).observe({

I am not sure how to put that into my code.
This is the code to load the markers
Template.map.onCreated(function() {
  GoogleMaps.loadUtilityLibrary('js/geolocationmarker-compiled.js');
  GoogleMaps.loadUtilityLibrary('js/infobox.js');

  var markers = {};

  GoogleMaps.ready('map', function(map) {
    var latLng = currentPosition();

    Tracker.autorun(function() {
      map.instance.setCenter(new google.maps.LatLng(latLng.lat, latLng.lng));
      var GeoMarker = new GeolocationMarker(map.instance);

    });

    Caves.find({$or: [{ backmount: {$exists: false}},{backmount: true}]}).observe({
      added: function(doc) {
        var infobox = new InfoBox({
          content: $("#infobox")[0],
          disableAutoPan: false,
          pixelOffset: new google.maps.Size(-140,0),
          zIndex: null,
          infoBoxClearance: new google.maps.Size(1,1),
          boxStyle: {
            background: "url('images/tipbox.gif') no-repeat",
            opacity: 0.75,
            width: "280px"
          }
        });

        var marker = new google.maps.Marker({
          draggable: false,
          animation: google.maps.Animation.DROP,
          position: new google.maps.LatLng(doc.location.coordinates.latitude,doc.location.coordinates.longitude),
          id: doc._id,
          map: map.instance
        });

        marker.addListener('click', function() {
          infobox.open(map.instance, this);
        });

        markers[doc._id] = marker;
      },
      changed: function(newDoc, oldDoc) {
        markers[newDoc._id].setPosition({ lat: newDoc.lat, lng: newDoc.lng});
      },
      removed: function(oldDoc) {
        markers[oldDoc._id].setMap(null);

        google.maps.event.clearInstanceListeners(markers[oldDoc._id]);

        delete markers[oldDoc._id];
      }
    });

  });
});

And I have a template with the checkbox (#sidemountOnly)
<template name="mapFilters">

            <input type="checkbox" id="sidemountOnly" value="1">
            Sidemount Only

</template>

Thanks a lot for your help

A: I can answer my own question. I used a session variable where I change the subsription. Some of the related code:
Create an event:
Template.mapFilters.events({
  "change #sidemountOnly": function(event) {
    Session.set("sidemountOnly",event.target.checked);
  }
})

Pass to subscription inside autorun
Tracker.autorun(function() {
      getBox();
      Meteor.subscribe("primaryCoordinates", Session.get('box'), Session.get('sidemountOnly'));

      var GeoMarker = new GeolocationMarker(map.instance);

    });

Create filter in publish on the server side
Meteor.publish('primaryCoordinates', function(box,sidemountOnly) {
  var filter = {};

  if(sidemountOnly) {
    filter = {backmount: false};
  } else {
    filter = {$or: [{ backmount: {$exists: false}},{backmount: true}]};
  }

  var find = { $and: [{
    location: {
      $geoWithin: {
        $box: box
      }
    }},filter]
  };

  return Caves.find(find);
});


text:
Q: postfix - users are geting mail from them self that they did not send Our company has a mail server configured with postfix/dovecot/amavisd on Ubintu 14.04. The system has been running for a couple of years and it worked fine. Recently some users started complaining that they got some mail from themselves, that they did not send. The server is not an open relay.
I tried to enable authentification, but then no other mail could be recived.
My question is, if it is posible in any way to reject/deny mail that was not send from our users in our domain?
postfix main.cf:
# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = /usr/share/doc/postfix

# TLS parameters
smtpd_tls_cert_file = /etc/postfix/smtpd.cert
smtpd_tls_key_file = /etc/postfix/smtpd.key
smtpd_use_tls = yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = mail.mxserver.net
alias_maps = hash:/etc/aliases, hash:/var/lib/mailman/data/aliases
alias_database = hash:/etc/aliases, hash:/var/lib/mailman/data/aliases
myorigin = /etc/mailname
mydestination = mail.mxserver.net, localhost, localhost.localdomain
relayhost =
mynetworks = 127.0.0.0/8
mailbox_size_limit = 0
message_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
html_directory = /usr/share/doc/postfix/html
virtual_alias_domains =
virtual_alias_maps = proxy:mysql:/etc/postfix/mysql-virtual_forwardings.cf, proxy:mysql:/etc/postfix/mysql-virtual_email2email.cf, hash:/var/lib/mailman/data/virtual-mailman
virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domains.cf
virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailboxes.cf
virtual_mailbox_base = /var/vmail
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
inet_protocols = all
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_authenticated_header = yes
smtpd_reject_unlisted_sender = yes
smtpd_recipient_restrictions = check_recipient_access mysql:/etc/postfix/mysql-virtual_recipient.cf, permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_tls_security_level = may
transport_maps = hash:/var/lib/mailman/data/transport-mailman, proxy:mysql:/etc/postfix/mysql-virtual_transports.cf
relay_domains = mysql:/etc/postfix/mysql-virtual_relaydomains.cf
relay_recipient_maps = mysql:/etc/postfix/mysql-virtual_relayrecipientmaps.cf
proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks
#smtpd_sender_restrictions = check_sender_access mysql:/etc/postfix/mysql-virtual_sender.cf
smtpd_sender_restrictions = check_sender_access mysql:/etc/postfix/mysql-virtual_sender.cf, permit_sasl_authenticated, permit_mynetworks, reject_unlisted_sender, reject_unknown_sender_domain
smtpd_client_restrictions = check_client_access mysql:/etc/postfix/mysql-virtual_client.cf
smtpd_client_message_rate_limit = 100
maildrop_destination_concurrency_limit = 1
maildrop_destination_recipient_limit = 1
virtual_transport = dovecot
header_checks = regexp:/etc/postfix/header_checks
mime_header_checks = regexp:/etc/postfix/mime_header_checks
nested_header_checks = regexp:/etc/postfix/nested_header_checks
body_checks = regexp:/etc/postfix/body_checks
owner_request_special = no
smtp_tls_security_level = may
dovecot_destination_recipient_limit = 1
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
content_filter = amavis:[127.0.0.1]:10024
receive_override_options = no_address_mappings

# DKIM
# --------------------------------------
milter_default_action = accept
milter_protocol = 2
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891

Postfix master.cf:
#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       -       -       -       smtpd
#smtp      inet  n       -       -       -       1       postscreen
#smtpd     pass  -       -       -       -       -       smtpd
#dnsblog   unix  -       -       -       -       0       dnsblog
#tlsproxy  unix  -       -       -       -       0       tlsproxy
submission inet n       -       -       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       -       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o syslog_name=postfix/smtps
#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       -       -       -       qmqpd
pickup    unix  n       -       -       60      1       pickup
cleanup   unix  n       -       -       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       -       1000?   1       tlsmgr
rewrite   unix  -       -       -       -       -       trivial-rewrite
bounce    unix  -       -       -       -       0       bounce
defer     unix  -       -       -       -       0       bounce
trace     unix  -       -       -       -       0       bounce
verify    unix  -       -       -       -       1       verify
flush     unix  n       -       -       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       -       -       -       smtp
relay     unix  -       -       -       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       -       -       -       showq
error     unix  -       -       -       -       -       error
retry     unix  -       -       -       -       -       error
discard   unix  -       -       -       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       -       -       -       lmtp
anvil     unix  -       -       -       -       1       anvil
scache    unix  -       -       -       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d vmail ${extension} ${recipient} ${user} ${nexthop} ${sender}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -       n       n       -       2       pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}

dovecot   unix  -       n       n       -       -       pipe
  flags=DROhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}
amavis unix - - - - 2 smtp
        -o smtp_data_done_timeout=1200
        -o smtp_send_xforward_command=yes

127.0.0.1:10025 inet n - - - - smtpd
        -o content_filter=
        -o local_recipient_maps=
        -o relay_recipient_maps=
        -o smtpd_restriction_classes=
        -o smtpd_client_restrictions=
        -o smtpd_helo_restrictions=
        -o smtpd_sender_restrictions=
        -o smtpd_recipient_restrictions=permit_mynetworks,reject
        -o mynetworks=127.0.0.0/8
        -o strict_rfc821_envelopes=yes
        -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks,no_milters

A: Add an spf record for your domain at DNS level. You can create your spf record from online spf wizards. It is a txt record and should look like this
example.com.  IN TXT "v=spf1 mx a -all"

Then configure your server to check spf.
https://help.ubuntu.com/community/Postfix/SPF

A: You can use smtpd_restriction_classes
# /etc/postfix/main.cf
smtpd_restriction_classes = restricted_sender
restricted_sender = permit_mynetworks, permit_sasl_authenticated, reject

smtpd_sender_restrictions =
 check_sender_access hash:/etc/postfix/restricted_domain
 reject_non_fqdn_sender

Add all you domains to the list
# cat /etc/postfix/restricted_domain
example.com restricted_sender
example.net restricted_sender

# postmap /etc/postfix/restricted_domain

# postconf mynetworks
mynetworks = 127.0.0.0/8

Some basic tests
Sender within mynetworks. No authentication - Access granted
# echo "Hello world" | swaks -4 --server localhost --from alex@example.net --to alex@example.net --h-Subject "Test message" --body -
=== Trying localhost:25...
=== Connected to localhost.
<-  220 smtp.example.net ESMTP Postfix
 -> EHLO jenkins.example.net
<-  250-smtp.example.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> MAIL FROM:<alex@example.net>
<-  250 2.1.0 Ok
 -> RCPT TO:<alex@example.net>
<-  250 2.1.5 Ok
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Fri, 25 Mar 2016 10:12:47 +0000
 -> To: alex@example.net
 -> From: alex@example.net
 -> Subject: Test message
 -> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 ->
 -> Hello world
 ->
 ->
 -> .
<-  250 2.0.0 Ok: queued as 327251C1566
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.

Sender outside mynetworks. No authentication - Access denied
# echo "Hello world" | swaks -4 --server smtp.example.net --from alex@example.net --to alex@example.net --h-Subject "Test message" --body -
=== Trying 192.168.88.87:25...
=== Connected to 192.168.88.87.
<-  220 smtp.example.net ESMTP Postfix
 -> EHLO tl-resin-node1.example.net
<-  250-smtp.example.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> MAIL FROM:<alex@example.net>
<-  250 2.1.0 Ok
 -> RCPT TO:<alex@example.net>
<** 554 5.7.1 <alex@example.net>: Sender address rejected: Access denied
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.

Sender outside mynetworks. With authentication - Access granted
# echo "Hello world" | swaks -4 --server smtp.example.net --auth PLAIN --auth-user alex@example.net --auth-password 1234567 --from alex@example.net --to alex@example.net --h-Subject "Test message" --body -
=== Trying 192.168.88.87:25...
=== Connected to 192.168.88.87.
<-  220 smtp.example.net ESMTP Postfix
 -> EHLO tl-resin-node1.example.net
<-  250-smtp.example.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-AUTH LOGIN PLAIN
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> AUTH PLAIN [HASH]
<-  235 2.7.0 Authentication successful
 -> MAIL FROM:<alex@example.net>
<-  250 2.1.0 Ok
 -> RCPT TO:<alex@example.net>
<-  250 2.1.5 Ok
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Fri, 25 Mar 2016 06:20:10 -0400
 -> To: alex@example.net
 -> From: alex@example.net
 -> Subject: Test message
 -> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 ->
 -> Hello world
 ->
 ->
 -> .
<-  250 2.0.0 Ok: queued as D04581C7EAD
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.


text:
Q: ClearCase : How Can I Revert to Earlier baseline? How Can I Revert to Earlier baseline? We have a UCM parallel development(multi-stream) project. Each developer have a snapshot view on Project's Integration stream.
Developers want to see earlier version of the application in their snapshot views so They can debug early version of application to find bugs.
When I want to change an existing snapshot views's foundition baselines, clearcase does not allow me. So How Can I do this?

A: Since you employ the term Baseline, I will assume you are using UCM.
On a stream, you can not revert backward a baseline.
One possibility is to make a parallel stream, with the desired baseline as foundation: this is the quickest way.

After changes on this new stream, you can make a new rebase to change the foundation baseline, but only if that new rebase is using a more recent baseline from the parent stream (not an older baseline)

For your specific need, I would recommand a non-UCM snapshot view with a simple rule
element * thePreviousBaseline

In order for the developer to have:

*

*his/her current UCM view for development (always set on the LATEST of a branch associated to a stream)

*a second snasphot view set to whatever baseline he/she needs.

That second snapshot view is completely not-related to the UCM project and takes advantage of the "full" nature of the baseline (do check that your baseline has been put as "full", not "incremental". If it is "incremental", simply change its type and upgrade it to full)
So, beside your current snapshot UCM view, you can create anywhere you want a non-snasphot view:
cleartool mkview -snap -tag mylogin_myComponentname_csl_snap -vws myPathToViewStorage myPathToRootView
cd myPathToRootView
cleartool edcs
[add the selection rule: element * myOlderBaseline]
[add the load rule at the end: 'load /myVob_Including_MyComponent]
[save, type 'yes']

That is fine for consultation/execution, but if you need to patch (that i is to write, check out and in some files), then I would recommend one UCM stream per baseline to be patched.
That way, the stream clearly represents the patch effort for a given baseline. There should not be too many of them, unless you put into production a new version of your application every five minutes... which is not advisable ;)

So to summarize:

*

*the non-UCM snapshot view is unique and serve for a quick consultation/debug of one older baseline at a time.

*for patches (source modification), you create a parallel stream properly named, with the correct foundation baseline, and then a UCM view on it. You can not only debug but also fix some bugs in an activity, the deliver that activity to the main Int stream if that bug need to be retro-fitted on an higher stream.
(note: all bugs do not always need to be delivered: they can be obsolete when compared with the current state of the development)

A: The way I have solved this problem is by making another Stream, a child Stream of the Integration Stream.  The easiest way to create this Stream is to open ClearCase Project Explorer (not Rational ClearCase Explorer) and navigate to the Project and then the Stream in question.  Right click on the Integration Stream and select "Create Child Stream..."
Click "Advanced Options" and select a baseline for each component.  Do this by selecting the component and then selecting "Change..." and selecting the specific baseline you want to see.  You probably want to select "Prompt me to create a View for this Stream."  Select "OK".
Any developer can do this.  You don't need to be a VOB owner or Project or Stream owner.

A: Well, it depends.  Actually, the answer lies in setting up your config spec to point to the proper files.  Your config spec tells your view which versions of elements to look at.  But how you do write it depends on your project's approach to baselines.  Did you apply a label to mark that baseline?  If so, and if you only want to read and not checkout anything new, your config spec can be as simple as
element * <LABELNAME>

If you didn't use labels, you can also set up your config spec to show you files based on dates.  It gets more complicated the more rules you need to add to constrain your element choices.  If you have more specifics, I can try to elaborate on what rules you might need.  Otherwise, I would read the manuals that come with ClearCase.  If you view the Extended Help from ClearCase Explorer, and then do "Viewing Rational ClearCase Manuals On-Line" it should give you some links to the Command References.  This is where I go whenever I need to modify my config spec in some new way.
Also, note that we only use dynamic views, so I don't know if snapshot views work differently.


text:
Q: C++ Passing Options To Executable How do you pass options to an executable?  Is there an easier way than making the options boolean arguments?
EDIT:  The last two answers have suggested using arguments.  I know I can code a workable solution like that, but I'd rather have them be options.
EDIT2: Per requests for clarification, I'll use this simple example:
It's fairly easy to handle arguments because they automatically get parsed into an array.
./printfile file.txt 1000

If I want to know what the name of the file the user wants to print, I access it via argv[1].
Now about how this situation:
./printfile file.txt 1000 --nolinebreaks

The user wants to print the file with no line breaks.  This is not required for the program to be able to run (as the filename and number of lines to print are), but the user has the option of using if if s/he would like.  Now I could do this using:
./printfile file.txt 1000 true

The usage prompt would inform the user that the third argument is used to determine whether to print the file with line breaks or not.  However, this seems rather clumsy.

A: You seem to think that there is some fundamental difference between "options" that start with "--" and "arguments" that don't. The only difference is in how you parse them.
It might be worth your time to look at GNU's getopt()/getopt_long() option parser. It supports passing arguments with options such as --number-of-line-breaks 47.

A: I use two methods for passing information:
1/ The use of command line arguments, which are made easier to handle with specific libraries such as getargs.
2/ As environment variables, using getenv.

A: Command-line arguments is the way to go.  You may want to consider using Boost.ProgramOptions to simplify this task.

A: Pax has the right idea here.
If you need more thorough two-way communication, open the process with pipes and send stuff to stdin/listen on stdout.

A: You can also use Window's PostMessage() function. This is very handy if the executable you want to send the options to is already running. I can post some example code if you are interested in this technique.

A: The question isn't blazingly clear as to the context and just what you are trying to do - you mean running an executable from within a C++ program?    There are several standard C library functions with names like execl(), execv(), execve(),  ... that take the options as strings or pointer to an array of strings.   There's also system() which takes a string containing whatever you'd be typing at a bash prompt, options and all.

A: I like the popt library.  It is C, but works fine from C++ as well.
It doesn't appear to be cross-platform though.  I found that out when I had to hack out my own API-compatible version of it for a Windows port of some Linux software.

A: You can put options in a .ini file and use the GetPrivateProfileXXX API's to create a class that can read the type of program options you're looking for from the .ini.
You can also create an interactive shell for your app to change certain settings real-time.
EDIT:
From your edits, can't you just parse each option looking for special keywords associated with that option that are "optional"?


text:
Q: How to fetch only parts of json file in python3 requests module So, I am writing a program in Python to fetch data from google classroom API using requests module. I am getting the full json response from the classroom as follows :
{'announcements': [{'courseId': '#############', 'id': '###########', 'text': 'This is a test','state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/##########/p/###########', 'creationTime': '2021-04-11T10:25:54.135Z', 'updateTime': '2021-04-11T10:25:53.029Z', 'creatorUserId': '###############'}, {'courseId': '############', 'id': '#############', 'text': 'Hello everyone', 'state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/#############/p/##################', 'creationTime': '2021-04-11T10:24:30.952Z', 'updateTime': '2021-04-11T10:24:48.880Z', 'creatorUserId': '##############'}, {'courseId': '##################', 'id': '############', 'text': 'Hello everyone', 'state': 'PUBLISHED', 'alternateLink': 'https://classroom.google.com/c/##############/p/################', 'creationTime': '2021-04-11T10:23:42.977Z', 'updateTime': '2021-04-11T10:23:42.920Z', 'creatorUserId': '##############'}]}

I was actually unable to convert this into a pretty format so just pasting it as I got it from the http request. What I actually wish to do is just request the first few announcements (say 1, 2, 3 whatever depending upon the requirement) from the service while what I'm getting are all the announcements (as in the sample 3 announcements) that had been made ever since the classroom was created. Now, I believe that fetching all the announcements might make the program slower and so I would prefer if I could get only the required ones. Is there any way to do this by passing some arguments or anything? There are a few direct functions provided by google classroom however I came across those a little later and have already written everything using the requests module which would require changing a lot of things which I would like to avoid. However if unavoidable I would go that route as well.

A: Answer:
Use the pageSize field to limit the number of responses you want in the announcements: list request, with an orderBy parameter of updateTime asc.
More Information:
As per the documentation:

orderBy: string
Optional sort ordering for results. A comma-separated list of fields with an optional sort direction keyword. Supported field is updateTime. Supported direction keywords are asc and desc. If not specified, updateTime desc is the default behavior. Examples: updateTime asc, updateTime

and:

pageSize: integer
Maximum number of items to return. Zero or unspecified indicates that the server may assign a maximum.

So, let's say you want the first 3 announcements for a course, you would use a pageSize of 3, and an orderBy of updateTime asc:
# Copyright 2021 Google LLC.
# SPDX-License-Identifier: Apache-2.0

service = build('classroom', 'v1', credentials=creds)

asc = "updateTime asc"
pageSize = 3

# Call the Classroom API
results = service.courses().announcements().list(pageSize=3, orderBy=asc ).execute()

or an HTTP request example:
GET https://classroom.googleapis.com/v1/courses/[COURSE_ID]/announcements
      ?orderBy=updateTime%20asc
      &pageSize=2
      &key=[YOUR_API_KEY] HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json

References:

*

*Method: announcements.list | Classroom API | Google Developers


text:
Q: Hide Column in Material UI Data Grid Filter I have successfully hidden the id in the columns. But how do I also hide it in the filter?
<StyledDataGrid
  getRowId={(r) => r.newId}
  columns={columns}
  rows={rows}
  disableSelectionOnClick
  checkboxSelection
/>;

const columns = [
  { field: "id", hide: true, filterable: false },
  {
    field: "product",
    headerName: "Product Name",
  },
  { field: "price", headerName: "Price" },
  {
    field: "expiry",
    headerName: "Expiry date",
  },
];

A: You could apply a filter when you provide the columns to <StyledDataGrid />.
colums={ columns.filter((col) => !col.hide) }


text:
Q: CSS rotate and translate transform give unexpected results I've checked CSS-TRICKS and any other site Google offered me up to page two of their list of links, so my only assumption is I'm misunderstanding how this works or doing it wrong.
What I want is for an image to slide in from its current position to the absolute center of the page. As it slides, I want it to rotate at its center, spinning like a perfectly-balanced wheel. As it slides and rotates, I want it to appear to come towards the user. I want to do this while still keeping the image flat and unskewed.
What it does instead is rotate the image clockwise around and down back towards the left side of the page and off of it.
Here's my code (borrowed from animate.css and changed to suit my needs):
    @-webkit-keyframes rotOutZm {
    0% {
    -webkit-transform-origin: center;
    transform-origin: center;
    opacity: 1;
    }

    100% {
    -webkit-transform-origin: center;
    transform-origin: center;
    -webkit-transform: rotate3d(0, 0, 1, 90deg) scale3d(3, 3, 3) translate3d(100% ,100% ,0);
    transform: rotate3d(0, 0, 1, 90deg) scale3d(3, 3, 3) translate3d(100% ,100% ,0);
    opacity: 0;
    }
    }

    @keyframes rotOutZm {
    0% {
    -webkit-transform-origin: center;
    transform-origin: center;
    opacity: 1;
    }

    100% {
    -webkit-transform-origin: center;
    transform-origin: center;
    -webkit-transform: rotate3d(0, 0, 1, 90deg) scale3d(3, 3, 3) translate3d(100% ,100% ,0);
    transform: rotate3d(0, 0, 1, 90deg) scale3d(3, 3, 3) translate3d(100% ,100% ,0);
    opacity: 0;
    }
    }

    .rotOutZm {
    -webkit-animation-name: rotOutZm;
    animation-name: rotOutZm;
    -webkit-animation-duration: 2s;
    animation-duration: 2s;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    }

Currently, my code does not take into account the starting point of the image, which will be wrong/messy when I have a row of images. Is there a way to dynamically figure from their starting locations, if they need to slide up to the center, slide down to the center, etc? I'm pretty sure this is a job for JavaScript or jQuery but I'm not sure how to code that.
Am I simply expecting too much of the animation functions? Should I simplify my design to not do this due to complexity?
EDIT: Here is a JSFiddle showing the code in action. It's an image with a small delay to the animation so you can see the image and then watch how it animates to see my problem. My apologies for not providing this sooner.
JSFiddle

A: Sure you can do it:
FireFox Live example
@keyframes rotOutZm {
  100% {
    margin: -50px; /* image is 100x100px size so... */
    transform: translate3d(50vw, 50vh, 0) scale(3) rotate(360deg);
    opacity: 0;
  }
}

.rotOutZm {
  transform-origin: center;
  animation: rotOutZm 2s forwards 0.5s;
}

P.S: Expand the above also for -webkit- and other vendor prefixes
vw and vh are the Viewport sizes. 50vh is half the viewport height
Note that is extremly important the order you place your stack of transform, i.e: if you move translate3d to the end or the transform rule you might get unwanted results.


text:
Q: Get type from GUID For various reasons, I need to implement a type caching mechanism in C#. Fortunately, the CLR provides Type.GUID to uniquely identify a type. Unfortunately, I can't find any way to look up a type based on this GUID. There's Type.GetTypeFromCLSID() but based on my understanding of the documentation (and experiments) that does something very, very different.
Is there any way to get a type based on its GUID short of looping through all the loaded types and comparing to their GUIDs?
EDIT: I forgot to mention that I would really like a "type fingerprint" of fixed width, that's why the GUID is so appealing to me. In a general case, of course, the fully qualified name of the type would work.

A: why not use the designated property for that, ie. AssemblyQualifiedName? This property is documented as "can be persisted and later used to load the Type".
The GUID is for COM interop.

A: This may just be a summary of answers already posted, but I don't think there is a way to do this without first building a map of Guid->Type.
We do this in our framework on initialization:
static TypeManager()
    {
        AppDomain.CurrentDomain.AssemblyLoad += (s, e) =>
        {
            _ScanAssembly(e.LoadedAssembly);
        };

        foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
        {
            _ScanAssembly(a);
        }
    }

    private static void _ScanAssembly(Assembly a)
    {
        foreach (Type t in a.GetTypes())
        {
           //optional check to filter types (by interface or attribute, etc.)
           //Add type to type map
        }
    }

Handling the AssemblyLoad event takes care of dynamically loaded assemblies.
From what I understand, Type.GUID uses the assembly version of the type as part of the Guid generation algorithm.  This may lead to trouble if you increment your assembly version numbers.  Using the GetDeterministicGuid method described in another answer would probably be advisable, depending on your application.

A: Don't loop to compare. Populate a Dictionary<Type> and use the Contains method.
Dictionary<Type> types = new Dictionary<Types>();
... //populate

if (types.Contains(someObject.GetType()))
  //do something

This will certainly give you a fixed size entry, since all of them will be object references (instances of Type essentially being factory objects).

A: What about (from Generating Deterministic GUIDs):
private Guid GetDeterministicGuid(string input)
{
    // use MD5 hash to get a 16-byte hash of the string:
    MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
    byte[] inputBytes = Encoding.Default.GetBytes(input);
    byte[] hashBytes = provider.ComputeHash(inputBytes);

    // generate a guid from the hash:
    Guid hashGuid = new Guid(hashBytes);
    return hashGuid;
}

And throw in that typeof().AssemblyQualifiedName. You could to store this data inside a Dictionary<string, Guid> collection (or, whatever, a <Guid, string>).
This way you'll have always a same GUID for a given type (warning: collision is possible).

A: If you are in control of these classes I would recommend:
public interface ICachable
{
    Guid ClassId { get; }
}

public class Person : ICachable
{
    public Guid ClassId
    {
        get {  return new Guid("DF9DD4A9-1396-4ddb-98D4-F8F143692C45"); }
    }
}

You can generate your GUIDs using Visual Studio, Tools->Create Guid.

A: The Mono documentation reports that a module has a Metadata heap of guids.
Perhaps Cecil might help you lookup a type based on its guid?  Not sure though, there is a GuidHeap class, it seems to be generating the guids though, but perhaps this is enough for your cache to work?

A: I would use the  typeof (class).GUID to find the instance in the cache dictionary:
private Dictionary<Guid, class> cacheDictionary { get; set; }

and I would have a method to return the dictionary and the GUID as parameter of the method to search for the class in the dictionary.
public T Getclass<T>()
    {
        var key = typeof(T).GUID;
        var foundClass= cacheDictionary.FirstOrDefault(x => x.Key == key);
        T item;
        if (foundClass.Equals(default(KeyValuePair<Guid, T>)))
        {
            item = new T()
            cacheDictionary.Add(key, item);
        }
        else
            item = result.Value;

        return item;
    }

and I would use a singleton pattern for the cache,
and the call would be something like the code below:
   var cachedObject = Cache.Instance.Getclass<class>();


text:
Q: API to Create and Delete a Relationship Object In our sandbox, we have created Student, Role, and StudentRoleRelationship objects. Currently, we have a Drupal project that has its own Student and Role objects, therefore in Student and Role we have a drupalId field for referencing the object in Drupal.
I am attempting to create an API (apex class) that creates and deletes a StudentRoleRelationship. When I do this, I will request the student's and role's DrupalId, look up the respected objects based off that DrupalId, and then create a StudentRoleRelationship based on those values.
Here is what my code looks like so far:
@RestResource(urlMapping='/Student/Roles/')
global class api_YTPStudentRolesController {

    @HttpPost
    global static void addRole() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;

        try {

            // Get Request Params
            Decimal roleDrupalId = Decimal.valueOf(req.params.get('role_id'));
            Decimal studentDrupalId = Decimal.valueOf(req.params.get('student_id'));

            // Query for role and student
            Role__c role = [SELECT Id FROM Role__c WHERE drupalId__c = :roleDrupalId];
            Student__c student = [SELECT Id FROM Student__c WHERE drupalId__c = :studentDrupalId];

            // Create the new StudentRoleRelationship
            StudentRoleRelationship__c studentRoleRelationship = new StudentRoleRelationship__c();
            studentRoleRelationship.Role__c = role.Id;
            studentRoleRelationship.Student__c = student.Id;
            insert studentRoleRelationship;

            res.responseBody = Blob.valueOf(JSON.serialize(studentRoleRelationship));
            res.statusCode = 200;

        } catch (Exception e) {
            res.responseBody = Blob.valueOf(e.getMessage());
            res.statusCode = 500;
        }
    }

    @HttpDelete
    global static String deleteRole() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;

        try {
            // Get Request Params
            Decimal roleDrupalId = Decimal.valueOf(req.params.get('role_id'));
            Decimal studentDrupalId = Decimal.valueOf(req.params.get('student_id'));

            // Query for role and student
            Role__c role = [SELECT Id FROM Role__c WHERE drupalId__c = :roleDrupalId];
            Student__c student = [SELECT Id FROM Student__c WHERE drupalId__c = :studentDrupalId];

            // Delete StudentRoleRelationship
            StudentRoleRelationship__c studentRoleRelationship = [SELECT Id FROM StudentRoleRelationship__c WHERE Role__c = :role.Id AND Student__c = :student.Id];
            delete studentRoleRelationship;

            // Add Response
            res.responseBody = Blob.valueOf(JSON.serialize(studentRoleRelationship));
            res.statusCode = 200;

        } catch (Exception e) {
            // Error
            res.responseBody = Blob.valueOf(e.getMessage());
            res.statusCode = 500;
        }
    }
}

As a newbie to Salesforce, I am curious of a couple of things:

*

*Is this the best practice on how to do what I am attempting to do (i.e. am I handling responses correctly, errors handled properly, etc.)

*How can I handle different error types? I would prefer to send back more than just a 500 error. For instance if there is no role_id in the request params or there is no 'studentfound with the givenstudent_id, I should be sending a4xx error` instead. How would you handle this?

A: You already have what you need to return custom errors.
Basically, you just need to add a few if statements:
global static void addRole() {
    RestRequest req = RestContext.request;
    RestResponse res = RestContext.response;

    try {

        // Get Request Params
        Decimal roleDrupalId = Decimal.valueOf(req.params.get('role_id'));
        Decimal studentDrupalId = Decimal.valueOf(req.params.get('student_id'));

        if (roleDrupalId == null || roleDrupalId == '') {
            res.responseBody = Blob.valueOf('No Drupal Role Id provided');
            res.statusCode = 4xx; // What ever error code you want to send
            return;
        }

        if (studentDrupalId == null || studentDrupalId == '') {
            res.responseBody = Blob.valueOf('No student Drupal Id provided');
            res.statusCode = 4xx; // What ever error code you want to send
            return;
        }

        // Query for role and student
        Role__c role = [SELECT Id FROM Role__c WHERE drupalId__c = :roleDrupalId];
        Student__c student = [SELECT Id FROM Student__c WHERE drupalId__c = :studentDrupalId];

        if (role == null) {
            res.responseBody = Blob.valueOf('No Role Found with given id ' + studentDrupalId);
            res.statusCode = 4xx; // What ever error code you want to send
            return;
        }

        if (student == null) {
            res.responseBody = Blob.valueOf('No Student Found with given id ' + studentDrupalId);
            res.statusCode = 4xx; // What ever error code you want to send
            return;
        }

        // ... The rest of your code (truncated)
    } catch (Exception e) {
        res.responseBody = Blob.valueOf(e.getMessage());
        res.statusCode = 500;
    }
}

Also,
Role__c role = [SELECT Id FROM Role__c WHERE drupalId__c = :roleDrupalId];
Student__c student = [SELECT Id FROM Student__c WHERE drupalId__c = :studentDrupalId];

These two lines are likely to cause you errors. Instead try:
List<Role__c> roles = [SELECT Id FROM Role__c WHERE drupalId__c = :roleDrupalId];

if (roles.isEmpty()) {
    res.responseBody = Blob.valueOf('No Role Found with given Id: ' + roleDrupalId);
    res.statusCode = 404;
}

Lastly, I generally advice that if you have full control on both sides, you want to design a bulkified api that can handle more than 1 request at a time and send your requests in bulk. So instead of taking in 1 id, it should take in a map of roles to student ids and an operation type or something.

A: You can try to check the size of the results and throw a custom exception and handle that custom exception to throw 4xx error
 @HttpDelete
 global static String deleteRole() {
     RestRequest req = RestContext.request;
     RestResponse res = RestContext.response;

     try {

         string roleDrupalIdString = req.params.get('role_id');
         string studentDrupalIdString = req.params.get('student_id');

         if (string.isblank(roleDrupalIdString)) {
             throw new RecordNotFoundException('Drupal RoleId is blank or not provided');
         }

         if (string.isblank(studentDrupalIdString)) {
             throw new RecordNotFoundException('Drupal StudentId is blank or not provided');

         }
         // Get Request Params
         Decimal roleDrupalId = Decimal.valueOf(roleDrupalIdString);
         Decimal studentDrupalId = Decimal.valueOf(studentDrupalIdString);

         // Query for role and student

         List<Role__c> roleList = [SELECT Id FROM Role__c WHERE drupalId__c =: roleDrupalId];
         List<Student__c> studentList = [SELECT Id FROM Student__c WHERE drupalId__c =: studentDrupalId];

         if (roleList.size() == 0) {
             throw new RecordNotFoundException('Role not found');
         }

         if (StudentList.size() == 0) {
             throw new RecordNotFoundException('Studentnot found');
         }

         // Delete StudentRoleRelationship
         StudentRoleRelationship__c studentRoleRelationship = [SELECT Id FROM StudentRoleRelationship__c WHERE Role__c =: role.Id AND Student__c =: student.Id];
         delete studentRoleRelationship;

         // Add Response
         res.responseBody = Blob.valueOf(JSON.serialize(studentRoleRelationship));
         res.statusCode = 200;

     } catch (RecordNotFoundException e) {
         // Error
         res.responseBody = Blob.valueOf(e.getMessage());
         res.statusCode = 400;
     } catch (Exception e) {
         // Error
         res.responseBody = Blob.valueOf(e.getMessage());
         res.statusCode = 500;
     }
 }

 public class RecordNotFoundException extends Exception {}


text:
Q: ListView Xamarin.forms dynamically load image from ItemSource with ImageResource I have an issue in my xamarin.Forms application in MVVM. I have a ListView and I want to show an image in the ItemTemplate. To do that I have created a ImageRessource Class:
[ContentProperty("Source")]
public class ImageResourceExtension : IMarkupExtension
{
    public string Source { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Source == null)
        {
            return null;
        }

        var imageSource = ImageSource.FromResource($"CoPro.Assets.{Source}");

        return imageSource;
    }
}

Here is the xaml of my ListView:
 <ListView  ItemsSource="{Binding Series}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="20"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>
                                <StackLayout Orientation="Horizontal">
                                    <Image Source="{images:ImageResource image.jpg}"/>
                                </StackLayout>
                                <Label Grid.Column="1" Text="{Binding Name}" Style="{StaticResource UsualLabelTemplate}" />
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

Besides, I have set "images" by this namespace :xmlns:images="clr-namespace:CoPro.Assets"
Like this, my ListView show the same picture for every "Series" Item.
For each Item there is a string property with the path of the image.
How can I show image of each Item, please?
Thanks in advance for your help.

A: I have just found the solution. I had to use Source property from Image tag:
<ListView Grid.Row="1" x:Name="MainListView"  ItemsSource="{Binding Series}">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <ViewCell.View>
                                    <Grid>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="60"/>
                                            <ColumnDefinition Width="*"/>
                                        </Grid.ColumnDefinitions>
                                        <Image Source="{Binding ImageUrl, Converter={StaticResource StringToImageSourceConverter}}"
                                               Aspect="AspectFill"
                                              />
                                        <Label Grid.Column="1" Text="{Binding Name}" Style="{StaticResource UsualLabelTemplate}" />
                                    </Grid>
                                </ViewCell.View>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

The solution was to use a Converter, and Source property contained a string. This string is sent into parameter in my converter like this:
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
        {
            return ImageSource.FromResource($"CoPro.Assets.{value}");
        }
        else
        {
            return null;
        }
    }

in this code "$"CoPro.Assets" is the path where is my image File.
Thanks for your help