text:
Q: Issue detecting textures in Unity C# I am trying to program a Unity Minesweeper game, and I am almost done, but as part of it I have a boolean variable called "isCovered" that works out if the square has been clicked or not.
This variable is used to see if the player has won yet. I have a 2d array that stores all of my squares, and to see if you win yet, it checks the array for covered, non mine squares, and if it finds them, concludes that you have not won yet.
However, when I test it, the code does not seem to find any squares that are covered, even though I can see that there are some. I concluded this because it outputs the "you win" message every time I click a safe square, even when I am not finished.
My variable is declared using this code:
public class Square : MonoBehaviour {
    //creates boolean variable
    public bool IsCovered() {
        //checks if the square still uses the default texture.
        return GetComponent<SpriteRenderer>().sprite.texture.name == "Default";
    }
}

and the code to determine if you win, which is within a different class (that is my array/grid) is:
public static bool gameWon()
{
    // Checks all squares in the array
    foreach (Square elem in elements)
        // Tries to find a covered, safe square
        if (elem.IsCovered() && !elem.dangerous)
            // The player is not finished
            return false;
    // The player has won
    return true;
}

The asset that is used for the default texture is called "Uncleared proposed", rather than "Default" so I don't know if that is an issue.
My entire "Square" code for each individual tile is:
using System.Collections;
using UnityEngine;

public class Square : MonoBehaviour
{
    //is this dangerous?
    public bool dangerous;

    //creates boolean variable
    public bool IsCovered()
    {
        //checks if the square still uses the default texture.
        return GetComponent<SpriteRenderer>().sprite.texture.name == "Default";
    }
    //different textures
    public Sprite[] emptyTextures;
    public Sprite dangerTexture;

    // Use this for initialization
    void Start()
    {
        //game randomly decides if square is dangerous
        //10% chance for initial testing
        //Chance likely to be changed at some point
        dangerous = Random.value < 0.1;

        //registers square in grid
        int x = (int)transform.position.x;
        int y = (int)transform.position.y;
        Grid.elements[x, y] = this;
    }

    void OnMouseUpAsButton()
    {
        // It's dangerous
        if (dangerous)
        {
            //uncover all mines
            //calls for procedure "uncoverDanger()" from class "Grid"
            Grid.uncoverDanger();
            //ToDo: display loss screen
            // game over
            print("Game Over");
        }
        // It's not a mine
        else
        {
            // change to correct texture
            int x = (int)transform.position.x;
            int y = (int)transform.position.y;
            loadTexture(Grid.adjacentCount(x, y));

            //Flood Fill nearby area
            Grid.FFuncover(x, y, new bool[Grid.w, Grid.h]);

            // checks if the player has won
            if (Grid.gameWon() == true)
                //tells the player they have won
                print("you win");
        }
    }

    //Loads a different texture
    public void loadTexture(int adjacentCount)
    {
        //checks to see if square is dangerous
        if (dangerous)
            //Changes to correct texture using Unity Component
            GetComponent<SpriteRenderer>().sprite = dangerTexture;
        //if not dangerous
        else
            //changes to correct texture using Unity Component
            GetComponent<SpriteRenderer>().sprite = emptyTextures[adjacentCount];
    }
}

and my Grid class code is:
using System.Collections;
using UnityEngine;

public class Grid {

    public static int w = 10; // w is the width of the grid (10)
    public static int h = 13; // h is the height of the grid (13)
    public static Square[,] elements = new Square[w, h];

    //Uncover all mines when losing
    public static void uncoverDanger() {
        foreach (Square elem in elements)
            if (elem.dangerous)
                elem.loadTexture(0);
    }

    // Determines if the square is dangerous
    public static bool dangerAt(int x, int y)
    {
        // Makes sure the square is in the range
        if (x >= 0 && y >= 0 && x < w && y < h)
            // Checks if the square is dangerous
            return elements[x, y].dangerous;
        return false;
    }

    // Counts number of dangerous squares adjacent
    public static int adjacentCount(int x, int y)
    {
        int count = 0;
        //checks adjacent squares
        //potentially adds to counter
        if (dangerAt(x, y + 1)) ++count; // top
        if (dangerAt(x + 1, y + 1)) ++count; // top-right
        if (dangerAt(x + 1, y)) ++count; // right
        if (dangerAt(x + 1, y - 1)) ++count; // bottom-right
        if (dangerAt(x, y - 1)) ++count; // bottom
        if (dangerAt(x - 1, y - 1)) ++count; // bottom-left
        if (dangerAt(x - 1, y)) ++count; // left
        if (dangerAt(x - 1, y + 1)) ++count; // top-left
        //outputs value
        return count;
    }

    // Flood Fill (FF) safe squares
    public static void FFuncover(int x, int y, bool[,] visited)
    {
        // Checks if coordinates in range
        if (x >= 0 && y >= 0 && x < w && y < h)
        {
            // Filled already?
            if (visited[x, y])
                return;

            //uncovers a square
            elements[x, y].loadTexture(adjacentCount(x, y));

            //checks if adjacencyCount is not 0
            if (adjacentCount(x, y) > 0)
                //ends algorithm
                return;

            // set square as visited
            visited[x, y] = true;
            // repeates with all 4 adjacent squares (not using diagonal)
            FFuncover(x - 1, y, visited);
            FFuncover(x + 1, y, visited);
            FFuncover(x, y - 1, visited);
            FFuncover(x, y + 1, visited);
        }
    }

    public static bool gameWon()
    {
        // Checks all squares in the array
        foreach (Square elem in elements)
            // Tries to find a covered, safe square
            if (elem.IsCovered() && !elem.dangerous)
                // The player is not finished
                return false;
        // The player has won
        return true;
    }
}

I am a real newbie to unity so it might be something stupid, any help would be greatly appreciated.

A: Turns out I am an idiot, I just had to change the name of the texture in the variable code to "Uncleared proposed", I don't know why it didn't work earlier.


text:
Q: An error occurred while installing pg (0.12.2), and Bundler cannot continue I'm following the Michael Hartl Ruby on Rails Tutorial & there is a part where he is he he instructs you to update your Gemfile to include:
group :production do
  gem 'pg', '0.12.2'
end

And then enter the below commands in your terminal:
bundle update
bundle install --without production

When you run the bundle update command it throws back the below errors.
sample_app:$ bundle update
Fetching gem metadata from https://rubygems.org/.........
Fetching gem metadata from https://rubygems.org/..
Resolving dependencies...
Using rake (10.0.3)
Using i18n (0.6.4)
etc
[omitted lines for brevity]
etc
Using railties (3.2.12)
Using coffee-rails (3.2.2)
Installing diff-lcs (1.1.3)
Using jquery-rails (2.0.2)
Installing pg (0.12.2)
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

        /home/ross/.rvm/rubies/ruby-1.9.3-p392/bin/ruby extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    etc
    [omitted lines for brevity]
    etc

Gem files will remain installed in /home/ross/.rvm/gems/ruby-1.9.3-p392/gems/pg-0.12.2 for inspection.
Results logged to /home/ross/.rvm/gems/ruby-1.9.3-p392/gems/pg-0.12.2/ext/gem_make.out

An error occurred while installing pg (0.12.2), and Bundler cannot
continue.
Make sure that `gem install pg -v '0.12.2'` succeeds before bundling.
sample_app:$

I was able to overcome this error easily be removing the 'pg', '0.12.2' gem from the Gemfile & replacing it after running the bundle update command.   This seems to work fine as the 'pg', '0.12.2' gem is aslo omitted in the without production flag in the latter bundle install --without production.
The 'pg', '0.12.2' gem is only needed for deploying to heroku with the correct database & everything works fine even when I deployed it to heroku but I'm just wondering if this is  an error in the Tutorial or am I missing something bigger here?
It's also annoying to have to remove this Gem everytime I run bundle update, is bundle update really that necessary?
Thanks in Advance

A: I'm following the same tutorial and I think it's redundant to run update without modifying existing dependency, but in this case it's even causing problems because update command has not --without argument.
I stumbled upon Rails 3 cheatsheet which mentions bundler workflow this way:

After adding or removing dependencies from Gemfile

*

*$ bundle

*Commit Gemfile and Gemfile.lock

  After modifying existing dependency versions

*

*$ bundle update

*Commit Gemfile and Gemfile.lock

I read man pages for bundle update and tried RECOMMENDED WORKFLOW which consists of running bundle update after bundle install.
In my case (some output omitted):
$ bundle install --without production
Resolving dependencies...
Using rake (10.0.3)
...
Installing rspec-core (2.11.1)
Your bundle is complete!
Gems in the group production were not installed.             <-- check

$ bundle update
Resolving dependencies...
Using rake (10.0.3)
...
Using uglifier (1.2.3)
Your bundle is updated!
Gems in the group production were not installed.             <-- check

I tried it with new RVM gem set and everything was installed correctly.
After that Gemfile.lock contains pg (0.12.2) and deploying to Heroku works.

RECOMMENDED WORKFLOW

In general, when working with an application managed with bundler, you
    should use the following workflow:
After you create your Gemfile for the first time, run
$ bundle install
Check the resulting Gemfile.lock into version control
$ git add Gemfile.lock
When checking out this repository on another development machine, run
$ bundle install
When checking out this repository on a deployment machine, run
$ bundle install --deployment
After changing the Gemfile to reflect a new or update dependency,
    run
$ bundle install
Make sure to check the updated Gemfile.lock into version control
$ git add Gemfile.lock
If bundle install reports a conflict, manually update the specific
    gems that you changed in the Gemfile
$ bundle update rails thin
If you want to update all the gems to the latest possible versions
    that still match the gems listed in the Gemfile, run
$ bundle update

