text:
Q: Cannot access Eloquent attributes on Twig I am trying to access an Eloquent attribute with Twig in Slim, and getting an error.
I have a Field and a Type object, and the relationship is as follows
class Field extends \Illuminate\Database\Eloquent\Model {

protected $table = 'fields';

public function type()
{
    return $this->belongsTo('models\Type');
}

When doing {{ f }} (being f a field), the output is this:
{"field_id":"1","field_name":"Your name","form_id":"2","type_id":"1","placeholder":"Please give us your name"}

And when doing {{ f.type }}, the result is:

Message: An exception has been thrown during the rendering of a template ("Object of class Illuminate\Database\Eloquent\Relations\BelongsTo could not be converted to string") in "pages/editform.html" at line 97.

If I try to do {{ f.type.name }}, doesn't throw up an exception but doesn't print anything either.
If I do it in PHP
    $fields = $form->fields;
    var_dump($fields[0]->type->name);

The value gets output correctly.
Any ideas?,
Thanks

A: If you don't want to do an eager load, you can override the magic __isset method in your Field class to return true for the type relationship property:
public function __isset($name)
{
    if (in_array($name, [
        'type'
    ])) {
        return true;
    } else {
        return parent::__isset($name);
    }
}

Explanation
The problem is in the interaction between how Eloquent implements the "dynamic property" for a relation (in your case, f.type), and the rules that Twig uses for accessing "attributes" of a variable.
From the Twig documentation:

For convenience's sake foo.bar does the following things on the PHP layer:

*

*check if foo is an array and bar a valid element;

*if not, and if foo is an object, check that bar is a valid property;

*if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead);

*if not, and if foo is an object, check that getBar is a valid method;

*if not, and if foo is an object, check that isBar is a valid method;

*if not, return a null value.

  foo['bar'] on the other hand only works with PHP arrays:

*

*check if foo is an array and bar a valid element;

*if not, return a null value.

The key here is the part where it says "check that bar is a valid property".  This means that on the level of PHP, Twig is calling isset on $f->type.  Eloquent implements the magic __isset method in Model, so you might think that this wouldn't be a problem.
However, take a look at how it actually implements __isset for model relations:
/**
 * Determine if an attribute exists on the model.
 *
 * @param  string  $key
 * @return bool
 */
public function __isset($key)
{
    return (isset($this->attributes[$key]) || isset($this->relations[$key])) ||
            ($this->hasGetMutator($key) && ! is_null($this->getAttributeValue($key)));
}

It determines whether a relation is "set" by looking in its array of loaded relationships (isset($this->relations[$key])).  The problem is that if type hasn't been loaded yet, Eloquent will say that it is not "set".
Thus when Twig looks at $f->type, it will think that type is not a valid property, and move on to the next rule:

...if foo is an object, check that bar is a valid method

So now it will look for the method type(), which it finds.  The only problem?  type() (the method) returns a Relation (specifically, a BelongsTo), rather than a Type object.  And BelongsTo objects aren't models.
If you want Twig to know that the property $f->type does indeed exist, you have two choices:

*

*You can eager-load the related Type object along with your Field, as suggested by @roger-collins, or;

*You can overload the __isset magic method in Field:

    public function __isset($name)
    {
        if (in_array($name, [
            'type'
        ])) {
            return true;
        } else {
            return parent::__isset($name);
        }
    }

This will force Twig to recognize that type is a valid property for Field, even before the related model has actually been loaded.

A: I had the same issue and stumbled upon this question.  After solving it myself, I thought I'd try to help you out.
Try doing a Eager Load on the model:
Field::with('type')->get()

This should allow you to do the following with no other issues.
{{ f.type }}

See more info here: http://laravel.com/docs/4.2/eloquent#eager-loading


text:
Q: Why is coffescript creating this closure I'm learning CoffeeScript I have this code:
class Person
    constructor: (@firstName, @lastName) ->
    sayHi: () ->
        return "Hi, I'm #{@firstName} #{@lastName}"

And is generating this javascript code:
// Generated by CoffeeScript 1.10.0
(function() {
  var Person;

  Person = (function() {
    function Person(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
    }

    Person.prototype.sayHi = function() {
      return "Hi, I'm " + this.firstName + " " + this.lastName;
    };

    return Person;

  })();

}).call(this);

I want to create instances of that class, but since it's inside the closure I can't how should I do that?

A: An option that is slightly less hackish is the @ operator (which is the same as this). In a browser environment, this will point to window, in node.js, it will point to exports.
class @Person
  constructor: (@firstName, @lastName) ->
  sayHi: () ->
    return "Hi, I'm #{@firstName} #{@lastName}"

window.Person only works on the browser, the @ will work for node and the browser. See https://stackoverflow.com/a/24352630/227299
Alternatively, you can run coffescript with the -b (--bare) option and the wrapping function won't be created.

A: change a bit declaration of a class
class window.Person
  constructor: (@firstName, @lastName) ->
  sayHi: () ->
    return "Hi, I'm #{@firstName} #{@lastName}"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Word to describe this behavior: applying your work habit even when you're not working? For example: I'm an engineer on a vacation. When someone mentioned a machine that's broken, I can't help but join in an try to debug the issue.

A: If you automatically try to fix a problem when you're not at work because you're so used to always fixing problems when you are at work, the behaviour is called conditioned:

[Merriam-Webster]
2 : determined or established by conditioning
// But, really, people like Padraic — who, having been deemed too mad for even the Irish Republican Army, creates his own splinter of a splinter group — are folks for whom wholesale destruction has become a conditioned reflex.
— Ben Brantley, New York Times, "Orlando Bloom and Aidan Turner Are Drenched in Blood in London," 4 July 2018

In more applied terminology, there is an entire branch of psychology related to conditioned behaviour, and how that behaviour is the result of conditioning.
For instance, from "What is conditioning? What Pavlov's dogs experiment teaches us about how we learn." at Psychologist World:

Conditioning in behavioral psychology is a theory that the reaction ("response") to an object or event ("stimulus") by a person or animal can be modified by 'learning', or conditioning. The most well-known form of this is Classical Conditioning (see below), and Skinner built on it to produce Operant Conditioning.


text:
Q: Switch error in Flutter What should I do? I'm coding a Youtube clone using GetX in Flutter.
I use Switch to route with GetX BottomSheet, but it doesn't apply, but breaks the code to apply it.
It is the same code as in the related video.
Here's the code:
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Obx(() {
        switch (RouteName.values[controller.currentIndex.value]) {
          case RouteName.Home:
            return Home();
            break;
          case RouteName.Explore:
            return Explore();
            break;
          case RouteName.Subscribe:
            return Subscribe();
            break;
          case RouteName.Library:
            return Library();
            break;
          case RouteName.Add:
            break;
        }
        return Container();
      }),

enum RouteName { Home, Explore, Add, Subscribe, Library }

class AppController extends GetxService {
  static AppController get to => Get.find();

  RxInt currentIndex = 0.obs;

  void changePageIndex(int index) {
    if (RouteName.values[index] == RouteName.Add) {
      _showBottomSheet();
    } else {
      currentIndex(index);
    }
  }