A: Installation of postgres fails with this error : "Can't find the 'libpq-fe.h header"
Looks like a lot of people faced this problem, good news is : stackoverflow has the answer ;)
Can't find the 'libpq-fe.h header when trying to install pg gem
(or at least it should help you to look in the right direction)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to position two tabularray tables side by side in such a way that their top edges align? A description of the problem
I would like to present two tables of different row numbers side by side in such a way that the top edges of the tables' first rows would lie along the same (imaginary) horizontal line.
TeX-wise the two tables are coded as tblrs of package tabularray.
An attempt at a solution
I tried to solve the problem by embedding the two tables as the left and right cells inside another tblr table consisting of a single, two column row, and then setting the vertical alignment of the cells of the external table to 't'. As follows.
I saved the following LaTeX code in ~/Test.tex.
\documentclass{article}
\usepackage{tabularray}
\begin{document}
\begin{tblr}{Q[c,t]Q[c,t]}
\begin{tblr}{c}
A
\end{tblr}
&
\begin{tblr}{c}
A\\
B
\end{tblr}
\end{tblr}
\end{document}

I then executed the following commands in the Terminal.
> cd ~
> lualatex Test

This resulted in the file ~/Test.pdf being created. When opened in a PDF viewer the file displayed as follows. (I screenshot only the relevant part of the display.)

As can be seen, this didn't have the desired effect. If the top edges of the first rows of the two inner tables were aligned, then presumably the two letters A would align in such a way that their baselines would be lying on the same (imaginary) horizontal line. But this is not the case. Instead the left A is lower on the page than the right A.
Question
How can two tblr tables of different row numbers be positioned side by side on the page in such a way that the top edges of their first rows align along an imaginary horizontal line?

A: You can set the baseline to top (T) to align the tables:
\documentclass{article}
\usepackage{tabularray}
\begin{document}
\begin{tblr}{cc}
    \begin{tblr}[T]{c}
        A
    \end{tblr}
     &
    \begin{tblr}[T]{c}
        A \\
        B
    \end{tblr}
\end{tblr}
\end{document}

The option T aligns the first row of the table, whereas t aligns the top of the table. For more, see sec. 3.1.6 in the manual

A: This answer will address the question of why the attempt shown in the original post of using the specification Q[c,t]Q[c,t] failed. The implementation details described below are for explanation purposes only; I have no idea if they reflect the actual implementation of the tabularray package.
When a tblr has two or more cells in a certain row, these cells can be vertically aligned relative to each other using the vertical alignment specifications t, m, and b. (Also h and f, but they are mere aliases of b and t, respectively.)
tblr wraps the content of each of the row's cells inside a box, one box per cell. We will refer to these boxes as alignment boxes. Each of the alignment boxes has a baseline, and tblr aligns these boxes along their baselines.
When the content of one of the cells consists of a single line of text, the vertical alignment specification for this cell is ignored, and the baseline of the alignment box coincides with the single line's baseline.
However, when the content of one of the cells consists of two or more lines of text, the baseline of this cell's alignment box is determined by the vertical alignment specification for this cell (which is t by default): If the specification is t, the alignment box's baseline is that of the top line; if the specification is b, the alignment box's baseline is that of the bottom line; if the specification is m and the number of lines is odd, the alignment box's baseline is that of the middle line; and if the specification is m and the number of lines is even, the alignment box's baseline is half way between the baselines of the two middle lines.
Each tblr has a bounding box with a baseline. By default this baseline is the middle of the tblr's bounding box. The position of this baseline can be specified using tblr's baseline option, which can be passed as either an inner specification (i.e. to tblr's mandatory argument) or as an outer specification (i.e. to tblr's optional argument). The possible values of this option are t, T, m, b, B, and <n> for some positive integer n. If the value of this option is t, the tblr's baseline is the top edge of its bounding box, if the value is T it is the baseline of the tblr's first row, if it is m it is the vertical middle of the bounding box, if it is b it is the bottom edge of the tblr's bounding box, if it is B it is the baseline of the tblr's bottom row, and if it is <n> it is the baseline of the tblr's nth row.
Putting all this information together, when a tblr has a row with two or more cells, and the content of one of them is itself a tblr, then, regardless of the vertical alignment specification for this cell, the baseline of this cell's alignment box will coincide with the baseline specified (explicitly or by default) for the inner tblr, since the content of this cell consists of a single line of text, namely the line comprising a single box: the inner tblr's bounding box. And this line's baseline is therefore the baseline of the inner tblr's bounding box.
Applying this to your example from the original post, each of the external tblr's cells consists of a single line of text comprising the respective inner tblr. Therefore, the external tblr's vertical alignment specifications for these cells are ignored, and the baselines of the two cells' alignment boxes are set to coincide with those of these lines, respectively. These baselines, in turn, coincide with the baselines of the respective inner tblr's bounding boxes. Since no baselines have been specified for the two inner tblrs explicitly, their baselines are set by default to m, i.e. their baselines are at the vertical middles of their respective bounding boxes. Therefore, the two tables are vertically aligned along their respective vertical middles.

A: There are situations, I would explicitly set the baseline of each sub-table to say row 1 and apply an inner alignment across such headers. For instance the table below contain headers with multiple lines of different size, while Q[c,b] aligns tables w.r.t to a bottom line of each header.
\documentclass{article}
\usepackage{tabularray}
\begin{document}
\begin{tblr}{c}
  \begin{tblr}{
      baseline=1,
      colspec={Q[c,b]},
      hline{2},
    }
    {Header Line 1\\Header Line 2\\Header Line 3} \\
    Line 1 \\
    Line 2
  \end{tblr}
  &
  \begin{tblr}{
      baseline=1,
      colspec={Q[c,b]},
      hline{2},
    }
    {Header Line 1\\Header Line 2} \\
    Line 1 \\
    Line 2 \\
    Line 3
  \end{tblr}
\end{tblr}
\end{document}


text:
Q: Samba AD GPO "Display information about previous logons during user logon" does not apply and makes it impossible to logon We are performing tests to deploy a Univention UCS domain with samba Active Directory in our company and, to comply with a security normative, we need to activate the GPO "Display information about previous logons during user logon" found in "Computer Configuration > Administrative Templates > Windows Components > Windows Logon Options".
I have been testing but I can't get it to work correctly. The result I get is that, on the computers that I apply the GPO, during login it shows me an error and I can't log in. The error message is "Security policies on this computer are set to show info about the last interactive sign-in, but Windows couldn't retrieve that info. Contact your network administrator for help."
I have found on the internet that this policy only works with a domain functional level equal or higher than 2008, so this is not the problem, since samba-ad has a domain functional level of 2008 R2.
I also found that the policy must be applied to the domain controller for it to work correctly, but I have also tried it and I can't get it to work, I keep getting the same error.
Before trying Univention UCS we configured an Active Directory with samba4 on a Debian 11, but the result is the same.
Could someone tell me why this GPO is failing and how to fix it? And, in case it is not possible, how can I get something similar to what this policy does in some other way, such as through a script at login or similar?
Best regards.

A: I can tell you from my own experience, that this GPO is dangerous. It malfunctions sometimes for no apparent reason and shows what you see. In fact, it just did yesterday on a machine here. Domain functional level is server 2016 and we have been using it for years. Without any change, it malfunctioned on just one client and this client had to be excluded from the GPO! Same happened some months ago in my lab domain for no apparent reason on just one machine as well. I don't trust that GPO anymore. By the way: it does not work with anything but passwords anyway (for example, with SmartCard-logon, it does not work).


text:
Q: XmlElement not working in interface I was trying to deserailize an object to generic list, Property marked with [XmlElement("ProcessName")] return null with interface but it works when [XmlElement("ProcessName")] is applied to class property.When the [XmlElement("ProcessName")] is removed from class pName property it returns null even though interface is marked with [XmlElement("ProcessName")]
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfProcess xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Process>
<Id>1</Id>
<ProcessName>Top Mold</ProcessName>
<ProcessCode>120</ProcessCode>
</Process>
<Process>
<Id>2</Id>
<ProcessName>Bottom Mold</ProcessName>
<ProcessCode>10</ProcessCode>
</Process>
<Process>
<Id>5</Id>
<ProcessName>Cooling</ProcessName>
<ProcessCode>110</ProcessCode>
</Process>
<Process>
<Id>6</Id>
<ProcessName>Heating</ProcessName>
<ProcessCode>310</ProcessCode>
</Process>
</ArrayOfProcess>

Interface and class`
 public interface IProcess
{
    [XmlAttribute]
    int Id { get; set; }

    [XmlElement("ProcessName")]
    string pName { get; set; }

    [XmlAttribute]
    string ProcessCode  { get; set; }
}

public class Process : IProcess
{
    public int Id { get; set; }

    [XmlElement("ProcessName")]
    public string pName { get; set; }

    public string ProcessCode { get; set; }
}

   public List<T> GenericDeSerialize<T>(string xml)
    {

        //Creating XmlSerializer for the object
        XmlSerializer serializer = new XmlSerializer(typeof(List<T>));

        //Geting XMl from the file.
        TextReader tr = new StringReader(xml);

        //Deserialize back to object from XML
        List<T> b = (List<T>)serializer.Deserialize(tr);
        tr.Close();
        return b;
    }


text:
Q: Backward compatibility for iOS build SDKs I would like to run old application which has a support of iOS 5.0 and less. It has a deployment target 5.0. The thing is that:
I have upgraded system to Yosemite OS 10.10 and lowest Xcode version I have 5.0. Now when I look on base SDK and I see below picture.

As you see the least build SDK shown s  iOS 7.0. No other lower version is there.
I heard or I read some where that you can also use lower version SDK here. By copying SDKs to some where or any other means. I would like to know a better approach here.
Edit:
I have a requirement of one application which was developed in Xcode 4.6 for iOS 5.0. So that just to check that application flow I need to download Xcode 4.6. Is it so? Can we don't include older SDKs in newer version of Xcode?

A: You should not attempt to build your application with an old version of Xcode. The only version of Xcode supported on Yosemite is Xcode 6.1, which only ships with the iOS 8 SDK. You should build for the latest SDK, and set the Deployment Target to iOS 5 if you want your code to run there (by degrading gracefully using NSClassFromString and respondsToSelector: checks)


text:
Q: Dialog box appear that only characters are allowed but after click ok on dialog box numeric also entered in text fields Numeric also enters in name text fields, this code is not working properly.  Please help me by example.
   Name_text.addKeyListener(new KeyAdapter() {

        @Override
        public void keyTyped(KeyEvent e) {
           if(e.getKeyChar()>='0'&& e.getKeyChar()<='9'|| e.getKeyChar()>=33&& e.getKeyChar()<=47|| e.getKeyChar()>=58&& e.getKeyChar()<=64 || e.getKeyChar()>=91&& e.getKeyChar()<=96 || e.getKeyChar()>=123&& e.getKeyChar()<=127 ){
          JOptionPane.showMessageDialog(null, "enter characters only");
        }
        }
           });

A: There are much better ways to accomplish what you want.
Check out JFormattedTextField

A: The code you posted only shows a dialog complaining that numbers are not allowed (with an ugly check, what was wrong with the regex [0-9] ) but it does not remove the input.
Further, as stated in other answers there are built-in validation mechanisms or better ways then using a KeyListener:

*

*JFormattedTextField is the text field for validating user input. It requires a few tweaks to improve the usability (see for example this blogpost)

*Use an InputVerifier. No link here as I am no fan of this mechanism. Just mentioning it for completeness

*Use a DocumentListener instead of a KeyListener, which allows to suppress certain input, and will also work when using Drag-and-Drop or copy-paste which is not the case for your KeyListener
Examples can be found in the links.


text:
Q: Flutter - Notificacion push personalizada con una imagen de la app Quiero mostrar el icono de la app en una notificacion push. Ya tengo todas las configuraciones y las notificaciones push estan funcionando. Pero necesito colocar el icono de la app.

Uso la libreria de firebase en el archivo pubspec.yaml
firebase_messaging: ^6.0.1

He buscado en google pero no encuentro alguna guia en Flutter,
Gracias de antemano
EDIT.
parte de mi codigo que recibe la notificacion push
FirebaseMessaging _fcm = FirebaseMessaging(); // variable global
...

class Start extends StatefulWidget {
  final FirebaseApp app;

  Start({Key key, this.app}) : super(key: key);

  @override
  _InicioState createState() => _InicioState();
}

class _StartState extends State<Start> {

  DatabaseReference _messagesRef;

  @override
  void initState() {
    super.initState();
    _fcm.configure(
      onMessage: (Map<String, dynamic> message) {},
      onResume: (Map<String, dynamic> message) {},
      onLaunch: (Map<String, dynamic> message) {},
    );
    _fcm.subscribeToTopic('notificaciones');
    getToken();
   }
  ...
 }

A: Para recibir imágenes en la notificación , tienes que enviarlo desde el server dentro del campo notification.
https://firebase.google.com/docs/cloud-messaging/android/send-image
{
  "message":{
    "token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
     "android": {
       "notification": {
           "body" : "This is an FCM notification that displays an image.!",
           "title" : "FCM Notification",
           "image": "url-to-image"
       }
   }
}

Ojo que estas notificaciones solo las verás cuando la app está en background, si deseas mostrar una notificación cuando la app está en foreground,  tienes que adicionar este plugin:
https://pub.dev/packages/flutter_local_notifications , donde puedes guiarte de este ejemplo : https://github.com/MaikuB/flutter_local_notifications/blob/master/flutter_local_notifications/example/lib/main.dart


text:
Q: What is the problem with this query? I am trying to create a practice small table with some primary id to do matching but I don't find the error here Small table to practice id matching.
CREATE DATABASE test_1;
USE test_1;

CREATE TABLE test_items(

contact_id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR (20) ,
last_name VARCHAR (20),
PRIMARY KEY (contact_id)
);

INSERT INTO test_items()

VALUES (
(NULL, 'Javier','Droid'),
(NULL,'Gret','Jun'),
(null,'Kilot','Ramirez')

);
SELECT * FROM test_items;

A: Always specify the column names you are inserting:
INSERT INTO test_items(first_name, last_name)
VALUES ('Javier','Droid'), ('Gret','Jun'), ('Kilot','Ramirez');

SELECT * FROM test_items;


text:
Q: Trying to understand a method in this code Now I found this code online and I found it interesting, the loop has quite a good function and it was well although for me I had issues with some parts.  understand what he is trying to do here:
int pos = -1;
int index = 0;
while(pos == -1 && index < network.size()){
     if(network.get(index).getName().equals(current))
          pos = index;
          index++;
     }

So i wondered why didnt he use this
int pos = -1;
int index = 0;
while(pos == -1 && index < network.size()) {
    if(network.get(index).getName().equals(current)) {
         pos = index;
    }
    index++;
    .
    .
    .
}

A: You missed the indentation. What you want is exactly what he did. The only difference is that he omits the brackets.
Without brackets
while(pos == -1 && index < network.size()){
    if(network.get(index).getName().equals(current))
        pos = index;
    index++;
}

With brackets
while(pos == -1 && index < network.size()){
    if(network.get(index).getName().equals(current)) {
        pos = index;
    }
    index++;
}


text:
Q: error in while loop with sed I have a file I want to parse:
mmu-miR-15-5p/16-5p/195-5p/424-5p/497-5p    0610007P14Rik
mmu-miR-326-3p/330-5p   0610007P14Rik
mmu-miR-326-3p/330-5p   Lmir
mmu-miR-15/16/195/424/497   0610007P14Rik
mmu-miR-15-5p/16-5p/195-5p/424-5p/497-5p/6838-5p    0610007P14Rik
mmu-miR-15/16/195/424-5p/497    Alinf
mmu-miR-326/330-5p  0610007P14Rik
mmu-miR-326/330 0610007P14Rik
mmu-miR-1/206/613   Crgi
mmu-miR-1-3p/206    0610007P14Rik

the desired output:
for the first line
mmu-miR-15-5p   0610007P14Rik
mmu-miR16-5p    0610007P14Rik
mmu-miR195-5p   0610007P14Rik
mmu-miR424-5p   0610007P14Rik
mmu-miR497-5p   0610007P14Rik

and so on...
I just need to replace / with mmu-miR and create a new line along with their second column.
I tried with following one line code on bash:
sed 's/\//\nmmu-miR/g' test.txt

mmu-miR-15-5p
mmu-miR16-5p
mmu-miR195-5p
mmu-miR424-5p
mmu-miR497-5p   0610007P14Rik
mmu-miR-326-3p
mmu-miR330-5p   0610007P14Rik
mmu-miR-326-3p
mmu-miR330-5p   Lmir

I tried to use a while loop and this sed command:
while read line; do
    lineCols=( $line );
    v1=($(echo "${lineCols[0]}"));
    v2=($(echo "${lineCols[1]}"));
    sed 's/\//\n/g' ${v1};
done <test.txt

but got an error:
sed: can't read mmu-miR-15-5p/16-5p/195-5p/424-5p/497-5p: No such file or directory
sed: can't read mmu-miR-326-3p/330-5p: No such file or directory
sed: can't read mmu-miR-326-3p/330-5p: No such file or directory
sed: can't read mmu-miR-15/16/195/424/497: No such file or directory
sed: can't read mmu-miR-15-5p/16-5p/195-5p/424-5p/497-5p/6838-5p: No such file or directory

What am I doing wrong?

A: How to achieve this with awk
For better readability/ease of use, create a awk script (myScript.awk) with following content:
{
  n=split($1, a, "/")
  split(a[1], b, "-")

  for (i=1; i<n+1; i++) {
    if (i == 1) {
      printf a[i]"\t"$2"\n"
    }
    else {
      printf b[1]"-"b[2]"-"a[i]"\t"$2"\n"
    }
  }
}

How it works:
n=split($1, a, "/")

This line takes the first field (for example "mmu-miR-15-5p/16-5p/195-5p/424-5p/497-5p" for the first line), splits it with separator "/", stores it in array a and stores the number of elements split in n. For the first line:
a[1] = "mmu-miR-15-5p"
a[2] = "16-5p"
a[3] = "195-5p"
a[4] = "424-5p"
a[5] = "497-5p"
n = 5

Remember awk instructions are executed for every line so the result will be different for the next line !
split(a[1], b, "-")

Similarly, this line takes the first element of a and splits it with separator "-". This yields:
b[1] = "mmu"
b[2] = "miR"
b[3] = "15"
b[4] = "5p"

Once we have those arrays, all we need to do is loop over the number of output lines (number of "/" separated elements in an input line) and construct each line with bits of arrays a and b! We have to make an exception for the first line because a[1] already contains "mmu-miR-" hence the if to differentiate that case !
How to run it
awk -f myScript.awk input.txt

Tested it, it does output what you ask for in your question.
NOTE
As stated in my comment on your question, using a single awk invocation is way more efficient and "shell-friendly" than looping on every line of your file.
EDIT NOTE
I have modified the script following your comment. Should be fine now !

A: I think you're looking for something like that:
cat inputFile.txt | while read line
    do
        eval `echo "$line" | sed 's|^\([^/]*\)/\([^ ]*\) \(.*\)|name="\1" ports=\2 tag="\3"|'`
        echo "$name $tag"
        realname=`echo "$name" | sed 's|-[0-9].*||'`
        for port in $(echo $ports | sed 's|/| |g')
        do
            echo "$realname-$port $tag"
            #or echo "$realname$port $tag", but I suspect a typo in your initial post
        done
    done

A: Assuming that the input is a header-less TSV file (i.e. a tab-delimited file with no header line(s)), then you may read it as such with Miller (mlr) and "un-nest" each record by the /-delimited strings in the first field. You may then prepend the string mmu-miR- to each value in the 1st field that does not already have it:
$ mlr --tsv -N nest --evar '/' -f 1 then put -S '$1 !=~ "^mmu-miR-" { $1 = "mmu-miR-" . $1 }' file
mmu-miR-15-5p   0610007P14Rik
mmu-miR-16-5p   0610007P14Rik
mmu-miR-195-5p  0610007P14Rik
mmu-miR-424-5p  0610007P14Rik
mmu-miR-497-5p  0610007P14Rik
mmu-miR-326-3p  0610007P14Rik
mmu-miR-330-5p  0610007P14Rik
mmu-miR-326-3p  Lmir
mmu-miR-330-5p  Lmir
mmu-miR-15      0610007P14Rik
mmu-miR-16      0610007P14Rik
mmu-miR-195     0610007P14Rik
mmu-miR-424     0610007P14Rik
mmu-miR-497     0610007P14Rik
mmu-miR-15-5p   0610007P14Rik
mmu-miR-16-5p   0610007P14Rik
mmu-miR-195-5p  0610007P14Rik
mmu-miR-424-5p  0610007P14Rik
mmu-miR-497-5p  0610007P14Rik
mmu-miR-6838-5p 0610007P14Rik
mmu-miR-15      Alinf
mmu-miR-16      Alinf
mmu-miR-195     Alinf
mmu-miR-424-5p  Alinf
mmu-miR-497     Alinf
mmu-miR-326     0610007P14Rik
mmu-miR-330-5p  0610007P14Rik
mmu-miR-326     0610007P14Rik
mmu-miR-330     0610007P14Rik
mmu-miR-1       Crgi
mmu-miR-206     Crgi
mmu-miR-613     Crgi
mmu-miR-1-3p    0610007P14Rik
mmu-miR-206     0610007P14Rik

The first Miller sub-command, nest, is here used to "un-nest" or "explode" the records into further records by splitting up the 1st field on slashes and duplicating the other fields (only one other field in this case) once for each generated string.
The second Miller sub-command, put, tests whether the value in the resulting 1st field starts with the correct prefix string and adds it if it doesn't.  The -S option with put stops Miller from inferring a type on the fields and will treat all fields as text.

Given the input in the question, we may get the same result using awk like so:
awk -F '\t' '
    BEGIN { OFS=FS }
    {
        nf = split($1,a,"/")

        print a[1], $2
        for (i = 2; i <= nf; ++i)
            print "mmu-miR-" a[i], $2
    }' file

This also reads the file as a tab-delimited file and splits the 1st field on slashes, generating a set of new strings in the array a. It then prints the first generated string together with the 2nd field before iterating over the remaining generated strings, prepending each with the missing mmu-miR- prefix, and outputting them with the value from the 2nd field.


text:
Q: Doubts with the conversion that pandoc does I have migrated a large document from InDesing to .html and then passed that document to .tex using pandoc.
The conversion is almost perfect, I just have to correct a few things manually.
In the content I have two doubts:

*

*In the case of ... pandoc does this conversion: \ldots{}

*And when there is content with [ and with ] pandoc places it like this: {[}Lorem ipsum{]}
Since I am correcting all the content and this I can easily fix with find / replace I want to know if there are any specific rules in LaTeX regarding (1) and (2).
With respect to what is exposed in (1), I suppose that the correct way is as pandoc puts it, because in a manual test, if I do not put {} at the end, it does not respect the white space that would follow, then Lorem\ldots ipsum will print: Lorem...ipsum.
With respect to what is exposed in (2), I do not see any difference.


text:
Q: Drivers for monitor lenovo y27-20q I want to connect 2 monitors one with HDMI and one with display port, the one with the HDMI cable is a basic dell display 1920:1080 and the one with the display port has a 2K resolution. the monitor with the display port is not working, Ubuntu does see it but the screen on it is black. when I first installed Ubuntu i had only a dell display connected and it was not the one I'm using currently but the one I'm using right now still works.
I updated the Nvidia GTX 1080 drivers to the latest version I saw on the list that Ubuntu suggests and now the computer would not boot into Ubuntu and only windows works. its a lenovo legion cube and the display using the display port is a lenovo y27 - 20q display. when my computer still booted into Linux that's what was happening:
if i restart my computer with the two monitors connected to it i will just see a black screen. Ubuntu does not recognize my second monitor no matter what i do. it is just black and goes to sleep. although i see it in the monitors tab in the settings menu it does not show anything when i try to set it as my main monitor. can someone please help me manually connect the drivers to the display like we do in Windows? (device manager and then manually select drivers)


text:
Q: Tool that draws Venn diagram from subset relation Is there a tool (LaTeX, JavaScript, Mathematica..) that allows one to draw Venn diagram automatically from subsets relations, e.g.
$$A\subset A+B$$
$$A\subset C$$
$$C\subset C+D$$
$$B \not\subset C$$
woud yield
------------------------------------------------
|                      C+D                     |
|                                              |
|  ------------------------------------------  |
|  |         A+B       |          C         |  |
|  |                   |                    |  |
|  |                   |                    |  |
|  |  ------------------------------------  |  |
|  |  |                                  |  |  |
|  |  |                A                 |  |  |
|  |  |                                  |  |  |
|  |  ------------------------------------  |  |
------------------------------------------------

(Sorry for the pitiful Ascii drawing)

A: https://tex.stackexchange.com/questions/9681/how-to-draw-venn-diagrams-especially-complements-in-latex  answers it in latex but I couldn't get their answer to work in my answer, as it used tikzpicture ( seems unsupported here).


text:
Q: When a block slides down an incline, why does the incline move back, if the work is done by an external force (gravity)? If I put a point mass on the top of the incline, and if all surfaces are frictionless, I heard, that the incline is going to move back a little (depending on the mass difference), because momentum is conserved and velocity of the center of mass should remain constant. How is this possible though when, it's the gravity (an external force) which is acting on the mass?

A: The block is pulled vertically downwards by gravity. But it can't move vertically due to the slope. It will have to break through the slope surface in order to do so.
The particles that the sloped object consist of are bonded both vertically and horizontally with chemical forces in molecular or crystalline or similar grids or patterns. Pushing one such particle or atom down vertically, will envoke horizontal forces that pull and prevent the motion in order to hold it in place.
This is where the horizontal forces come from. At the macroscale we see all these forces that together prevent that the object breaks apart merging into what is called the normal force. It always acts perpendicular to the surface, since there will typically be material symmetry across such perpendicular direction. The horizontal component of this normal force represent the horizontally pushing or pulling interchemical forces.
With such normal force pushing on the sliding block, the block will from a similar line of arguments necessarily exert a matching (equal but opposite) total normal force the other way. This is Newton's third law. This normal force also has a horizontal component, and it is this component that pushes the slope sideways.

A: I think you might be considering a special case. If the ramp itself is supported on frictionless rollers at its base, then I can see that what you describe would happen.
However, this is a special case. If the ramp is rigidly fixed to a table which itself cannot move relative to the Earth and is itself rigid then it will not move, except to the extent that it deforms elastically.

A: As @Triatticus rightly mentioned, there is no external force in the horizontal direction. Hence the COM's x coordinate (assuming an x-y plane with x axis along the horizontal direction) should stay constant. Now as the point mass is moving away from, the incline plane has to compensate for that and hence it moves in the opposite direction. Depending on the mass differences, how far both the bodies move can be calculated.


text:
Q: Definir nome campo virtual Tenho o seguinte código no meu model SubGrupo:
namespace Aplicacao.Core.Dominio
{
    public class SubGrupo
    {
        [Key]
        public int Codigo { get; set; }

        [Required(ErrorMessage = "Campo Obrigatório.")]
        public string Descricao { get; set; }

        public virtual TipoFormulario TipoFormulario { get; set; }
    }
}

Model TipoFormulario
namespace Aplicacao.Core.Dominio
{
    public class TipoFormulario
    {
        [Key]
        public int Codigo { get; set; }

        [Required(ErrorMessage = "Campo Obrigatório.")]
        public string Descricao { get; set; }
    }
}

No caso, a Keydo model TipoFormulario é Codigo. Por isso no banco é gerado TipoFormulario_Codigo
Como posso definir o nome que será gerado ? Gostaria de nomear a coluna para TipoFormulario

A: Assim:
namespace Aplicacao.Core.Dominio
{
    public class SubGrupo
    {
        [Key]
        public int Codigo { get; set; }
        [Column("TipoFormulario")]
        [ForeignKey("TipoFormulario")]
        public int TipoFormularioId { get; set; }

        [Required(ErrorMessage = "Campo Obrigatório.")]
        public string Descricao { get; set; }

        public virtual TipoFormulario TipoFormulario { get; set; }
    }
}


text:
Q: JWT Token Not Being Received by API (React Native -> Apollo -> Next.js API) I had an app that was working as expected, but due to some complications with management, we had to transfer git ownerships, repos, and change accounts on Vercel and PlanetScale. I do not know if this has anything to do with my issue, but it was the only change before this issue began.
Currently, I am unable to properly log into my app. This is because the Login / Signup will only return a user's token. The token is then immediately taken, put into the Native Device's AsyncStorage, saved into a recoil state, and then sent back to the API for any and all future queries / mutations. Then, the Native App calls for the GET_USER query which is what returns all of the user data. This step never works, however, because despite the Native app saving and holding the token, the API never receives it.
I am using React Native to create the front-end, and the backend is powered by Next.js and runs on Vercel, connected to a PlanetScale Database using prisma.
Inside the Native project's App.js file, I have the following connection set up (which had worked in the past)
////////////////////////////////
// Apollo Linking Information //
////////////////////////////////

  // Create HttpLink for Apollo
  const httpLink = createHttpLink({
    uri: 'https://xxxxxxxxxxxxxxxx.app/api/graphql' // Live
    // uri: 'http://localhost:3000/api/graphql' // Local
  });

  // Creates the Authorization Link
  const authLink = setContext( async (_, { headers }) => {
    const token = await AsyncStorage.getItem('@token')
    console.log("TOKEN IN HEADER ::: ", token)
    return {
      headers: {
        ...headers,
        authorization: token
      }
    }
  })

  // Initialize Apollo Client (Connection Object for Apollo API)
  const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
  });

return(
    <ErrorBoundary
    onError={(error) => console.error("\nAPP.JS ERROR REPORTING REPORTING\n", error)}
    >
      <NavigationContainer>
        <ApolloProvider client={client}>

         // The rest of the app //

        </ApolloProvider>
      </NavigationContainer>
     </ErrorBoundary>

Note that right before the error occurs, setting that there was no authorization sent, the line console.log("TOKEN IN HEADER ::: ", token) successfully prints the token
Inside of the API, I test again to make sure it truly is an issue with the context. Low and behold, it is, as this is what the GET_USER query looks like...
export default {
  Query: {
    getUser: async (_, {}, context) => {

      console.log("GET_USER CONTEXT ::: ", context)

      /////////////////
      // LOGIN CHECK //
      if (!context.user) throw new UserInputError("Login required");

      // Rest of the Query irrelevant since it never even gets hit //

    }
  }
}

I sincerely have no idea why this could be happening, everything else is properly linked up, the token is clearly getting received by the Native App from the API after I run either signup or login so why is the token just getting lost?


text:
Q: Azure still haven't provide REST API for Adding co-admin Right? I can list all my admin/co-admin eamail accounts by :
List Subscription User Accounts
But I didn't found any API for adding a eamail account to Azure co-admins.
Does this API exist?


text:
Q: Azure Pipelines - apply Build Number into App Settings I have a Build and Release pipelines setup for a project and I want to be able to get the Build Number that was used for the Release into the running application.
I've seen a number of explainations of how to use the Release.Artifacts.{alias}.BuildNumber variable for things like the artifact output, however I haven't been able to find how to use this to directly update the App Settings for the App Service.
I've found a few Tasks available to use in the Release process that allow changing of App Settings, but none of them supported using variables from the build process (just allow setting of static values)
I want this to be set at the App Service level so that the website and all the webjobs are able to access the variable (rather than having to update several app.config files).
Can anyone point me in the right direction for this?

A: Delay in updating this, however this is the Powershell based solution I arrived at and this has been working well so far.
Added this as a Powershell script within the solution and updated the Build process to copy this artifact
param (
    $myResourceGroup,
    $mySite,
    $mySlot,
    $buildNo
)

$webApp = Get-AzureRMWebAppSlot -ResourceGroupName $myResourceGroup -Name $mySite -Slot $mySlot
$appSettingList = $webApp.SiteConfig.AppSettings

$hash = @{}
ForEach ($kvp in $appSettingList) {
    $hash[$kvp.Name] = $kvp.Value
}

$hash['BuildNumber'] = $buildNo

Set-AzureRMWebAppSlot -ResourceGroupName $myResourceGroup -Name $mySite -AppSettings $hash -Slot $mySlot

This takes the parameters provided and retreives the current App Settings from the slot and adds/updates the BuildNumber setting to the $buildNo parameter that is received.
During the Release process, I added in an Azure Powershell task to call this script and then set the "Script Argurements" field to the following
-myResourceGroup "WebResourceGroup" -mySite "myexamplservice" -mySlot "staging" -buildNo $(Build.BuildNumber)

Now I can read the "BuildNumber" app setting within my website and get the deployed build number.

A: If you want to set the AppsSettings directly against the website without using an XML transform on the web.config, then you would need to go down the route of applying an ARM template.
Here's how you can do that via Pipelines:

*

*Grab the ARM template for your site from the portal

*Edit the template to accept a new buildNumber variable, and set this in the app settings for the site e.g.
{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "buildNumber": {
      "type": "string"
    }
  },
  ...
  "resources": [{
    "type": "Microsoft.Web/sites",
    ...
    "properties": {
      "siteConfig": {
        "appSettings": [
          {
            "name": "BUILD_NUMBER",
            "value": "[parameters('buildNumber')]"
          },
          ...
        ]
      }
    }
  }]
}

*Setup a Azure Resource Group Deployment task to consume your template

*Set the buildNumber parameter

This should result in having a BUILD_NUMBER app setting in your Web App that reflects the current build in Azure Pipelines.


text:
Q: Phoenix deployment on Heroku failed to bind $PORT I have big issues with deploying my application on heroku server. I've done it with help of tutorial from phoenix webpage. But it doesn't work. Below you can see the logs and configuration i used.
heroku logs
2016-02-07T04:28:55.623435+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web
process failed to bind to $PORT within 60 seconds of launch
2016-02-07T04:28:55.623435+00:00 heroku[web.1]: Stopping process with SIGKILL
2016-02-07T04:28:56.344649+00:00 heroku[web.1]: State changed from starting to c
rashed
2016-02-07T04:28:56.348324+00:00 heroku[web.1]: Process exited with status 137
2016-02-07T09:54:29.124036+00:00 heroku[web.1]: State changed from crashed to st
arting
2016-02-07T09:54:34.703208+00:00 heroku[web.1]: Starting process with command `m
ix run --no-halt`
2016-02-07T09:55:35.386922+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web
process failed to bind to $PORT within 60 seconds of launch
2016-02-07T09:55:35.386922+00:00 heroku[web.1]: Stopping process with SIGKILL
2016-02-07T09:55:36.330258+00:00 heroku[web.1]: State changed from starting to c
rashed
2016-02-07T09:55:36.323082+00:00 heroku[web.1]: Process exited with status 137
2016-02-07T12:14:35.182306+00:00 heroku[router]: at=error code=H10 desc="App cra
shed" method=GET path="/" host=kpsz.herokuapp.com request_id=7de0ee97-14cf-46f9-
a9a3-cbffa09ac379 fwd="83.7.11.212" dyno= connect= service= status=503 bytes=
2016-02-07T12:14:35.850018+00:00 heroku[router]: at=error code=H10 desc="App cra
shed" method=GET path="/favicon.ico" host=kpsz.herokuapp.com request_id=4e9b1979
-deb6-497b-80b2-655615f43d01 fwd="83.7.11.212" dyno= connect= service= status=50
3 bytes=

Configuration prod.exs
config :kpsz, Kpsz.Endpoint,
  http: [port: System.get_env("PORT")],
  url: [host: "example.com", port: 80],
  cache_static_manifest: "priv/static/manifest.json",
  secret_key_base: System.get_env("SECRET_KEY_BASE")

config :kpsz, Kpsz.Repo,
  adapter: Ecto.Adapters.Postgres,
  url: System.get_env("DATABASE_URL"),
  pool_size: 20

A: I'm not sure if that's the problem but you could try to replace
http: [port: System.get_env("PORT")]
with
http: [port: {:system, "PORT"}]
At least that's what I'm using in my apps. You can also read the docs for more information http://www.phoenixframework.org/docs/heroku

A: I had a similar problem.
Adding a Procfile with a single line web: mix phoenix.server solved it.

A: heroku destroy project name
heroku create
and for some weird reason it works now...
Thanks very much for help.

A: I ran into this issue and, for me, the fix was as follow (copied from the answer on this question).
The fix is twofold:

*

*to use the phoenix buildpack config and export the PORT as well, like so: config_vars_to_export=(DATABASE_URL PORT)

*Avoid changing the MIX_ENV without recompiling the app, as that behavior is unsupported, as explained here.

A: As Recreation solves the problem, I suspect the problem is with loading environment variables.
Once I had a similar problem in my local. My observations

*

*mix phoenix.server (you might see the message compiled so and so files)

*Stopped the server

*Export/Change the env variable in zshrc/bashrc file and source it

*Start the server (you might not see that compilation message, as there are no changes in your codebase and so your new/edited env variables won't get reflected)

*If you just add a space in that file will make it compile and take that env variable.

Reason for your problem might be: Setting env variables after the server is running/deployed, as env variables are converted to value during the compilation time itself.

A: I had a similar problem when deploying the phoenix umbrella project with docker.
I've taken these steps:
Heroku https://hexdocs.pm/phoenix/heroku.html#deploying-to-heroku-using-the-container-stack
Dockerfile https://hexdocs.pm/phoenix/releases.html#containers
I've also looked at other links, but these two was the best.

The only problem with that Dockerfile is that it needs $PORT (and $SECRET_KEY_BASE) on the build step which is not present. So we have to "stub" it somehow in prod.exs. BUT we have to provide real $PORT on a run step (runtime configuration). So you have to be sure that you renamed config/prod.secret.exs to config/releases.exs (the 1 step at https://hexdocs.pm/phoenix/releases.html#runtime-configuration) or just create config/releases.exs which would rewrite $PORT (and maybe some other application environment variables - for example, $SECRET_KEY_BASE).
UPD: as @Daniel mentions - releases is an Elixir 1.9 feature.


text:
Q: Gravity Form - Dynamically Populate Name Field I have a multipage Gravity form. I would like the name field from the first page auto populate the name field on other pages? How do I do this? Any help would be greatly appreciated.

A: sounds like you're looking for Live Merge Tags, a feature provided by Gravity Forms Populate Anything.


text:
Q: Creating a Batch to go through all folders on a share and move files Here is what I am attempting to do and if I can get your help it would be greatly appreciated!
Issue:
I want to create a script to do the following:

*

*Go out to a network share where all account folders exist (2,400 folders with a 9-digit naming convention for account numbers, i.e folder name is 123456789).

*Then go through a specific directory within the account folders that have a time stamp naming convention (i.e 123456789\Jan_29_2013_453pm).

*Next, all folder structures are the same for all account folders EXCEPT the time stamped folder under the root (i.e 123456789`Jan_29_2013_453pm`\data).

*Once being able to get through the time stamp folder there will be a set of folders that start off with a naming convention of media1, media2, media3, media4, media5, etc. that I need to access in order to move files.

*I need to move a certain file from all media folders into media1. **There is an unknown amount of media folders for different account folders. Some may have 1 and other may have 50.

*I need to run a test within the data folder (123456789\Jan_29_2013_453pm\data) to open a logfile.txt to see if a specific string exists at the end of the log (i.e item was successfully created as well as item has failed`).