  void _showBottomSheet() {
    Get.bottomSheet(YoutubeBottomSheet());
  }
}```


text:
Q: How to avoid re-rendering of login component meanwhile app fetches data from firestore Every time I refresh the page, my react app renders the login component meanwhile it fetches the current status of signed in user. What is that is I am doing wrong over here, as redux store is supposed to be hold values even when the page is refreshed. But right now, even if the user is signed in, the app shows login component.
my app.js:
 import { doc, getDoc, setDoc } from "@firebase/firestore";
    import React, { useEffect } from "react";
    import { useDispatch, useSelector } from "react-redux";
    import { Route, Switch } from "react-router";
    import Login from "./components/Login";
    import Mainthread from "./components/Mainthread";
    import Notifications from "./screens/notifications";
    import Profile from "./screens/profile";
    import { auth, db } from "./services/Firebase";
    import { login, logout, selectUser } from
    "./services/redux/userSlice";

    function App() {
      const user = useSelector(selectUser);
      const dispatch = useDispatch();

      async function createDocument(id, data) {
        await setDoc(doc(db, "users", id), data);
      }

      async function checkDocument(id) {
        const docRef = doc(db, "users", id);
        const docSnap = await getDoc(docRef);
        if (docSnap.exists()) {
          console.log("your document exists with us...");
        } else {
          const data = { email: user?.email };
          createDocument(user?.uid, data);
          console.log("your document is being created...");
        }
      }

      useEffect(() => {
        function unsubscribe() {
          auth.onAuthStateChanged(function (authUser) {
            if (authUser) {
              dispatch(
                login({
                  uid: authUser.uid,
                  email: authUser.email,
                })
              );
              checkDocument(user?.uid);
            } else {
              dispatch(logout());
              console.log("Logged Out!");
            }
          });
        }
        unsubscribe();
      }, [dispatch]);

      return (
        <>
          <Switch>
            <Route path="/notifications">
              <Notifications />
            </Route>
            <Route path="/profile">
              <Profile />
            </Route>
            <Route path="/">{user ? <Mainthread /> : <Login />}</Route>
          </Switch>
        </>
      );
    }

    export default App;

and userSlice.js:
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  userDetails: null,
};

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    login: (state, action) => {
      state.userDetails = action.payload;
    },
    logout: (state,action) => {
      state.userDetails = null;
    },
  },
});

export const { login, logout } = userSlice.actions;
export const selectUser = (state) => state.user.userDetails;

export default userSlice.reducer;


text:
Q: ERROR: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html" I am running Reactjs with vite, When I am trying to start my app with network IP I am getting the following error

I am getting the following error when I am trying to start the app with host: localhost

index.html
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <link rel="icon" type="image/svg+xml" href="/favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Asset Scanner</title>

src/main.jsx
import React from 'react'
import ReactDOM from 'react-dom'

import App from '@@/App'
import { loadCSSVariables } from './common/utils/cssVariables'

loadCSSVariables().then(() => {
    ReactDOM.render(<App />, document.getElementById('root'))
})


text:
Q: How to Merge Three Arrays by grouping Elements under the same Index together I have three arrays like the below:
int a[] = {1,2,3,4};
int b[] = {5,6,7,8};
int c[] = {9,10,11,12};

I want to merge the above arrays by taking the first element from each array, then the second, etc. to get the below result:
int d[] = {1,5,9,2,6,10,3,7,11,4,8,12};

I have tried the following code, but as can be observed from the output it concatenates the data from each of the array rather than grouping elements under the same index together. How can I fix that?
My code:
public class MergeTwoArrays2 {

    public static void main(String[] args) {
        int a[] = {1,2,3,4};
        int b[] = {5,6,7,8};
        int c[] = {9,10,11,12};

        int a1 = a.length;
        int b1 = b.length;
        int c1 = c.length;

        int d1 = a1 + b1 +c1;

        int[] d = new int[d1];

        for (int i = 0; i < a1; i = i + 1) {
            d[i] = a[i];
        }

        for (int i = 0; i < b1; i = i + 1) {
            d[a1 + i] = b[i];
        }

        for (int i = 0; i < c1; i = i + 1) {
            d[a1 + b1 + i] = c[i];
        }

        for (int i = 0; i < d1; i = i + 1) {
            System.out.println(d[i]);
        }
    }
}

Output:
[1,2,3,4,5,6,7,8,9,10,11,12]

Expected Output:
[1,5,9,2,6,10,3,7,11,4,8,12]

A: So you want to take the first element from all three arrays a, b, c, then the second one, and so on.
For that, you need a different strategy of populating the array d.
You can iterate over all your arrays simultaneously checking if the next element exists in a particular array, and if it's the case assigning it to the current position in the resulting array.
int[] d = new int[d1];

for (int i = 0, j = 0; i < Math.max(Math.max(a1, b1), c1);i++) {
    if (i < a1)  d[j++] = a[i];
    if (i < b1)  d[j++] = b[i];
    if (i < c1)  d[j++] = c[i];
}

System.out.println(Arrays.toString(d));

Output:
[1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12]

In the case when all the given arrays a, b, c are of the same length, you can get rid of the if-statements:
for (int i = 0, j = 0; i < a1; i++) {
    d[j++] = a[i];
    d[j++] = b[i];
    d[j++] = c[i];
}

Generalizing the problem
Your problem can be generalized to merging an arbitrary number of integer arrays having the same length.
That would allow eliminating duplicated statements and hard-coded names.
/**
 * Merges arbitrary number of arrays of the same length
 */
public static int[] joinAll(int[]... arrays) {
    if (arrays.length == 0) return new int[0];

    int[] result = new int[arrays.length * arrays[0].length];

    for (int i = 0, j = 0; i < arrays[0].length; i++) {
        for (int[] arr: arrays) {
            result[j++] = arr[i];
        }
    }
    return result;
}

System.out.println(Arrays.toString(joinAll(a, b, c)));

Output:
[1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12]

Stream-based solution
In case if you fill comfortable with Stream IPA you represent the logic from generalized method shown above using a single statement:
/**
 * Merges arbitrary number of arrays of the same length
 */
public static int[] joinAll(int[]... arrays) {
    if (arrays.length == 0) return new int[0];

    return IntStream.range(0, arrays[0].length)
        .flatMap(i -> Arrays.stream(arrays).mapToInt(arr -> arr[i]))
        .toArray();
}

A: With java streams you can do that in that way:
var aMap = IntStream.range(0, a.length)
        .boxed()
        .collect(Collectors.toMap(i -> i, i -> a[i], (x, y) -> y));

var bMap = IntStream.range(0, b.length)
        .boxed()
        .collect(Collectors.toMap(i -> i, i -> b[i], (x, y) -> y));

var cMap = IntStream.range(0, c.length)
        .boxed()
        .collect(Collectors.toMap(i -> i, i -> c[i], (x, y) -> y));

var collect = Stream.of(aMap, bMap, cMap)
        .flatMap(map -> map.entrySet().stream())
        .collect(Collectors.groupingBy(Map.Entry::getKey))
        .values().stream()
        .flatMap(Collection::stream).map(Map.Entry::getValue).toList();


text:
Q: More efficient way to find if a class inherits an interface? In C#, currently i'm doing the following code to filter out a specific set of classes that inherit from the CaptureType that is passed to the method.
    public static CaptureType[] ListPluginsWith<CaptureType>()
    {
        List<CaptureType> plugins = new List<CaptureType>();
        foreach (var plugin in Bot.AutoPlugins)
        {
            CaptureType plug;
            try
            {
                if ((plug = (CaptureType)plugin.Interface) != null)
                {
                    plugins.Add(plug);
                }
            }
            catch
            {
                //doesn't inherit
            }
        }
        return plugins.ToArray();
    }

is there a more efficient/better/faster way to do this? if so, please let me know :)

A: if (plugin.Interface is CaptureType)
{
    // inherits
}

or even
return Bot.AutoPlugins.Where(i => i.Interface is CaptureType).ToArray();

UPD: if CaptureType is strongly required to be returned:
return Bot.AutoPlugins.Where(i => i.Interface is CaptureType)
                      .Select(i => i as CaptureType)
                      .ToArray();

(yes, now it looks a little more bloated, but there is another laconic answer with OfType() in this thread, so i will not repeat it)

A: I would actually suggest the following:
public static IEnumerable<CaptureType> ListPluginsWith<CaptureType>()
   where CaptureType : class
{
    foreach (var plugin in Bot.AutoPlugins)
    {
        CaptureType plug = plugin.Interface as CaptureType;
        if (plug != null)
            yield return plug;
    }
}

This has a number of advantages:

*

*If you use the is keyword, you basically end up doing two type casts (the evaluation of x is y is basically a type cast and has the same performance characteristics) so if you do (if (x is Y) { blah = (Y)x } you're doing two casts instead of just one that as and a null check requires.

*By using an interator (i.e. the yield return stuff) you don't need to create a temporary List<CaptureType> in memory, convert it to an array and then return the array.

Also note the where CaptureType : class. Since CaptureType is an interface, you can be sure that it'll always pass, but that constraint is required in order to use the as keyword. If you have a "base" interface that all your plugins implement (e.g. IPlugin maybe) then you could replace the where CaptureType : class with where CaptureType : IPlugin instead.

A: I would suggest a simple
return Bot.AutoPlugins.Select (p => p.Interface).OfType<CaptureType> ().ToArray ();

EDIT:
Thinking more, this is potentially less efficient than doing the a Where then Select combination, as in my example you do the select for every item, then limit by type...


text:
Q: Getting certain string blocks from a STRING Here is a text: string txt holds this value.

CREATE TABLE table_name1 ( column_name11231 data_type, column_name232
  data_type, column_name3 data_type, .... )
CREATE TABLE table_name2 ( column_name1 data_type, column_name2
  data_type, column_name3 data_type, .... )
CREATE TABLE table_name3 ( column_name1231 data_type, column_name2
  data_type, column_name3 data_type, .... )
CREATE TABLE table_name4 ( column_name1231 data_type, column_name1232
  data_type, column_name1233 data_type, .... )

this is a sample. i will read it from a text file. then i just want to take each CREATE TABLE command in a string array. how could i take it? I have tried split and substring. but that was foolish. I have done it with a silly and uneffective way.
here is it:
string[] totalSp = Regex.Split(txt, "CREATE TABLE");
string[] output = new string[totalSp.Length-1];

for (int i = 1; i < totalSp.Length; i++ )
{
output[i - 1] = "CREATE TABLE " + totalSp[i].Replace("\r\n", "");
}

this give me the desired output. but i now this is poor coding. cannot I do it any simplier way?

A: You can use this regex to find the statements, as long as you're not going to have much variation in the input.
var matches = Regex.Matches(txt, @"^CREATE TABLE .+", RegexOptions.Multiline);
string[] myArray = matches.Cast<Match>().Select(x => x.ToString()).ToArray();

A: You can use File.ReadLines to get the lines, and it's easy enough to filter the empty lines out without regexes.
var commands = File.ReadLines("filename.txt")
    .Where(line => !string.IsNullOrEmpty(line))
    .ToArray();

If there are other commands in the file besides create table then you can add a simple filter for that too.  Just add the below command after the other filter:
.Where(line => line.StartsWith("CREATE TABLE"))


text: Q: In App Purchase in Flutter not Fetchhing Past Purchases in Different Device Hey guys I am currently working on a project with in app purchase I can fetch past purchases if I use the device that purchased a product but if I change device with the same Apple ID there are no records of past purchases. I already used in_app_purchase and flutter_in_app_purchase both of their functions in fetching past purchases' have the same result


text:
Q: Scatterplot colors and legend based on label in R (plotly) I'm building a scatterplot in R with the following data:
df <- data.frame(
  produto=c('P1','P2','P3','P4','P5','P6','P7','P8','P9','P10')
  , categoria=c('A','B','C','A','B','A','B','C','A','C')
  , qtd_reviews=runif(10,10,50)
  , nota=runif(10,0,5)
  , flag_presente=c('Presente', 'Presente', 'Presente','Ausente', 'Ausente', 'MP','MP', 'Ausente', 'Presente', 'MP')
  , stringsAsFactors = F
)

Then, I create one dataframe for each category (one for 'A', 'B', and 'C'), because I want to create a dropdown menu for each category.
I want to create legend for flag_presente ('Presente', 'Ausente', 'MP') with 3 colors, but when I add the parameters color and colors on add_trace() the filtering on updatemenus doesn't work.
Here's the full code:
library("plotly")

df <- data.frame(
  produto=c('P1','P2','P3','P4','P5','P6','P7','P8','P9','P10')
  , categoria=c('A','B','C','A','B','A','B','C','A','C')
  , qtd_reviews=runif(10,10,50)
  , nota=runif(10,0,5)
  , flag_presente=c('Presente', 'Presente', 'Presente','Ausente', 'Ausente', 'MP','MP', 'Ausente', 'Presente', 'MP')
  , stringsAsFactors = F
)

unq_categorias <- unique(df$categoria)
for (ctg in unq_categorias) {
  assign(
    paste0("df_", ctg),
    subset(df, categoria==ctg)
  )
}

# Retorna o número maximo de reviews
max_rev <- max(df$qtd_reviews) + 1

######
# Gráfico
p <- plot_ly() %>%

  add_trace(data = df, y = ~nota, x = ~qtd_reviews, type = 'scatter', mode = 'markers', hoverinfo = 'text',
            text = ~paste('Produto: ', produto,
                          '
Categoria: ', categoria,
                          '
Qtd Avaliações: ', round(qtd_reviews, 1),
                          '
Nota Média: ', round(nota, 1))) %>%

  add_trace(data = df_A, y = ~nota, x = ~qtd_reviews, type = 'scatter', mode = 'markers', hoverinfo = 'text',
            text = ~paste('Produto: ', produto,
                          '
Categoria: ', categoria,
                          '
Qtd Avaliações: ', round(qtd_reviews, 1),
                          '
Nota Média: ', round(nota, 1)),
            visible = F) %>%

  add_trace(data = df_B, y = ~nota, x = ~qtd_reviews, type = 'scatter', mode = 'markers', hoverinfo = 'text',
            text = ~paste('Produto: ', produto,
                          '
Categoria: ', categoria,
                          '
Qtd Avaliações: ', round(qtd_reviews, 1),
                          '
Nota Média: ', round(nota, 1)),
            visible = F) %>%

  add_trace(data = df_C, y = ~nota, x = ~qtd_reviews, type = 'scatter', mode = 'markers', hoverinfo = 'text',
            text = ~paste('Produto: ', produto,
                          '
Categoria: ', categoria,
                          '
Qtd Avaliações: ', round(qtd_reviews, 1),
                          '
Nota Média: ', round(nota, 1)),
            visible = F) %>%

  layout(
    title = 'Título',

    # Legend
    legend = list(
      x = 0.6, y = 1.1,
      bordercolor = "#000000",
      borderwidth = 1,
      orientation = 'h',
      font = list(
        family = "sans-serif",
        size = 12,
        color = "#000")
    ),

    # Axes
    yaxis = list(
      title='Nota Média',
      zeroline = T,
      rangemode = "tozero",
      autorange = F,
      range=list(0,5.1)
    ),

    xaxis = list(
      title='Quantidade de Avaliações',
      zeroline = T,
      rangemode = "tozero",
      autorange = F,
      range=list(0, max_rev)
    ),

    updatemenus = list(

      list(
        y = 0.8,
        buttons = list(

          # Todas categorias
          list(
            method = "restyle",
            args = list("visible", list(TRUE, FALSE, FALSE, FALSE)),
            label = "Todas"
          ),

          # Categoria A
          list(
            method = "restyle",
            args = list("visible", list(FALSE, TRUE, FALSE, FALSE)),
            label = "Categoria A"
          ),

          # Categoria B
          list(
            method = "restyle",
            args = list("visible", list(FALSE, FALSE, TRUE, FALSE)),
            label = "Categoria B"
          ),

          # Categoria C
          list(
            method = "restyle",
            args = list("visible", list(FALSE, FALSE, FALSE, TRUE)),
            label = "Categoria C"
          )

        )
      )
    )

  ) %>% config(displayModeBar = F)

ggplotly(p)

Its in portuguese but it isn't necessary for understanding the code.
Can anyone help? Thanks

A: You simplify the whole code by adding each categoria in a loop. You then get the legend for "free".
p <- plot_ly()
for (i in unique(df$categoria)) {
  p <- add_trace(p,
                 data = df[df$categoria==i,],
                 y = ~nota,
                 x = ~qtd_reviews,
                 type = 'scatter',
                 mode = 'markers')
}

This also simplifies your updatemenus.

Complete, reduced code
library("plotly")

df <- data.frame(produto=c('P1','P2','P3','P4','P5','P6','P7','P8','P9','P10'),
                 categoria=c('A','B','C','A','B','A','B','C','A','C'),
                 qtd_reviews=runif(10,10,50),
                 nota=runif(10,0,5),
                 stringsAsFactors = F
)

p <- plot_ly()
for (i in unique(df$categoria)) {
  p <- add_trace(p,
                 data = df[df$categoria==i,],
                 y = ~nota,
                 x = ~qtd_reviews,
                 type = 'scatter',
                 mode = 'markers')
}

p <- layout(p,
  updatemenus = list(
    list(
      y = 0.8,
      buttons = list(
        list(
          method = "restyle",
          args = list("visible", list(TRUE, TRUE, TRUE)),
          label = "All"
        ),

        list(
          method = "restyle",
          args = list("visible", list(TRUE, FALSE, FALSE)),
          label = "Category A"
        ),

        list(
          method = "restyle",
          args = list("visible", list(FALSE, TRUE, FALSE)),
          label = "Category B"
        ),

        list(
          method = "restyle",
          args = list("visible", list(FALSE, FALSE, TRUE)),
          label = "Category C"
        )
      )
    )
  )
)

p

A: The way I got it (after Maximilian Peters answer), was adding 3 traces for each category.  Each trace represent on level of flag_presente.
And then, for each button we need a list of 9 TRUE and FALSE.
It goes like this:
library("plotly")

df <- data.frame(produto=c('P1','P2','P3','P4','P5','P6','P7','P8','P9','P10'),
                 categoria=c('A','B','C','A','B','A','B','C','A','C'),
                 qtd_reviews=runif(10,10,50),
                 nota=runif(10,0,5),
                 flag_presente=c('P', 'P', 'P','A', 'A', 'MP','MP', 'A', 'P', 'MP'),
                 stringsAsFactors = F
)

p <- plot_ly()
for (i in unique(df$categoria)) {

  # P
  plot_df <- df[(df$categoria==i) & (df$flag_presente=='P'),]
  p <- add_trace(p,
                 data = plot_df,
                 y = ~nota,
                 x = ~qtd_reviews,
                 type = 'scatter',
                 mode = 'markers',
                 marker = list(color = "red"))

  # A
  plot_df <- df[(df$categoria==i) & (df$flag_presente=='A'),]
  p <- add_trace(p,
                 data = plot_df,
                 y = ~nota,
                 x = ~qtd_reviews,
                 type = 'scatter',
                 mode = 'markers',
                 marker = list(color = "green"))

  # MP
  plot_df <- df[(df$categoria==i) & (df$flag_presente=='MP'),]
  p <- add_trace(p,
                 data = plot_df,
                 y = ~nota,
                 x = ~qtd_reviews,
                 type = 'scatter',
                 mode = 'markers',
                 marker = list(color = "blue"))
}

p <- layout(p, showlegend = F,

            updatemenus = list(
              list(
                y = 0.8,
                buttons = list(
                  list(
                    method = "restyle",
                    args = list("visible", list(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE)),
                    label = "All"
                  ),

                  list(
                    method = "restyle",
                    args = list("visible", list(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)),
                    label = "Category A"
                  ),

                  list(
                    method = "restyle",
                    args = list("visible", list(FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE)),
                    label = "Category B"
                  ),

                  list(
                    method = "restyle",
                    args = list("visible", list(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE)),
                    label = "Category C"
                  )
                )
              )
            )
)

p

We also need to notice that the legend is based on each trace, so it is better to hide.


text:
Q: Issue with Fabs() and Abs() My program checks to see if the max price is bigger than the price you spent. If the max price is bigger than the price you spent it turns the absolute value of two floats; but when I use fabs(), returns "Wow, you overspent on that first cupcake...you owe $0.00. Bye!".
I also tried abs(), but that didn't work.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(int argc, char**argv)
{
    float maxPrice;
    char flavor[20];
    char flavor2[20];
    float price;
    double price2;
    char anotherCupcake[20];
    double newPrice;
    newPrice=maxPrice-price;

   // int idxToDel = 2;
    //memove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);

    printf("Please enter starting budget: ");
    scanf("%f", &maxPrice);
    printf("Enter the flavor of cupcake 1: ");
    scanf("%s", &flavor);
    printf("Enter the price of %s cupcake: $", flavor);
    scanf("%f", &price);

    //determining if you have enough money for a second cupcake
    if(price == maxPrice)
    {
        printf("\nOops! No more money left to spend on anymore cupcakes...enjoy the %s one! Bye!", flavor);
    }
    else if(price > maxPrice)
    {

        printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!", fabs(newPrice)*1.0);
    }
    else
    {
        printf("Ok, looks like you you have $.2lf left to spend on cupcakes...  Would you like to get another one?", maxPrice - price);
        scanf("%s", &anotherCupcake);
        if(anotherCupcake == "yes")
        {
           printf("Enter the flavor of cupcake 2: ");
           scanf("%s", &flavor2);
           printf("Enter the price of cupcake 2 $: ");
           scanf("%f", &price2);
           printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);

        }
        else
        {
            printf("Ok then...Enjoy that one %s cupcake! Bye!", flavor);
        }
    }
    return 0;
}

A: You have to calculate newPrice with current values of
maxPrice-price, not at the beginning when neither maxPrice nor
price are initialized. Like that:
      newPrice = maxPrice - price;
      printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!\n", fabs(newPrice)*1.0);

It'll work like that:
$ ./main
Please enter starting budget: 10
Enter the flavor of cupcake 1: 1
Enter the price of 1 cupcake: $18

Wow, you overspent on that first cupcake...you owe $8.00. Bye!

As a sidenote, you didn't specify what compiler you're using but the minimum set of flags you should use with gcc/clang is -Wall -Wextra -pedantic and fix all warnings.


text:
Q: _mm_set_epi8 - what does "set" mean? What does the _mm_set_epi8 do?
I'm reading the documentation but I can't understand it, what is r0..r15?

A: _mm_set_epi8 is just a convenience macro which initialises a 128 bit SSE __m128i vector to a specified set of values (16 x 8 bit values in this case), e.g.
__m128i v = _mm_set_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);

will set v to the 128 bit value: 0x000102030405060708090a0b0c0d0e0f.
There are other similar macros for different vector element types, e.g. _mm_set_epi16, _mm_set_epi32, _mm_set_ps, etc.
(Note: the documentation you linked to in your question is not very good, but r0..r15 apparently just refer to the individual 8 bit fields within the returned vector).


text:
Q: How to Integrate React Epub Reader with next js I am trying to integrate react epub reader  with Next Js  but getting one error and  works  well with react js,  I need your help to integrate epub reader with next js
error
My code
import React from 'react';
import { ReactReader } from "react-reader";

export default function Home() {
  return (

<ReactReader
        url="./Boy without a name English.epub"
        title={"Alice in wonderland"}
        location={"epubcfi(/6/2[cover]!/6)"}
        locationChanged={epubcifi => console.log(epubcifi)}
      />

  )
}

A: The issue can be fixed by transpiling react-reader and epubjs modules (exported as ESM since a few months back).
For example, using next-transpile-modules in Next.js config:
// next.config.js
const withTM = require("next-transpile-modules")(["react-reader", "epubjs"]);

module.exports = withTM({/* custom config */});


text:
Q: Arbitrary attributes in retrofit api get with json deserialization I have an API response that looks like this:
{
"attribute_name_that_i_know": "stuff",
"attribute_name_that_i_know": "stuff",
"attribute_name_that_i_know": "stuff",
"attribute_name_that_i_know":
{
"attribute_name_that_i_do_not_know": "stuff",
"attribute_name_that_i_do_not_know": "stuff",
"attribute_name_that_i_do_not_know": "stuff",
...
}
}

I'm trying to get at what is in the attribute_name_that_i_know that has arbitrary keys (length and name.)
When I put:
@SerializedName("attribute_name_that_i_know")
Sometype sometype;

in the parent object's class sometype (the nested object) is always null.  I can't figure out how to just drop the nested data into an object.  Any object, I don't care.  I just want gson to keep the data.

A: Having that field Object is not your only choice here. I wouldn't call it an anti-pattern because you cannot do much where you can't have enough type info. Since you expect arbitrary data structure, you can accomplish what you need or smooth it with:

*

*Map<String, Object> - This is already a deserialized value. The pro for this approach is that it can hide unknown objects one level down having the keys known at the top-most level. Some disadvantages are that deserialization may be expensive for some strategies, and that the underlying Objects can be deserialized as raw primitive literals (like strings, numbers, and that's fine) and more complex raw structures like maps (Map<String, Object>) and lists (List<Object>) because Gson does not have enough information to restore a ready-to-use object from any given JSON until you can provide an exact mapping.

*JsonObject - Another option that can be useful. Some pros for this option is that you can introspect the structure of unknown arbirtrary objects more precisely and even deserialize some fields in a certain way you want, because Gson does not make deserialization here per se (in terms of your application scope), but constructs a JSON object tree here that you can traverse with easy to use Gson tree API (yes, you can get rid of instanceof comparing to the first option, but you "instanceof"-like introspection is still necessary). A con is that you should have DTO (well-Gson-aware) and your application objects (that know nothing of Gson at all) thus only letting Gson-aware classes to live in the scope of the application-to-service-talk layer.

*

*JsonElement - An alternative of the latter option for cases you expect that arbitrary property to be a primitive, an array, or null (the latter does not play much here). Looks like Object but still has more convenient introspection facilities and keeps the structure in the tree form.

*JsonDeserializer<T> - The most advanced option. If you can make some analysis of the arbitrary object based on the JSON tree structure in order to restore the right type, then you can try to write such a deserializer. Unfortunately, your mapping type would be still Object, but you could create a concrete object you need if it's possible. JsonDeserializers can be attached to Gson via GsonBuilder.

A: The solution I came up with is to assign whatever is in that attribute to Object, then manipulate the data on getThatAttribute().
So it looks like this:
@SerializedName("something")
String something;
@SerializedName("something_else")
String somethingElse;
@SerializedName("something_else_else")
int somethingElseElse;
@SerializedName("nested_object")
Object nestedObject;

public ConvertedClass getNestedObject() {
    return new ConvertedClass(nestedObject);
}

This seems like an anti-pattern, but it works.  If anyone has a better solution I will pick that answer over this functional, but ugly, solution.


text:
Q: Do Electrical Engineers use microcontrollers? I've always loved to program, and I just recently became interested in electronics and programming microcontrollers. It is very fun, but I am wondering if I am learning something useful that can get a job in when I grow older. I am wondering whether Electrical Engineers use microcontrollers.
I know that jobs where you need to bring power to different parts of a house probably would not, but perhaps a job like this:

Your Responsibilities:

*

*Design and develop new defibrillator products. Primary focus will be on new product design and current product support in the area of analog and digital design.

*Model analog circuits using various simulation tools, such as PSPICE and MATLAB.

*Build prototypes and prove design feasibility, functionality and performance.

*Document all phases of the design including requirements, specifications, plans, reviews, test procedures, and test reports.

*Support existing products. Investigate and determine root cause of product issues found in manufacturing and the field. Troubleshoot systems, PCBs, cables, and firmware. Use test equipment to analyze and resolve issues.

*Identify, evaluate and recommend key suppliers based on electrical technical abilities, experience, history, and certifications.

*Facilitate and maintain constant communications with key suppliers and internal stakeholders during project development.

*Represent the EE development group as a technical team lead on projects. This would include providing technical solutions as well as project scheduling and project tracking.

*Document the design for manufacturing (i.e. drawings, schematics, experiments, changes, test results, data, PCB layout, etc.).

*Work with cross functional teams that include: Mechanical eng., Software eng, Clinical applications, Learning Products, Marketing, Support Engineering, Quality & Regulatory, and Supply Chain. Teams are experienced, but relatively small and members hold many development roles.

Would people who do this use Microcontrollers or something similar?

A: For slower speed, low cost, smaller packages, higher reliability (because of fewer connections) and more easily maintained solutions microcontroller are often the goto solution.  Even if you scan around on this web site you will see many questions where someone is being overly complex, some people automatically ask the poster "why don't you use a microcontroller) ?

A: The definition of EE is somewhat flexible. If you have an EE degree from a major university, you may or may not have experience with programming and microcontrollers. Many EE programs do not require programming courses. This is a reason why a lot of engineers Re choosing Computer Engineering rather than EE because they straddle the fence between hardware design and software design.
Microcontrollers can enable lower cost and shorter design cycles for the same functionality for many designs. There are some things that must be done in the analog world, and some that must be done in the digital, but generally when it comes to microcontrollers the decision isn't whether it can be done, but whether it can be done better, cheaper, faster, or offer more features and performance than a design without a microcontroller.
An EE who is not familiar with and does not use microcontrollers will limit themselves, but if they have a great depth in the analog world, or prefer working in large teams where the micro stuff can be done by others, they will do  very well where their expertise and focus is needed.

A: Many EE's use microcontrollers, but there are many that don't, such as ones that specialize in analog design, RF engineering, power engineering etc.
But I would think that most EE's that do digital design these days also incorporate microcontrollers into their designs, just because it saves a lot of hardware in most cases, and makes the design more flexible.  (Another way to minimize parts and keep a design easier to change is to use FPGAs, which requires a different type of programming called VHDL.)  As one will see below, whether or not they get involved much with the programming of these mirocontrollers will depend upon the size of the company and its organization.
Ideally, a EE that has gotten a bachelors degree in EE has also taken a least a few programming courses.  Most likely one or more of these have included C, which is used for the majority of embedded programming on microcontrollers.  If not, it is relatively easy to pick up C on one's own, although if you never done any programming there will be some hurdles to get over.
Nevertheless, IMO it is is way easier for a EE to learn to program than for a programmer to learn to work with hardware.  In the latter case, I wouldn't think most  CS majors would to be able to learn digital or analog design on their own without any formal courses, but they should be able to learn to read schematics, use a multimeter and oscilloscope, and perhaps a logic analyzer.
As others have mentioned, if one knows they are interested into going into embedded programming and design, a degree in CE might be a good choice.  I doubt you will get as much basic EE theory as one would get taking just a EE major, for example there would be less emphasis on analog design.  When I got my BSEE, CE degrees didn't exist yet so I went ahead and got an MSCS degree at night while working my first job (and let the company pay for my tuition and books).
Surprisingly, working with embedded devices does involve quite a bit of analog circuitry, in order to interface with the outside world.  Also one gets involved in power supply design.  One of the products I was involved with had 9 different voltage rails (-6.1, 1.8, 2.5, 3.3, 3.6, 4.1, 5.0, 9.6 and 12), several of them for an LCD display.
As far as your hypothetical job description goes, in smaller companies like a start-up, as the lone engineer I have done all these roles for a single project -- wrote the spec, designed the circuit, both digital and analog, created a BOM (bill of materials), ordered parts from Digi-Key and Mouser, laid out the PCB with Eagle, ordered PCB's, debugged the hardware when it came back from the assembly house, wrote firmware in C to further test out the board, and then wrote the production firmware in C.  I also wrote the necessary documentation for the FDA (this was a medical device), and provided support for the field.  So in this case, it was very useful for me to have a background in both EE and CS.
But in many companies, these roles might be split up among several engineers -- most likely the hardware design would be done by one or more engineers, the PCB layout by another, and the programming and testing by a third group.  In the latter case, as mentioned above, the programmer, in order to test out their firmware, would need to have a basic grounding in electronics.  But the hardware designer, besides having to know how to incorporate the microcontroller into the design (which is not a trivial task -- most microcontroller datasheets run hundreds of pages long), may not get involved in the firmware at all. However at the beginning of the design, it is likely the hardware designer(s) and firmware programmer(s) would spend quite a bit of time together doing trade-offs that would minimize the hardware required while also making the design as easy for the programmers to deal with.

A: Yes!
Programming and interacting with microcontrollers can be one of the main responsibilities of an electrical engineer.
Microcontrollers represent somewhat of a middle ground for engineers and programmers.  Creating proper firmware requires not only a good knowledge of programming, but also a working knowledge of the electronics that will be interacting with the program in the microcontroller.
The job description you posted doesn't seem to be about design, specifically.  It sounds more like they would put you in a testing and troubleshooting position.  This is still a task that an electrical engineer would do though.

A: Yes EEs use microcontrollers.
The human race produces over 20,000,000,000/year[1], about 40x more than microprocessors. Someone is designing, testing, debugging, and enhancing systems and products using those MCUs; many are used in products designed by teams including EEs.
AFAICT a UK a trend is for EEs to become embedded software developers, or get training to be embedded software developers too. So you might be ahead of that EE trend anyway. You might want to consider majoring in embedded development if looking at college, or looking at jobs recruiting 'Embedded Software Developers', to get a better idea of what skills are useful.
At least one large, famous, UK company has said that there product development life-cycle would be improved by having more, even better, embedded software developers. I suspect that is true for many other companies around the world.
[1] IIRC they were a figure for 2011. I'll try to find my original source reference.  It was very hard to get up-to-date numbers, and that was the most up-to-date I have found. I think that was a value from an industry survey by one of the market analysts. In that case, it may have been approximate, maybe derived by taking, say, the top 10 manufacturers, reading and interpreting their annual reports, and scaling for overall estimates of sector revenues.
Alternatively, it may have been derived by looking at products shipped in several sectors and extrapolating. For example, AFAIK, every mobile phone contains at least one MCU, digital cameras have one, music players have one, TVs have one, hand-help games have one, wireless routers have one, cars average 17 (IIRC), etc. so if there are a figure for product volumes in large sectors, then it might be 'triangulated' that way.
I believe ST claimed over 1B ARM MCU's, or 2B MCUs, and they aren't the biggest, and there are lots of big players, so I think the value is likely realistic now. I also believe I've seem some press releases for individual manufacturers claim over 1B parts/annum, so I think it is plausible.

A: Q: Do Electrical Engineers Use Microcontrollers?
Yes.  Absolutely.  From simple toys to complex manufacturing processes and robots.  It is not  a skill that will hurt you to know.  Learn as much about them as you can.

A: This particular job may not, but the product would likely include a microcontroller and perhaps be controlled by a more powerful embedded system.
Note that it mentions 'troubleshooting' (but not writing) "firmware".
It's also possible this job description was written by someone (for example, an HR person) who doesn't really understand the engineering process.
In larger companies people tend to specialize, and you might have an analog person doing the high voltage design and control design, and a firmware person doing the low-level control firmware, and maybe an entire different team developing a GUI and touch panel controller. On a regulated safety-critical device like a defibrillator, you'd probably have a systems engineer defining the specifications to be met and the interfaces between the areas of responsibility.

A: Yes, and Yes! I've done the job described by your posting (almost certainly not for the same client) and many similar ones. You better believe the defib had a microcomputer in it (pedants: I'm totally aware of the difference; I just don't give it much significance in this context).
I'm an SWE with one foot in EE; there just as many are EEs with a foot in SWE. Sit wherever on that spectrum it suits you. Any product smarter than a hammer (and maybe some of those!) have a programmable controller in them. It might be an MCU, a micro-computer, or a full-on desktop mother-board, depending on what / how much it needs to do. Some laboratory instruments like HPLCs that manage and reduce a lot of data and have to present a complex GUI to the user (each of which tasks can be very compute-intensive) would fall into the latter category. The portable defibrillator an amublance crew or emergency department uses would fall somewhere in the middle. A string of holiday lights might have the cheapest, smallest MCU, if it has any at all.
Your programming skills won't go to waste if that's how you want to spend your career. Do be aware, though, that while a full set of EE, SWE, and whatever xxxE skills will come in very handy, you will almost certainly specialize - or get boxed into :-( - one of those as primary.
I got an Engineering Management degree (because it was the closest (hint: not close!) fit to SWE I had available to me at the time) knowing full well I'd suck rocks at managing people, would have hated it and run screaming from any attempt to put me in a manager's chair. But! (and there's always 'but', isn't there?) a BS in EM came with at least a 101-level course in Physics, Mechanics, Chemistry, Math (a lot more than a 101, of course), Programming (a few of which I tutored or taught or just outright screwed around with), Electronics, Analog Computing, and more. I would have been well served with a couple of life sciences courses as well, had they been offered, though I'm not sure I or the university knew that then.
But, the bottom line - and, finally, my point - is that a broad spectrum education can take you a lot places a highly specialized one might not (and, yes, vice-versa). My 101-levels put me in a position to know what I didn't know but needed to, and to ask useful questions of the brilliant specialists whose work I and my co-workers were incorporating into ever smarter, and sometimes previously unimagined, products.

A: Usually learning a microcontroller is not enough and one microcontroller cannot suitable for all application (industrial,didactic,...).learning a microcontroller maybe need long time and its maybe the microcontroller do not generate after some years.however its just a skill and its not the main of EE.but this skill is necessary for every electronic engineer.

A: Yes, embedded system (hardware, circuit and software to drive it) is standard in education courses at technical school and university levels.
Example: UTAustinX: UT.6.01x Embedded Systems - Course Info


text:
Q: Is there an NHibernate event you can register for which fires on lazy load When my server is run in some debug mode, I'd be interested in logging lazy loads (whether it be that a foreign key was exercised or whether it be that a child collection was loaded).  Anyone aware of whether NHibernate exposes such an event?
Edit: I don't just want to enable nhibernate log4net logging (which I currently suppress below Warn), I'd actually like to catch an event so that I can process it as I wish.  For instance, at the end of a web service call where I log how long the web service call took, I may log some db statistics including number of lazy loads that occured during that call, etc.

A: Have you looked at NHProf? It's should let profile how nHibernate is behaving and give you a good insight into how thigns are running.
EDIT See this question: NHibernate for web app, count amount of lazy loading occurrences per request

A: Try implementing the IInitializeCollectionEventListener or overriding the DefaultInitializeCollectionEventListener.  This fires during the lazy load of a collection.  At least it does the first time.  Not sure if it fires when the collection is loaded from cache or not.

A: There are pre-load and post-load events...


text:
Q: C# Access BindableObject properties I have a problem. I created a CollectionView with a few products. Now I added a TapGestureRecognizer to it with the following function:
private void product_Clicked(object sender, EventArgs e)
{
    CachedImage image = (CachedImage)sender;

    var FileName = image.Source.BindingContext;
}

Now what I want is to get the FileName that is stored inside the BindingContext. If I set a breakpoint on this line: var FileName = image.Source.BindingContext; I can see in the BindableContext that there is a element called FileName, but when I do this: var FileName = image.Source.BindingContext.FileName;, It says:

'object' does not contain a definition for 'FileName'

So how can I access that property from the BindableObject?

A: The declared type of BindingContext is object, which of course does not have a FileName property, so the C# compiler won't allow that.
If you want access to the actual object's type, you need to cast the BindingContext like this:
var viewModel = (MyViewModel)image.Source.BindingContext;
var filename = viewModel.FileName;

Substitute in the actual class name you use for the BindingContext that has FileName as a property.


text:
Q: forfiles.exe not working for c:\users\internet\downloads or documents I am getting could not find c:\users\internet\downloads\new.txt when i run the script in cmd
is it because there's a lock icon on the user account on windows7, the script works fine if i change the location to the c:\test folder
forfiles.exe /P "C:\users\Internet" /S /M . /D -7 /C "cmd.exe /c del /Q ""@path""
what i need to do is delete files every 7 days left in my documents and downloads folder, on a generic library account used by everyone at work, it's a windows 7 guest account.

A: Ok. So it's not the Guest-account but a Local account.
First some small things i noticed about your script.

*

*If you're going to delete everything older than 7 days in the whole profile (like your script is doing) you'll get in trouble. You will also delete lots of files in appdata, "program settings", etc... You don't want that because those programs could become unusable. The default is, you don't see those files/directories but if you use the command prompt they are there. (Try setting explorer to display hidden files or typing C:\Users\Internet\appdata in the address-bar)

*I'm still getting nothing with /M .. I need to use /M *.* or omit it completly. (default is /M *)

*If you are running this as yourself (and not "internet") you don't have enough permission to delete them. (Hence the lock-icon in the file) You need to take ownership of the files before you can delete them. You could try running the script as administrator but i'm not sure if that helps.

There are several ways to tackle this problem. Below i mention another approach about resetting the whole account. But here is a script which deletes files older than 7 days.
It changes the current directory to C:\Users\Internet (the popd changes it back). Then it loops through a given set of directories from which you want to delete files. You see i didn't specify the whole appdata-dir but did include the AppData\Local\Temp and Temporary Internet Files. Add your own if you so desire. It will take ownership (for you) on all files and directories specified. Then it will give Everyone rights to those files (so it won't interrupt with their programs). After that only files older than 7 days will be deleted. You need to specify del /a to include deleting hidden files.
(I added some checks at the top of the batch-file to make sure your in the right directory. You really don't want to do this in another directory by accident.;)
@echo off
PUSHD C:\Users\Internet
IF /I "%cd%"=="C:\Users\Internet" GOTO OK
ECHO Oops, CD didn't work. You really don't want to do this in another directory !!!
POPD
EXIT/b
:OK
SET "dirs=AppData\Local\Temp:Contacts:Desktop;Documents:Downloads:Favorites:Links:Music:Pictures:Videos:AppData\Local\Microsoft\Windows\Temporary Internet Files"
FOR %%d IN ("%dirs::=" "%") DO (
  TAKEOWN /R /D Y /F %%d
  ICACLS %%d /T /GRANT Everyone:F
  FORFILES /P %%d /S /D -7 /C "cmd /c del /q /a "@path""
)
POPD

This will not delete "program settings" but will also leave other temp-directories (other than AppData\Local\Temp) alone. So if you have other directories you can include them in the set-line.
Another approach would be to reset the whole user-account. You could do
net user internet /delete
net user internet /add
rd c:\users\internet /s/q

You need to do this as an administrator. But this way all settings the user did gets lost. Not only older then 7 days. It will clear everything. Not sure if that's desired. It is however the "cleanest". If it's a public computer you could do this every other day (or every day). You could also backup the profile and restore it but this also deletes younger files and resets the account to a specific time/state.
What is the reason only files older than 7 days should be deleted? If you really want to get to files younger than 7 days you need the first script.


text:
Q: transfer file to remote host and append to file if existing I have a command-line program that continuously generates output on the shell.
I would like to be able to transfer the output to another unix host for which I know IP, username and password.
Since the program does not terminate, I would also like to continuously update the file, without removing the previous output.
Is there a way to do it from command line?

A: I think an ideal method would involve sending it to the remote server via syslog. This simple ssh command should also work:
somecommand | ssh somehost 'cat - >> file.log'

A: *

*Re-direct the command line program's output to a file with >> filename

*Use rsync to send it onto the remote machine and file

A: Automation :
1.Install or compile sshpass
2.Add the lines to your .bashrcof .profile
HOSTNET=<YOUR_REMOT_HOST>
LOGINNET=<YOUR_REMOTE_LOGIN>
PASSNET=<YOUR_REMOTE_PASSWD>
teenet () {
    sshpass -p$PASSNET ssh $LOGINNET@$HOSTNET 'tee >> YOUR_REMOTE_LOG_FILE'
}

3.Now update your environment : . ~/.bashrc
You can now pipe every output to teenet.
Example :
tail -f /var/log/syslog | teenet


text:
Q: lib/gdbserver Error:Permission denied I'm trying to debug my android application in Eclipse/ADT by selecting:
Debug As->Android Native Application
However, after building I get:
gdbserver output:
run-as: exec failed for lib/gdbserver Error:Permission denied
Verify if the application was built with NDK_DEBUG=1

I am indeed building with NDK_DEBUG=1
Any ideas on how to fix this, or at least why this shows up?
I'm trying to debug the app on a droid bionic, Android Ver 4.1.2
NDK Ver: r8e
I'm not sure what extra information to provide, so please feel free to ask away.
EDIT/SOLVED!!
I needed to change the installLocation attribute in my manifest to:
android:installLocation="internalOnly"

I can't believe how much time i spent on this... :-(

A: You need to change your installLocation attribute in your manifest. Try this:
android:installLocation="internalOnly"


text:
Q: Как влияет шифрование диска Linux на скорость работы и производительность системы При установке какой-либо Linux (например Ubuntu или Kali), установщик предлагает установить шифрование диска.
Как скажется шифрование на скорости работы системы?, будет ли Linux использовать больше ресурсов компьютера и будет ли это заметно?

A: В большей степени это будет влиять на старт ОС, т.к. данные зашифрованного диска необходимо расшифровать перед чтением. Лично у меня это не вызывало никаких проблем, однако есть вероятность столкнутся с проблемами при востановлении системы, если что-то пошло не так.
Если у Вас нет необходимости хранить большие объемы супер секретного содержания можно ограничиться шифрованием директории пользователя (при необходимости)
Еще не приходилось сталкиваться со специалистами, которые рекомендуют шифровать диск. Если есть желание что-то спрятать или ограничить доступ используют более ухищренные способы. Например LVM на нескольких физических дисках с доп плюшками

A: Так или иначе влияет на произодительность дисковой подсистемы, процессора и расход памяти. Как именно влияет от выбранного алгоритма шифрования, поддержки его на аппаратном уровне, выбранного варианта шифрования: определнный раздел шифруется, весь диск, несколько дисков.


text:
Q: How do i apply custom date formatting from excel in java? I have an 2007 excel file called Test10. The first row has 10 headers, test1 test2 etc to test10. The second row, column 3 has a date, 10-10-2020 on the cell with the 10-10-2020 date there is a custom date format -> dd-mm-yyyy
The date in the cell is written as 2020-10-10.
I have the format from the cell in Java, however when I get it it's dd/-mm/-yyyy;@ and the date is 2020-10-10.
I need to somehow apply that format to the date at hand.
I need something more flexible, is there a class that does that format? All I have managed to find so far is how to apply formatting to the excel in java when creating the excel, but not the other way around, when getting it from the Excel file.
I can manually serialize the format and remove the special characters that are not needed but that is a workaround.
I need a class that will apply the strange looking format to the date, in Java. Is there anything like that?
Also the example I provided above is a very simple example.
We're using a custom handler, the date comes as a double and we currently use DateUtil.getJavaDate to get the date as a string.
I have not created the handler so it's quite hard to understand the whole of it, but somewhere in the handler, the custom formatting for the cell is extracted from the excel and put into a variable, at the point where the DateUtil.getJavaDate is called I have access to the formatting variable.
Previously it was using SimpleDateFormat(CONSTANT_FORMAT).format(DateUtil.getJavaDate(d)) to format it, but I need to apply the custom format. Is there a library that parses xlsx date formats. As the dd/-mm/-yyyy;@ format will not work with SimpleDateFormat.
Also I cannot serialize the format hardcoded as if I replace mm with MM how do I know if the user wanted minutes or months?

A: DataFormatter from org.apache.poi handles the weird excel formats


text:
Q: How do I access other attribute values from inside a custom ValidationAttribute in an asp.net mvc 2 application? I'm using asp.net mvc 2 with C# and DataAnnotations.
The situation is this: I have a custom control that is strongly typed against a model class. This control is displayed on the view several times but with differing property values, such as headings (Ex: Question 1, Question 2, Question 3, etc.. are all headings). I can write a custom validation class that validates this object as a whole, but the problem is, I can't get specific Html.ValidationMessage(...) tags to display. The validation errors only show in the summary at the top of the view and I want them to show at both the top and beside the specific control that failed a validation.
I've tried creating custom validation classes like the one below to validate on a property by property basis, but the issue is I need two of the model's values: the Rating and the Heading. The actual business validations are performed against the Rating, but the Heading property identifies to the user which control on the screen is incorrect.
    [AttributeUsage(AttributeTargets.Property)]
    public class RatingValidation : ValidationAttribute
     {

      public string Heading { get; private set; }
      private readonly string ErrorRatingInvalid = "Rating for {0} is invalid. Rating is required and must be between 1 and 5.";

        public override string FormatErrorMessage(string name)
        {
            String errorMsg = ErrorRatingInvalid;
            return String.Format(CultureInfo.CurrentUICulture,
                                 errorMsg,
                                 Heading);
        }

      public override bool IsValid(object value)
      {
       bool isValidResult = true;

       if (value == null)
        return false;

        //Trying to do something like the following. This doesn't work because the
        //attribute is applied to a property so only that property value is passed.
        //In this case, the type of myRatingObject would likely be the same as the
        //property validated.
        var myRatingObject = TypeDescriptor.GetProperties(value);
        this.Heading = myRatingObject.Heading;

        if( myRatingObject.Rating < 1 || myRatingObject.Rating > 5)
            isValidResult = false;

       return isValidResult;
      }
     }

Example of my model class:
    public class MyModel
    {
        public MyModel()
        {
            //this.IsEditable = true;
        }
        public String Heading { get; set; }
        [RatingValidation()]
        public int Rating { get; set; }
    }

Thoughts?
EDIT 1
I wanted to put some more code down to better explain why creating separate class validators won't work as a solution in this case.
Recall that all of this validation is going into a custom partial view that is strongly typed. More accurately put, this is an Edit template. The main Model will have a List of the same type Model that this partial view displays. For example purposes, I have revised some of the above code to illustrate this better. I am leaving the code above this edit untouched so the discussion leading to this edit makes sense and can see where the conversation started and the direction it went.
Pardon the code as the demo app for testing this is rather verbose. Hopefully, it better explains my problem.
    [RatingsValidationAttribute()]
    public class PersonRating
    {
        public String Heading { get; set; }
        public int Index { get; set; }
        public int Rating { get; set; }
    }

    public class Person
    {
        public String FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public List<PersonRating> Ratings { get; set; }
    }

In my main View I have:
        <%= Html.EditorFor(m => m.Ratings) %>

The Ratings View control looks like:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ModelBindingResearch.Models.PersonRating>" %>
<%= Html.HiddenFor(m=>m.Heading) %>
<%= Html.HiddenFor(m=>m.Index) %>
 <%= Html.DisplayTextFor(model => model.Heading) %>
 :
 <%= Html.TextBoxFor(model => model.Rating) %>
 <%= Html.ValidationMessageFor(model => model.Rating, "*")%>
 <%= Html.ValidationMessageFor(m=>m) %>

The validation attribute class:
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
        public class RatingsValidationAttribute : ValidationAttribute
        {
            public RatingsValidationAttribute()
            {

            }

            public int Rating { get; private set; }
            public string Heading { get; set; }

            private readonly string ErrorRatingInvalid = "Rating for {0} is invalid. Rating is required and must be between 1 and 5.";

            public override string FormatErrorMessage(string name)
            {
                String errorMsg = ErrorRatingInvalid;
                return String.Format(CultureInfo.CurrentUICulture,
                                     errorMsg,
                                     Heading);
            }

            public override bool IsValid(object value)
            {

                bool isValidResult = true;
                PersonRating personRating = (value as PersonRating);

                try
                {
                    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
                    Heading = personRating.Heading;

                    if (personRating.Rating < 1 ||      //Rating must be b/t 1 & 5
                        personRating.Rating > 5)
                    {
                        isValidResult = false;
                    }
                }
                catch (Exception e)
                {
                    //log error
                }

                return isValidResult;
            }
        }

My test model binder. This doesn't do anything yet. It's just exploratory. Note that variable o contains the full object model and all values. This code borrows heavily from: ASP.NET MVC - Custom validation message for value types
    public class TestModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Object o = base.BindModel(controllerContext, bindingContext);
            Object obj = bindingContext.Model;
            Person p = (Person)o;
            bindingContext.ModelState.AddModelError("FirstName", "Custom exception thrown during binding for firstname.");
            return o;
        }

        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
        {
            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
            String propertyName = propertyDescriptor.Name;
            Object propertyValue = value;
        }

        private bool IsFormatException(Exception e)
        {
            if (e == null)
                return false;
            else if (e is FormatException)
                return true;
            else
                return IsFormatException(e.InnerException);
        }
    }

My Home Controller (just the methods I added for the Create view):
    public ActionResult Create()
    {
        return View(getPerson());
    }

    [HttpPost]
    public ActionResult Create(Person p)
    {
        return View(p);
    }

    private Person getPerson()
    {
        Person p = new Person();
        Address a = new Address();
        PersonRating pr1 = new PersonRating();
        PersonRating pr2 = new PersonRating();
        PersonRating pr3 = new PersonRating();
        pr1.Heading = "Initiative";
        pr1.Rating = 5;
        pr1.Index = 1;
        pr2.Heading = "Punctuality";
        pr2.Rating = 5;
        pr1.Index = 2;
        pr3.Heading = "Technical Knowledge";
        pr3.Rating = 5;
        pr3.Index = 3;

        a.Street = "555 Somewhere Dr";
        a.City = "City";
        a.State = "AL";
        p.FirstName = "Jason";
        p.LastName = "Rhevax";
        p.Age = 30;
        p.PersonAddress = a;
        p.Ratings.Add(pr1);
        p.Ratings.Add(pr2);
        p.Ratings.Add(pr3);
        return p;
    }

Lastly, the Create.aspx in full:
    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ModelBindingResearch.Models.Person>" %>

    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
        Create
    </asp:Content>

    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Create

        <% using (Html.BeginForm()) {%>
            <%= Html.ValidationSummary() %>

            <fieldset>
                <legend>Fields</legend>

                    <%= Html.LabelFor(model => model.FirstName) %>

                    <%= Html.TextBoxFor(model => model.FirstName) %>
                    <%= Html.ValidationMessageFor(model => model.FirstName, "*") %>

                    <%= Html.LabelFor(model => model.LastName) %>

                    <%= Html.TextBoxFor(model => model.LastName) %>
                    <%= Html.ValidationMessageFor(model => model.LastName) %>

                    <%= Html.LabelFor(model => model.Age) %>

                    <%= Html.TextBoxFor(model => model.Age) %>
                    <%= Html.ValidationMessageFor(model => model.Age) %>

                    <%= Html.LabelFor(model => model.PersonAddress.Street) %>

                    <%= Html.TextBoxFor(model => model.PersonAddress.Street)%>
                    <%= Html.ValidationMessageFor(model => model.PersonAddress.Street)%>

                    <%= Html.LabelFor(model => model.PersonAddress.City) %>

                    <%= Html.TextBoxFor(model => model.PersonAddress.City)%>
                    <%= Html.ValidationMessageFor(model => model.PersonAddress.City)%>

                    <%= Html.LabelFor(model => model.PersonAddress.State) %>

                    <%= Html.TextBoxFor(model => model.PersonAddress.State)%>
                    <%= Html.ValidationMessageFor(model => model.PersonAddress.State)%>

                    <%= Html.EditorFor(m => m.Ratings) %>

                    <input type="submit" value="Create" />

            </fieldset>

        <% } %>

            <%= Html.ActionLink("Back to List", "Index") %>

    </asp:Content>

Lastly, I registered my model binder in global.aspx's application_start method via:
ModelBinders.Binders.Add(typeof(Person), new TestModelBinder());

So, the validation below works, but here's the issue. The validation message displayed by the RatingsValidationAttribute class is correct, but I only want that message displayed at the top of the page. On the control, I just want an "*" displayed by the Ratings text box. You'll note that the following
<%= Html.ValidationMessageFor(model => model.Rating, "*")%>

does not display the asterisk. I suppose this is because the attribute validates at the class level. When inspecting the ModelState in my model binder, the key that actually holds the error message is something akin to: "Ratings[0]", which means to display that message, I have to use the following:
 <%= Html.ValidationMessageFor(model => model)%>

For one, this is ugly. Secondly, there will be more than one validation checked per partial control, so I want the error in the summary to detail which heading has an error and just use "*" asterisks to denote the controls that have an error.
I apologize for the length of the edit. I try to handle questions I ask on stack overflow in such a way that there is little doubt what the resolution was. Feel free to ask for more code (in case I forgot to post something) or any other questions.
EDIT 3
A general note about creating a validation attribute on the class level: when an validation fails and an error is added to the ModelState, the field name is the name of the class. Since my class being validated is a List of 3 objects that are contained in a List on the view's Model, the ModelState keys are something like: Model.ListName[index].
Is there a way to specify the key associated with the error message for a custom validation class that evaluates at the class level? For field level custom validation attributes, this isn't an issue.
EDIT 4
This blog post, http://blog.ceredir.com/index.php/2010/08/10/mvc2-cross-field-validation/, addresses the issues of this question. My only issue is it requires me to create 4 classes per validation I want to perform, which is pretty excessive. Still, it's the first working example that shows a way to have an validation attribute applied to a field/property and have access to the entire model for that class.
Now my only remaining issue is trying to intercept some behind the scenes validations the framework does for you. I'm talking about if you have an int field on your form and don't put a value, the framework adds a validation message like:
The _____ field is required. (where ______ is the name of the int field).
It also does something similar if you provide a text value for an int field:
The value 'asdf' is not valid for ______.
Because of my situation where these validations are being performed on a model that is iterated over several times, I need to amend these messages to display the Heading property of the object in the messages above. The above messages would change like so:
The __________ field is required. --> The {0} field for {1} is required.
The value 'asdf' is not valid for (field name). --> The {0} value of {1} is not valid for {2}.       -->                                        The Rating value of 'asdf' is not valid for  Technical Knowledge.
I hope that made sense. I think I've fumbled this entire question into non-sense. I might come back and try to rephrase somehow. It'd help if I could get some kind of feedback.

A: Wait for MVC 3.  I'm being serious.
The options for class wide custom validation attributes are pretty poor right now without any really good extensibility points.  Your pretty much stuck creating a custom ModelBinder, which can then add values to ModelState, to do anything complex with validation attributes.
Use the attributes just like you would and then detect what Types are requested from the binder,  Reflect to find the attributes, and then validated/add to model state as necessary.
MVC 3 fixes this problem but until then your stuck creating your own binder.

A: You could use a class attribute to achieve this:
[AttributeUsage(AttributeTargets.Class)]
public class RatingValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var model = (MyModel)value;
        // TODO: here you have the model so work with the
        // Rating and Heading properties to perform your
        // validation logic

        return true;
    }
}

And you model:
[RatingValidation]
public class MyModel
{
    public String Heading { get; set; }
    public int Rating { get; set; }
}

Or even better: use FluentValidation which integrates nicely with ASP.NET MVC.

A: Better phrasing of this question altogether:
How can I get a distinct error message to show for the validation summary for a given form field with a separate & distinct message showing beside the field for which the validation applies?
Example:
Field: Rating
Summary Message: "Rating for Technical Knowledge is required and must be between 1 and 5."
Field Validation Message: "*"
Hopefully that illustrates what I'm trying to do. From the research the answer seems to be this isn't possible with the current data annotations framework without rolling at least one html helper on my own: either create my own ValidationSummary or my own ValidationMessage helper...

A: I wanted to elaborate on jfar's suggestion. I am not agreeing that I need to wait till MVC 3; however, his point for creating a custom model binder is actually THE ONLY way to do what I am trying to do. I've tried both field/property level attributes and class level attributes. Neither of these are sufficient for the sort of messages I need.
For example, recall that my situation is that I have a template control that is strongly typed against a model with properties Index, Heading, & Rating. So a page of these controls displayed would be something like:
Heading: Technical Knowledge
Rating: [text box]
Heading: Leadership
Rating: [text box]
Heading: Work Ethic
Rating: [text box]
...etc, etc.
For my validation messages, I wanted something very customized. It turns out my needs were too specific for the out of the box validating in MVC 2. I needed error messages for the Rating field to reference the Heading that Rating is associated with. So the validation would be something like:
The Rating for Work Ethic is required and must be a number between 1 and 5.
The Rating value of 'asdf' for Work Ethic is not valid.
The issue with field level attributes is that they didn't have access to the Heading value. Furthermore, each object actually contains an IsEditable field and should that field's value be false, I bypass validations altogether.
The issue with class level attributes is two fold. For one, I can't control the key used in the ModelStateCollection. The default is the class name and index of the object on the page. This yields a result akin to: PersonRating[0], PersonRating[1]. The problem with this is that it means you can only have 1 error message at a class level validation. If you have 2 class level attributes, they both get put into the ModelStateCollection with the same key. I'm not really sure how that works as I wouldn't think a dictionary would let you do that. Perhaps it fails silently or the second message just overwrites the first. In addition to this, I still need the fields themselves to have their css changes to denote an error. With class level validations, I could not figure out how to do this because the key does not reference a field...so I have no idea which message goes with what field unless I do hard string checks, which seems a really bad solution.
The blog post I referenced earlier does provide a solution, but it requires far too much code and effort per attribute and just seemed like overkill.
In addition to all of this, MVC data annotations has basic validations hard wired into it to sort of save you from yourself. This includes invoking a Required validator if a type on your model is non-nullable. The internal MVC validations also do data checking to ensure you're not trying to submit a string value to a int type. In both of these cases, I didn't not see a viable way to correct the validation message without doing hard checks against the validation text.
So, in the end, I wrote my own model binder for this object. While this is not the recommended way, I take comfort in that this really is the only viable solution in my case due to the internal validations hardwired in the MVC framework. My model binder looked something like below:
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Object o = base.BindModel(controllerContext, bindingContext);
            string ratingKey = bindingContext.ModelName + ".Rating";
            PersonRating pr = (PersonRating)o;
            ValueProviderResult ratingVpr = controllerContext.
                                        Controller.
                                            ValueProvider.
                                                GetValue(ratingKey);
            String ratingVal = ratingVpr.AttemptedValue;
            String ratingErrorMessage = getRatingModelErrorMessage(
                                            ratingKey,
                                            ratingVal,
                                            pr);

            if (!String.IsNullOrEmpty(ratingErrorMessage))
            {
                bindingContext.ModelState[ratingKey].Errors.Clear();
                bindingContext.ModelState.AddModelError(ratingKey, ratingErrorMessage);
            }

            return o;

                         }

The getRatingModelErrorMessage method is a custom method that performs validations on the Rating field of the PersonRating object and returns a string that represents the error message. If the string is null, no error was returned by the getRatingModelErrorMessage method.
I'll be the first to admit this isn't great code. There's always room to improve. Still it gets the job done. It's also worth noting that in situations where a value such as a text value is submitted for a non compatible type on the model, such as int, it will not be bound to the model. I am getting that value from the FormCollection via it's key.
Let me know if anyone has any suggestions on other ways this could be done or comments on the code in general. I'm always open for constructive criticism.


text:
Q: Ordered of pairs I dont know the concept or how to answer the question.

Suppose there are two sets, $X=\{1,2\}$ and $Y=\{a,b\}$.

*

*What are all the ordered pairs in the form of (element of $X$, element of $Y$)?

*What are all the ordered pairs in the form of (element of $Y$, element of $X$)?

A: To ask all the ordered pairs in a specific form essentially means you need to present all possible combinations of elements of both sets, $X$ and $Y$, in a specific order. For example, in the first case, we have that all the ordered pairs in that form are
$$
(1,a),\,\,(1,b),\,\,(2,a)\,\,\text{and}\,\,(2,b).
$$
The second answer is similar. For a more detailed answer please follow the link on the comment regarding the cross product of two sets.


text:
Q: Find all paths with cycles in directed graph, given the source vertex I'm having trouble solving this problem. I have to find all simple paths starting from a source vertex s containing a simple cycle in a directed graph. i.e. No repeats allowed, except of course for the single repeated vertex where the cycle joins back on the path.
I know how to use a DFS visit to find if the graph has cycles, but I can't find a way to use it to find all such paths starting from s.
For example, in this graph
        +->B-+
        |    v
s-->T-->A<---C
        |    ^
        +->D-+

Starting from s, the path S-T-A-B-C-A will correctly be found. But the path S-T-A-D-C-A will not be found, because the vertex C is marked as Visited by DFS.
Can someone hint me how to solve this problem?
Thanks

A: This is actually quite an easy algorithm, simpler than DFS. You simply enumerate all paths in a naive recursive search, remembering not to recurse any further any time the path loops back on itself:
(This is just a Python-inspired pseudocode. I hope it's clear enough.)
 def find_paths_with_cycles(path_so_far):
       node_just_added = path_so_far.back()
       for neigh in out_neighbours(node_just_added):
           if neigh in path_so_far:
               # this is a cycle, just print it
               print path_so_far + [neigh]
           else:
               find_paths_with_cycles(path_so_far + [neigh])

 initial_path = list()
 initial_path.append(s)
 find_paths_with_cycles(initial_path)

A: This is a common problem for garbage collection algorithms.
At a .net training, I learned that the .net garbage collector detects cycles by starting with two pointers in the graph, one of which advances at twice the speed as the other. If the fast advancing one runs into the slow one from behind, you found a cycle. It will be more involved for complex graphs, but it will work without labeling the nodes.

A: When you find a cycle, go back and unmark marked vertices as you retract past them.
Suppose you have found SABCA and want to find the next cycle. A is your final node, you should not unmark it. Go back to C. Is there another edge going out of C? No, so unmark C and go back to B. Is there another edge going out of B? No, unmark B and go back to A. Is there another edge going out of A? Yes! there's one that goes to D. So go there, mark D, go to C which is now unmarked, then to A. Here, you have found another cycle. You again retract to A, but now there are no more paths that lead out of A, so you unmark A and go back to S.

A: I went ahead and implemented Aaron's algorithm in C#.
Because it uses IEnumerable, which is lazily enumerated, you can use DirectedGraphHelper.FindSimpleCycles(s).First() if you only want the first cycle to be found:
public static class DirectedGraphHelper
{
    public static IEnumerable<Node[]> FindSimpleCycles(Node startNode)
    {
        return FindSimpleCyclesCore(new Stack<Node>(new[] { startNode }));
    }

    private static IEnumerable<Node[]> FindSimpleCyclesCore(Stack<Node> pathSoFar)
    {
        var nodeJustAdded = pathSoFar.Peek();
        foreach (var target in nodeJustAdded.Targets)
        {
            if (pathSoFar.Contains(target))
            {
                yield return pathSoFar.Reverse().Concat(new[] { target }).ToArray();
            }
            else
            {
                pathSoFar.Push(target);
                foreach (var simpleCycle in FindSimpleCyclesCore(pathSoFar))
                {
                    yield return simpleCycle;
                }
                pathSoFar.Pop();
            }
        }
    }
}

public class Node
{
    public string Id { get; private set; }
    public readonly List<Node> Targets = new List<Node>();

    public Node(string id)
    {
        this.Id = id;
    }
}

And you would use it like this:
class Program
{
    static void Main(string[] args)
    {
        var s = new Node("s");
        var t = new Node("t");
        var a = new Node("a");
        var b = new Node("b");
        var c = new Node("c");
        var d = new Node("d");

        s.Targets.Add(t);
        t.Targets.Add(a);
        a.Targets.AddRange(new[] { b, d });
        b.Targets.Add(c);
        c.Targets.Add(a);
        d.Targets.Add(c);

        foreach (var cycle in DirectedGraphHelper.FindSimpleCycles(s))
        {
            Console.WriteLine(string.Join(",", cycle.Select(n => n.Id)));
        }
        Console.Read();
    }
}


text:
Q: Can I switch between two analog references to read signals with different ranges with the ATmega328P? I want to read two voltages of different ranges with an ATmega328P ADC with the highest resolution possible:

*

*The 1st signal varies from 0 to 1V. It's the output of an LM35DZ Temperature Sensor. I wanted to use the internal 1V analog reference to get the highest ADC resolution possible.

*The 2nd signal is the battery voltage, that varies from 0 to 5V. I feed it to this Over-Discharge Protection circuit that Russell McMahon proposed and based on that reading, it will turn off the circuit if battery levels are too low. To read this signal, I have to use the ADC 5V voltage reference.
My questions are:

*

*Is it ok if I keep changing the ADC voltage reference from the internal 1V to the 5V reference to make one read then the other?

*When I switch to 1V internal reference, will the other 5V signal damage the other analog input? I got the impression that the 1V reference would be a limit for the ADC and the 5V on the other input would somehow violate this.

*I actually tried to switch between 1V and 5V reference, but when I do it, the reading of the 1st signal (with 0 to 1V range) starts fluctuating. Why is that? I tried giving the ADC time to settle (10 to 50 ms), but that didn't work. How do I get a stable reading after switching the analog reference?

A: *

*No problem at all.

*No.

*Take multiple readings and average them.  Also, the internal voltage reference isn't wonderfully stable.  Better to use an external voltage reference chip.  I often use an MCP4821 / MCP4822 DAC chip so I can program a precise voltage reference down to 500µV resolution.

A: Another option is to build a simple resistive divider for the higher voltage input to divide it down to the ADC range.  This way, even if the voltage is higher than the supply voltage for the part (say, sourced from before the voltage regulator) you can still get a good read on the voltage.  The downside to this is that you may have to worry about the resistor tolerances and temperature coefficients if you need extreme precision.  This method also allows you to read all of the input signals with the same (possibly very high precision) reference.

A: From the data sheet:

AVCC or an internal 1.1V reference voltage may be connected to the
  AREF pin by writing to the REFSn bits in the ADMUX Register. The
  internal voltage reference may thus be decoupled by an external
  capacitor at the AREF pin to improve noise immunity.

Also make sure you follow this:

By default, the successive approximation circuitry requires an input
  clock frequency between 50kHz and 200kHz to get maximum resolution.

And this:

When the bandgap reference voltage is used as input to the ADC, it
  will take a certain time for the voltage to stabilize. If not
  stabilized, the first value read after the first conversion may be
  wrong.

Just to elaborate a bit of the last quote from the datasheet... As you can see Atmel do not give you an exact figure for how long this "certain time" is. The simple reason for this is that it depends on your voltage, what cap you used to decouple AREF and probably system temp. along with other factors. What I did at the time was to take several readings and when the absolute difference between 10 consecutive reading was below a certain delta I decided the reference was stabilized. Of course this was using a constant DC input, otherwise it wouldn't make much sense. Another, simpler approach is to take a scope and sample the AREF pin. You should be able to trigger the scope on another pin at the moment you swap the voltage references and then measure how long does it take for the signal to stabilize. After you have this figured out you can set a delay in your code right after reference switching.


text:
Q: Flutter rotate widget How can I rotate the following icon 180 degree? (I want to animate it later and RotationTransition is not good choice for me)
Icon(Icons.keyboard_arrow_down)

A: Hello you can do it by simply using the Transform widget.
 Transform.rotate(
      angle: pi, // in radians
      child: Icon(Icons.keyboard_arrow_down),
  );

A: Here's how to animate a rotation, you could also stop the animation at 180° with the animationController:
import 'package:flutter/material.dart';

void main() {
  runApp(new IconRotate());
}

class IconRotate extends StatefulWidget {
  @override
  _IconRotateState createState() => new _IconRotateState();
}

class _IconRotateState extends State<IconRotate>
    with SingleTickerProviderStateMixin {
  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(
      vsync: this, //for using only a single AnimationController
      duration: new Duration(seconds: 5),
    );

    animationController.repeat();
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      alignment: Alignment.center,
      color: Colors.white,
      child: new AnimatedBuilder(
        animation: animationController,
        child: new Container(
          height: 150.0,
          width: 150.0,
          child: Icon(Icons.keyboard_arrow_down),
        ),
        builder: (BuildContext context, Widget _widget) {
          return new Transform.rotate(
            angle: animationController.value * 6.3,
            child: _widget,
          );
        },
      ),
    );
  }
}


text:
Q: Images in Java coming up NPE I was trying out putting images in java. My end goal is to make a image I can control with arrow keys, but I can't seem to put an image in. I imported the image, and I have the name correct. I keep getting a null pointer exception.
code:
import java.awt.*;
import javax.swing.*;

public class Test extends JPanel {
public static ImageIcon image;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        image = new ImageIcon(getClass().getResource("rocketJava.jpg"));
        image.paintIcon(this,g, 20, 20);

    }
    public static void main(String[] args) {
        JFrame f= new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Test s = new Test();
        f.add(s);

        f.setSize(600,600);
        f.setVisible(true);
    }
}

A: The problem was just that I needed to move the picture file to the bin folder.