*If there is a SUCCESSFUL string in the logfile.txt, then go ahead and move all files from other media folders into media1. If a FAILURE string, then output the account folder name to a log file (output.txt) so I am aware which account folders failed (I would append the output as I will run this script multiple times).
The idea is to disregard account folders that have just a single media1 folder. Other account directories that have more than ONE media folder need to run a test against the log for SUCCESS or FAIL and depending on the string, to move a single file from all other media (media2,media3,media4,etc.) folders over to media1 unless FAILURE is read in the log.
I created a text file with all account folders on the share. I'm sure a FOR statement can be used against it. I'm also sure that a FOR statement can be used to go through the log in the "DATA" directory to look for the "SUCCESSFUL" or "FAILED" string.
The hard part I see is being able to get through the time stamped folder in order to get to the DATA directory.
THANKS AGAIN FOR ALL THE HELP!
@echo off
setlocal enabledelayedexpansion

:beginning
echo.
echo.
echo ===========================================================
echo Starting on !date! !time! on !Computername!
echo ===========================================================
echo.
echo Press ENTER to begin...
pause
echo.

goto :main

:main

cls
echo.
set /P acct=Please type the 9 digit account number you would like to restore:
set acctDir=X:\!acct!\
set acctDir2=media1\Setup\setup.exe /cd
set acctDir3=media1
set x=x:\!acct!\!userDir!
set sumLog="x:\!acct!\!userDir!\SummaryLog.txt"
set succ=finished
set log=c:\logs.txt

    echo. Starting on !date! !time! on !Computername! >> !log!
    echo.
    echo The account number you selected is: !acct!
    echo.

    goto :user

:user

    set /p answer=Is this correct (Y/N)?
    echo.

    if /i !answer!==y goto :yes (
    ) else (
        echo.
        echo Ok. Let's try again^^!
        echo.
        pause
        cls
        goto :main
        )
    )

:yes

    set c=0
    For /f %%a in ('dir !acctDir! /B /A:D') do (
    set /a c+=1
    echo !c!    %%a
    set dir!c!=%%a
    )

    echo.
    set /p userIn="Select a directory [1-!c!]: "
    set userDir=!dir%userIn%!

    echo.
    echo You selected !userDir! for your data retrieval.
    echo.
    goto :execute

:execute

    echo.
    echo The software will now be installed...
    start !acctdir!\!userDir!\!acctDir2! >>!log!

:move

    forfiles /p "!acctdir!\!userDir!\" /s /m *.ARC /c "cmd /c move @file !acctdir!\!userDir!\!acctdir3!"

    goto

:string

    findstr " .*!succ!" !sumLog!
    if exist errorlevel 0 (
        pause
        goto :move
    ) else (
        goto :eof
    )

endlocal
goto :eof


text:
Q: Long lived (nonlocal) lambda with captured reference Question updated to show a more complete example.
I recently found that a library that I am using has a piece of code that implements something similar to the following functionality:
class Foo {
   std::function<void()> FuncPtr;
public:
   template <typename Type>
   void setBar(std::set<Type> &bar) {
      FuncPtr = [&bar](){
         //Do something with bar
      };
   }
   void useBar() {
      FuncPtr();
   }
};

This seems dangerous to me as it is not possible to guarantee that the variable that bar references still exist when Foo::useBar() is called. With that said, the requirements upon bar was documented.
What is the consensus on capturing references in long lived (nonlocal) lambdas?
When asking the maintainer of the library about having the lambda capture a reference, the reason given was that he wanted to make it possible to modify the variable (that bar references) after having called Foo::setBar(). An alternative solution to implement the same functionality could be to have bar be a shared_ptr<int> but maybe this is too heavy handed.
Are there other good alternatives to make the code "safe"?

A: Capturing a reference is no more or less dangerous than capturing a pointer. The only difference is that you might be more likely to use a raw pointer with caution and think about its lifetime than you would do with a reference.
As you've said the safe way to do it is to use a shared_ptr. Whether that is too heavyweight depends on your application, if you are mostly just calling useBar() then dereferencing a shared_ptr is fairly inexpensive.


text:
Q: Postman request PUT with body -->form-data with image req.file undefined why? I have a question about a problem I am encountering on a web api (node js, express and multer)
With Postman.
when I do a POST request with the image file in the body -> form-data in the console.log (req.file), I can see the characteristics of the file BUT when I do a put request with the correct url, when i look in the terminal in the req.file i have undefined.
Why on the POST controller I can see the req.file and in the PUT controller I have undefined ???
in any case i should see my file in the req.file


text:
Q: How to read option parameters on PHP [Cordova file uploading]? I'm uploading image file using phonegap.I want to read option parameters on PHP file how can I do it?
This is my mobile application code.
    function uploadPhoto(imageURI) {
    var options = new FileUploadOptions();
    options.fileKey="file";
    options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
    options.mimeType="image/jpeg";

    var params = new Object();
    params.value1 = "test";
    params.value2 = "param";

    options.params = params;

    var ft = new FileTransfer();
    ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
}

This is my upload.php file
    <?php
print_r($_FILES);
$new_image_name = uniqid().uniqid ().".jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "image/".$new_image_name);
?>

How to read bellow values on php file
params.value1 = "test";
params.value2 = "param";

A: options.params should be read as a POST, this should display them:
print_r($_POST);


text:
Q: Can you create an in-cell formula based on difference cell values? I have a workbook with over 50 sheets, each one with the exact same structure. I want to make a sheet ("MAIN") that pulls the same data from each of the worksheets. For example: three sheets are named "2015_01", "2016_01", and "2017_01" and MAIN has columns "2015", "2016", and "2017" with a row directly beneath each "01", "01", "01".
I want to pull cell A9 from each of those sheets and put it into a the corresponding column, but also change the sheet it pulls from depending on the sheet title. Would it be better to do this as VBA or some sort of function?

A: The example in your OP, using the approach in the first comment:
If
Sheet1!A1 is "2015" and Sheet1!A2 is "01"
Sheet1!B1 is "2016" and Sheet1!B2 is "01"
Sheet1!C1 is "2017" and Sheet1!C2 is "01"

Then use these formulas in row 3.
Sheet1!A3 = '=INDIRECT(A1&"_"&A2&"!C9";TRUE)'
Sheet1!B3 = '=INDIRECT(B1&"_"&B2&"!C9";TRUE)'
Sheet1!C3 = '=INDIRECT(C1&"_"&C2&"!C9";TRUE)'


text:
Q: Boto s3 get_metadata Trying to get meta_data that i have set on all my items in an s3 bucket. Which can be seen in the screenshot and below is the code I'm using. The two get_metadata calls return None. Any idea's

boto.Version
      '2.5.2'

amazon_connection = S3Connection(ec2_key, ec2_secret)
  bucket = amazon_connection.get_bucket('test')
  for key in bucket.list():
    print " Key %s " % (key)
    print key.get_metadata("company")
    print key.get_metadata("x-amz-meta-company")

A: bucket.list() does not return metadata. try this instead:
for key in bucket.list():
   akey = bucket.get_key(key.name)
   print akey.get_metadata("company")


text:
Q: best way to get 2 values from html in python I'm using beautifulsoup and I want to scrape 2 attribute values in python.
<input type="hidden" name="test" value="123456789">
<input type="hidden" name="test" value="987654321">

I want to get both the values. This is the code that I'm using right now
number = BeautifulSoup(html, 'html.parser')
final = number.find('input')['name']
soup.find('input')['value']
print(final [2])

A: You are using .find() which gives you only first tag. You should be using .find_all() to get all input tags then grab values out of them.
from bs4 import BeautifulSoup

text = '''
<input type="hidden" name="test" value="123456789">
<input type="hidden" name="test" value="987654321">
'''

soup = BeautifulSoup(text, 'lxml')
values = [each.attrs['value'] for each in soup.find_all('input')]
# -> ['123456789', '987654321']


text:
Q: RestFUL com Spring, Hibernate, maven, PostgreSQL e WildFly - CreateCriteria estou fazendo um projeto RestFUL com os seguintes frameworks e estou passando por um problema, criei uma classe User para relacionar com o banco de dados, depois criei o userDao para realizar os métodos do CRUD e depois criei o UserDaoImpl para implementar a interface UserDao, porém utilizei o método CreateCriteria, mas não quero utilizar este método e sim o EntityManager, alguém sabe como posso realizar a troca no meu projeto? (Estou utilizando o postman para realizar a inserção dos dados no banco do postgreSQL).
Foto do Projeto

User.Java
package com.restfulproject.crud.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="\"users\"")
public class User implements Serializable{
/**
 *
 */
private static final long serialVersionUID = -4986635240092422790L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String firstname;
private String lastname;
private String address;

public User() {
    super();
    // TODO Auto-generated constructor stub
}

public User(String firstname, String lastname, String address) {
    super();
    this.firstname = firstname;
    this.lastname = lastname;
    this.address = address;
}

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getFirstname() {
    return firstname;
}
public void setFirstname(String firstname) {
    this.firstname = firstname;
}
public String getLastname() {
    return lastname;
}
public void setLastname(String lastname) {
    this.lastname = lastname;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

}
UserDao.Java
package com.restfulproject.crud.dao;

import java.util.List;

import com.restfulproject.crud.model.User;

public interface UserDao {

  public String addUSer(User user);

  public String updateUser(User user);

  public String deleteUser(User user);

  public List<User> getAllUsers();

}

UserDaoImpl.Java
    package com.restfulproject.crud.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.restfulproject.crud.model.User;

@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    private SessionFactory factory;

    @Override
    public String addUSer(User user) {
        getSession().save(user);
        return "Usuário adicionado com sucesso!";
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> getAllUsers() {
        return getSession().createCriteria(User.class).list();
    }

    @Override
    public String updateUser(User user) {
        getSession().update(user);
        return "Alterado com sucesso";
    }

    @Override
    public String deleteUser(User user) {
        getSession().delete(user);
        return "Deletado com sucesso";
    }

    private Session getSession() {
        Session session = null;
        try {
            session = factory.getCurrentSession();
        } catch(HibernateException ex) {
            session = factory.openSession();
        }
        return session;
    }
}

application-context.xml
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/test_db" />
        <property name="username" value="postgres" />
        <property name="password" value="123456" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.restfulproject.crud.model.User</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernet.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

springRest-servlet.xml
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <context:component-scan base-package="com.restfulproject.crud.*"></context:component-scan>
    <mvc:annotation-driven/>
    <tx:annotation-driven/>

</beans>

web.xml
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application-context.xml</param-value>
    </context-param>
    <display-name>Spring Rest Application</display-name>
    <servlet>
        <servlet-name>springRest</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>springRest</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.restfulproject.crud</groupId>
<artifactId>user-crud</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>user-crud Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.6.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.3.0.Final</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4-1205-jdbc42</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

</dependencies>
<build>
    <finalName>user-crud</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

A: Tente alterar seu arquivo application-context.xml para utilizar implementação do JPA:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

       <bean id="myEmf"
         class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
           <property name="dataSource" ref="dataSource" />
           <property name="packagesToScan" value="seu.pacote.de.entidades.aqui" />
           <property name="jpaVendorAdapter">
               <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
           </property>
           <property name="jpaProperties">
              <props>
                 <prop key="hibernate.hbm2ddl.auto">update</prop>
                 <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                 <prop key="hibernet.show_sql">true</prop>
              </props>
           </property>
       </bean>

    <bean id="dataSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.postgresql.Driver" />
      <property name="url" value="jdbc:postgresql://localhost:5432/test_db" />
      <property name="username" value="postgres" />
      <property name="password" value="123456" />
    </bean>

       <bean id="transactionManager"
         class="org.springframework.orm.jpa.JpaTransactionManager">
           <property name="entityManagerFactory" ref="myEmf" />
       </bean>
       <tx:annotation-driven />

       <bean id="persistenceExceptionTranslationPostProcessor" class=
         "org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    </beans>

E na sua classe UserDaoImpl.Java utilize o próprio EntityManager.
@PersistenceContext
private EntityManager manager;

...
    @Override
    public String addUSer(User user) {
        manager.persist(user);
        return "Usuário adicionado com sucesso!";
    }

E adicione no seu pom a dependência do entity manager:
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-entitymanager</artifactId>
  <version>4.3.6.Final</version>
</dependency>


text:
Q: ffdf objects with stream and ffbase I'm trying to perform clustering on a large dataset which I have stored as an ffdf object from package ffbase. According to documentation for ffbase (notes from the useR!2013 conference), package stream provides support for doing this.
I have had a look at the functions in stream but I cannot see how to set up an ffdf as a stream. The only function I can think might work, DSD_Wrapper, does not work. I guess I should be using DSD_ReadStream but I don't know how to get it working.
Here's an mwe:
library(ffbase)
library(stream)

ffmt <- as.ffdf(mtcars)
dsmt <- DSD_Wrapper(mtcars) #works fine
dsff <- DSD_Wrapper(ffmt)   #does not work

Investigating the structure reveals that it is quite a simple object, and I could recreate it manually, although the size of my actual data prevents this.


text:
Q: Does weighted MAPE (wMAPE) provide an accurate estimate of error? I'm trying to use wMAPE to calculate demand standard deviation for future forecasts, however, the wMAPE that we are using is derived from 13 buckets of actuals over a period of 52 buckets of time. If there are 13 weeks of actuals (can be continuous or intermittent) over a horizon of 52 weeks, we calculate the wMAPE based on those actuals. I'm trying to determine if this is the right way of estimating error as the intermittency (demand volatility) seems to be ignored.
I tried finding academic texts on weighted MAPE but I'm not finding anything. Any help will be appreciated.

A: There is no single "error" that we can estimate using an error metric. An error is whatever we measure. We can definitely measure the error using the MAPE (which may be undefined), the wMAPE, the MSE and so forth. All these errors will be different, and more importantly, each error will be minimized by a different forecast. So the question is one of choosing an error measure that elicits the forecast we want. (Saying "we just want a good forecast" begs the question, because what a "good" forecast is depends on the error measure.)
You may be interested in What are the shortcomings of the Mean Absolute Percentage Error (MAPE)? Although it's about the plain vanilla MAPE, it should be enlightening about the wMAPE.
Since the wMAPE is just the MAE divided by the mean (assuming you use the same definition as Kolassa & Schütz, 2007), it elicits the same forecast as minimizing the MAE - that is, the conditional median. The difference in "optimal" forecasts for different error measures are illustrated here for lognormally distributed data and here for gamma distributed data.
A median forecast may or may not be what you want. I personally have never seen a business process that would be better served by a median forecast than by an expectation or high quantile forecast.
Note in particular that for intermittent demands, if you can't reliably forecast when demand occurs, your conditional median may well be zero, so the wMAPE- or MAE-minimal forecast may well be a flat zero, which is a bit of a problem for people working on intermittent demand forecasting and using the MAE (Kolassa, 2016).


text:
Q: Do I really need to create interfaces in Spring? In my Spring project I have many simple services to fetching data (just a simple CRUD). The design of the developers that started this project was to create the implementation for each of the service like
public interface UserService

and then implementation like
public class UserServiceImpl implements UserService

Since there is no chance that UserService will have more implementation I'm really sick of these Impl suffix and the more I read (e.g. this article) I'm realising that I have reasons to being sick
I had a discussion with a friend from a team last week and I shared my thoughts with him but what he answered was 'basically you're right but Spring likes interfaces and works with them better than with classes'.
Unfortunately I'm not an expert in Spring and, however I was trying to look for some arguments, I was not able to find an answer was he right.
Are there some strong arguments to use such approach in Spring to have interface for every little service class?

A: I've gone through all the Answers here, But would like to add more on proxy
AOP can use JDK proxy OR CGlib proxy
If Class has implemented interface it will use JDK proxy(preferred whenever you have a choice).
If Class has not implemented interface it will use CGlib proxy.

A: It isn't a must and maybe opinion based, but you are adding interface to enable future flexibility of service,
Although you don't see real usage, it will allow you to use a different implementation of specific services inside unit/integration test
You can add test implementation instead of current implementation and use it instead of real service when executing test (for example by using different Spring profile)
This can be done using mocks as @Simulant points out

A: Wherever you want to reap benefits of dependecy injection (DI) pattern you need to program against abstractions, usually an interface.
There are more benefits to DI, but the most persuasive seems to be it allows unit testing. There your interfaces will get at least one more implementation (the mock implementantion), when you will want to test your class in isolation from its dependencies (those production implementations of the interfaces).
That said, that doesn't mean every class must implement some interface. Some parts of code can be tightly coupled together without problem.
Note that using Spring or not doesn't play role in the use DI/not use DI decision.

A: I can tell from real world projects, that it works well without interfaces only having the implementing class. Following the principle "You aren't gonna need it" (YAGNI), you simplify your code if you follow that rule. Dependency Injection works also well with classes, interfaces are not a requirement for it.
Sure you can write and reuse test implementations, but you can do the same with mocks e.g. with mockito and overwrite the behavior of your implementation class for test cases.

A: Acutally not needed , currently , micro service or mini code base is popular.
So normally , in rest api backend , you really do not have chance to have serveral implemention for certain interface .
In this situation , concrete class with @Serivice is enough.

A: As others have suggested it really depends upon the use cases. Although Spring and Java in general started as a verbose language with design where interfaces are suppose to act as what client, the implementation classes, can see but I am finding less and less verbose code these days esp. with Spring Boot and libraries like lombok these days.
So, it is not mandatory to create interfaces for Service, DAO but it is preferred if you are working on a fairly medium code base where there are multiple developers and possibly clients consuming those APIs outside of the application as well. But if you are working for a small or proof of concept projects, you can create a CRUD application on one Java class as well.


text:
Q: searching users from facebook, with their name and other attributes I want to create a search engine for Facebook. It should search users on social networking site Facebook. So can I use Graph API for the purpose ?? or is there any other technology available which I can use ?

A: Yes you can use the Graph API for this. see the "Search" Section of http://developers.facebook.com/docs/reference/api/

You can search over all public objects
  in the social graph with
  https://graph.facebook.com/search


text:
Q: Can Aberforth read? His brother seems to think that he can't.

"My own brother, Aberforth, was prosecuted for practising inappropriate charms on a goat. It was all over the papers, but did Aberforth hide? No, he did not! He held his head high and went about his business as usual! Of course, I'm not entirely sure he can read, so that may not have been bravery..."
(Goblet of Fire, Chapter 24, Rita Skeeter's Scoop).

Do we have any objective answer as to whether or not Aberforth can actually read?

A: We don't know
In the fourth book Aberforth is characterized by Albus as a zoophile and a (possibly) illiterate person. It seemed more like a joke, and perhaps even a reference to witchcraft and sorcery practice accusations - the passage can be interpreted according to the reader's maturity.
It is a rather brief introduction, but in the seveth book a complex backstory of the Dumbledore family is described in which Aberforth plays an important part.
We learn that Abeforth is magical and attended Hogwarts:

 Three years after we had started at Hogwarts, Albus's brother,
  Aberforth, arrived at school. -The Deathly Hallows - Chapter two: In
  Memoriam

Attending Hogwarts can be challenging for an illiterate person: The students have reading and writing assignments in most of the subjects, and written exams.
It is technically possible that if Aberforth had difficulties in reading comprehension he was tutored and allowed to do verbal tests instead of written ones, or perhaps the questions were read to him and he had a permit to use a charmed quill which recorded automatically what he dictated.
We don't have additional information about Aberforth being illiterate, just that  contrary to his elder brother, Aberforth was not the bookish type:

 They were not alike; Aberforth was never bookish and, unlike Albus,
  preferred to settle arguments by dueling rather than through reasoned
  discussion. - ibid

It is entirely possible that Aberforth was (partially) dyslectic and therefore he was less enthusiastic about studying, but there are many other reasons why someone chooses not to pursue a scholarly career or became a bibliophile. Either way, Abeforth is an accomplished duelist, and even capable of performing the complex patronus charm:

"Someone sent a doe Patronus to us!" "Brains like that, you could be a
  Death Eater, son. Haven't I just proved my Patronus is a goat?" "Oh,"
  said Ron. "Yeah . . . well, I'm hungry!" he added defensively as his
  stomach gave an enormous rumble. - Deatly Hallows: Chapter 28: The
  Missing Mirror

If we look at the context of Dumbledore referring to his younger brother as illiterate it seems that he wanted to cheer up Harry, sharing an embarrassing family secret, namely that even he, the brilliant scholar has a rather infamous and less than stellar brother. It is told as an anecdote, therefore it is entirely possible that Albus was exaggerating a bit. Unfortunately famous people like Albus Dumbledore need to be careful what they reveal, as everything they say is scrupulously analyzed and discussed by the public or even twisted by sensational reporting.

A: He probably could read - if he couldn't, Skeeter would've said.
Aberforth attended Hogwarts, for at least until the duel that resulted in his sister Ariana's death and falling out with his brother Albus. After their mother died, Albus stayed with their sister so Aberforth could stay in school.

"I'd have looked after her, I told him so, I didn't care about school, I'd have stayed home and done it. He told me I had to finish my education and he'd take over from my mother."

Albus had already graduated when their mother died, and Aberforth started at Hogwarts three years after his brother, so he'd have been attending Hogwarts for at least four years, even if he did quit as soon as he fell out with his brother.

"Three years after we had started at Hogwarts Albus's brother, Aberforth, arrived at school. They were not alike; Aberforth was never bookish and, unlike Albus, preferred to settle arguments by duelling rather than through reasoned discussion." - Harry Potter and the Deathly Hallows, Chapter 2 (In Memoriam)

So if he was indeed illiterate, at least some people (like the teachers and other students there at the time) would have known about his inability to read since he'd be unable to do his schoolwork in the typical manner. Hogwarts students are typically required to both read and write while doing their classes. He wouldn't be able to hide that he couldn't from everyone while also going to Hogwarts.
However, nothing about Aberforth being unable to read was mentioned in either "eulogy" of Albus Dumbledore. Elphias Doge didn't mention it when comparing Albus with Aberforth. However, that's not necessarily proof by itself. Even though Elphias Doge would have certainly known if his friend's brother couldn't read, he might not share that with the public if he thought it'd be embarrassing. Rita Skeeter is clearly very willing to share all the salacious details she can in her book. With so many people who'd have knowledge of Aberforth being illiterate if he was, Rita Skeeter, who was able to find out a lot of details about Dumbledore's life that very few people would have known, would have surely found out about Aberforth's inability to read.

"I ask whether Skeeter is referring to Dumbledore's brother, Aberforth, whose conviction by the Wizengamot for misuse of magic caused a minor scandal fifteen years ago.
'Oh, Aberforth is just the tip of the dungheap,' laughs Skeeter. 'No, no, I'm talking about much worse than a brother with a fondness for fiddling about with goats, worse even than the Muggle-maiming father – Dumbledore couldn't keep either of them quiet, anyway, they were both charged by the Wizengamot." - Harry Potter and the Deathly Hallows, Chapter 2 (In Memoriam)

She's quite happy to mention Aberforth being charged for casting inappropriate charms on a goat, so if she knew he was also illiterate, she'd likely mention that as well to add in more unflattering details to her story. She portrayed the members of Albus Dumbledore's family as negatively as possible, as well as the man himself, so it's unlikely that she'd leave out anything that would reflect badly on them.
Albus was likely joking, but Aberforth may have avoided reading.
When Albus Dumbledore said he's not entirely sure his brother can read, he probably didn't mean it literally - he was likely joking, but he may have known his brother to avoid reading and not enjoy it.

"Yeh – yeh're not half-giant!' said Hagrid croakily.
'Hagrid, look what I've got for relatives!' Harry said furiously. 'Look at the Dursleys!'
'An excellent point,' said Professor Dumbledore. 'My own brother, Aberforth, was prosecuted for practising inappropriate charms on a goat. It was all over the papers, but did Aberforth hide? No, he did not! He held his head high and went about his business as usual! Of course, I'm not entirely sure he can read, so that may not have been bravery …" - Harry Potter and the Goblet of Fire, Chapter 24 (The Egg and the Eye)

That may have meant something more along the lines of "Aberforth barely read" rather than "Aberforth was actually incapable of reading". Indeed, if Aberforth didn't read much then his brother might have meant that he wouldn't be likely to read the newspapers instead.

A: Possibly.
This line from Harry Potter and the Deathly Hallows allows for the possibility that he can read:

"Mr. Dumbledore?" said Hermione rather timidly. "Is that your sister? Ariana?"
"Yes," said Aberforth tersely. "Been reading Rita Skeeter, have you, missy?"
Even by the rosy light of the fire it was clear that Hermione had turned red.
Harry Potter and the Deathly Hallows, chapter 28: "The Missing Mirror" (emphasis added)

Aberforth is shown as... not being very social, especially now that he thinks that the Death Eaters have won. It's possible that he read Rita Skeeter's book and thus knew that she had mentioned Ariana. Of course, he could have heard that she was in there from some other source, but I think it's likely that he read the book.

A: The question is: how could Albus not know for sure?
Knowing the whole story of their brotherhood and the fact that they are still in touch throughout the books, it is hard to believe Albus didn't really know if his brother could read. If Aberforth was illiterate then Albus would definitely know it. So it looks to me that Albus was just joking when said that.


text:
Q: matplotlib. как отобразить в качестве подписей на оси x все значения из столбца dataframe? matplotlib. ось x сформирована из значений столбца, которые являются строками. plot() рисует график, в котором в виде подписей на оси x представлены только некоторые значения столбца (в данном примере через один). как отобразить все значения исходного столбца?
d = {'string': ['a', 'b', 'c','d','e','f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'], 'f1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'f2': [3, 6, 8, 5, 2, 7, 12, 6, 7, 10, 4, 6, 13, 15]}
df = pd.DataFrame(data=d)

df.plot(x ='string', y =['f1', 'f2'], kind='line', figsize = (15.5, 6.5))

A: Добавьте после df.plot(...):
plt.xticks(np.arange(len(df)), df['string'])


text:
Q: The Java ClassLoader Security Model I'm trying to understand the security model used when the JVM is asked to load classes.
From the JVM specification on Sandboxing, I'm given to believe that a standard JVM implementation should maintain at least one other ClassLoader, independent of the primordial ClassLoader. This is used to load the application class files (from a provided classpath for example).
If the class is requested from the ClassLoader that is not in it's namespace, java/lang/String for example, then it forwards the request to the primordial ClassLoader, which attempts to load the class from the Java API, if its not there then it throws a NoClassDefFoundError.
Am I right in thinking that the primordial ClassLoader only loads classes from the Java API namespace, and all other classes are loaded via a separate ClassLoader implementation?
And that this makes the loading of classes more secure because it means that a malicious class cannot masquerade as a member of the Java API (lets say java/lang/Virus) because this is a protected namespace, and cannot be used in the current ClassLoader?
But is there anything to prevent the Classes of the Java API being replaced by malicious classes, or would that be detected during class verification?

A: For historical reasons the names used for class loaders are a little peculiar. The boot class loader loads the systems classes. The system class loader, by default, loads classes from the class path not the system classes. The system classes are in jre/lib (mostly in rt.jar), endorsed directories and anywhere added through -Xbootclasspath.
On the Sun/Oracle JRE, rt.jar contains classes with packages starting with java., javax., sun., com.sun., org.omg, org.w3c and org.xml.
Untrusted code (including configuration) should not be able to add to the system classes. Some packages name prefixed may be restricted through a security property. The java. prefix is specially protected against for non-technical reasons.
Generally a class loader will delegate to its parent before defining a new class, preventing any classes from an ancestor loader from being replaced. Java EE recommends (even though Java SE bans) having some class loaders prefer their own classes, typically to use a more up to date API or a different implementation. This allows shadowing of classes, but only as seen through that loader (and its children). All other classes continue to link to the original.


text:
Q: Typescript: Returned type depending on enum key I create class builder. But i cant set return type depending on enum key.
enum TestKeys {
  testBoolean,
  testString,
}

type SettingsKeyReturnType = {
  [TestKeys.testBoolean]: Test<boolean>,
  [TestKeys.testString]: Test<string>,
};

interface Test<T> {
  getData(): T;
}

class A implements Test<boolean> {
  getData(): boolean { return false; }
}

class B implements Test<string> {
  getData(): string { return 'test'; }
}

function buildTest<T extends keyof SettingsKeyReturnType>(key: T): SettingsKeyReturnType[T] {
  if (typeof key === 'boolean') { return new A(); }
  if (typeof key === 'string') {  return new B(); }

  throw new Error('Key not found');
}

Every return send error:
TS2322: Type 'A' is not assignable to type 'SettingsKeyReturnType[T]'.
   Type 'A' is not assignable to type 'Test<boolean> & Test<string>'.
     Type 'A' is not assignable to type 'Test<string>'.
       The types returned by 'getData()' are incompatible between these types.
         Type 'boolean' is not assignable to type 'string'.

Try check T extends. Bit its not working:
function buildTest<T extends keyof SettingsKeyReturnType>(key: T): T extends TestKeys.testBoolean ? Test<boolean> : Test<string> {

Send errors:
TS2322: Type 'A' is not assignable to type 'T extends TestKeys.testBoolean ? Test  : Test '.
TS2322: Type 'B' is not assignable to type 'T extends TestKeys.testBoolean ? Test  : Test '.

The only working thing I found is:
function buildTest<T extends keyof SettingsKeyReturnType>(key: T): SettingsKeyReturnType[keyof SettingsKeyReturnType] {

But. Return type does not depend on enum.

A: This is the best I could do... At least it does not show errors, and you are able to get correct type calling getData:
enum TestKeys {
  testBoolean,
  testString,
}

type SettingsKeyReturnType<T extends string | boolean> = {
  [TestKeys.testBoolean]: Test<T>,
  [TestKeys.testString]: Test<T>,
};

interface Test<T> {
  getData(): T;
}

class A implements Test<boolean> {
  getData(): boolean { return false; }
}

class B implements Test<string> {
  getData(): string { return 'test'; }
}

function buildTest<T extends keyof SettingsKeyReturnType<string | boolean>>(key: T): SettingsKeyReturnType<string | boolean>[T] {
  if (typeof key === 'boolean') { return new A(); }
  if (typeof key === 'string') {  return new B(); }

  throw new Error('Key not found');
}