Azure DevOps - How to ensure working directory

Question: How can i ensure that all stages of my pipelines are performed in the same working directory.
I have pipeline that looks like this:
resources:
  repositories:
    - repository: AzureRepoDatagovernance
      type: git
      name: DIF_data_governance
      ref: develop

trigger:
  branches:
    include:
      - main
  paths:
    include:
      - terraform/DIF

variables:
  - group: PRD_new_resources
  - name: initial_deployment
    value: false

pool: $(agent_pool_name)

stages:
  - stage: VariableCheck
    jobs:
      - job: VariableMerge
        steps:
          - checkout: self
          - checkout: AzureRepoDatagovernance
          - ${{ if eq(variables.initial_deployment, 'false') }}:
              - task: PythonScript@0
                inputs:
                  scriptSource: filePath
                  scriptPath: DIF-devops/config/dynamic_containers.py
                  pythonInterpreter: /usr/bin/python3
                  arguments: --automount-path $(System.DefaultWorkingDirectory)/DIF_data_governance/data_ingestion_framework/$(env)/AutoMount_Config.json --variables-path $(System.DefaultWorkingDirectory)/DIF-devops/terraform/DIF/DIF.tfvars.json
                displayName: "Adjust container names in variables.tf.json"

  - stage: Plan
    jobs:
      - job: Plan
        steps:
          - checkout: self
          - checkout: AzureRepoDatagovernance
          - script: |
              cd $(System.DefaultWorkingDirectory)$(terraform_folder_name) && ls -lah
              terraform init
              terraform plan -out=outfile -var-file=DIF.tfvars.json
            displayName: "Plan infrastructure changes to $(terraform_folder_name) environment"

  - stage: ManualCheck
    jobs:
      - job: ManualCheck
        pool: server
        steps:
          - task: ManualValidation@0
            timeoutInMinutes: 5

            displayName: "Validate the configuration changes"

  - stage: Apply
    jobs:
      - job: Apply
        steps:
          - checkout: self
          - checkout: AzureRepoDatagovernance
          - script: |
              cd $(System.DefaultWorkingDirectory)$(terraform_folder_name) && ls -lah
              terraform apply -auto-approve "outfile"
            displayName: "Apply infrastructure changes to $(terraform_folder_name) environment"

How can I make sure that all 4 stages are inside this same working directory so I can check out just once and all stages have access to work done by previous jobs? I know that this
I know that my pipeline has some flaws that will need to be polished.
Comment: You can't and **shouldn't try**. Azure Pipelines is designed so that each job starts from a clean slate with nothing from prior jobs. This is to allow for parallelization and idempotency. If you only need a subset of the repository in later stages, you can `- publish` what you'll need later as artifacts and `- download` them as appropriate.
Comment: Does this apply both to `jobs` and `- job`?
Comment: I don't understand your question. A `jobs` block contains a series of `job` entries. Each job is separate and has no shared state with previous or future jobs.
Answer: This is not possible. Each azure devops stage has its own working directory and it is considered a different devops agent job. The jobs inside the stage will use the same working directory for the steps that are included on them.
If you need to pass code or artifacts between stages you should use publish pipeline artifacts and download pipeline artifacts native devops tasks.


Laravel5.8 : Retrieving data from table

Question: I am building event information page.

My posts table has post_id and category_id.

Now I could retrieve post information(image, organizer, title, place, map, date, description) from posts table.

But I cannot retrieve category name.  Also, my post has tags. And I
  need to retrieve tag's name.

I have no idea how to get those data and show on my posts/show.blade.php.
I am glad if someone helps me out.
PostsController.php
 public function store(CreatePostsRequest $request)
{

    $image = $request->image->store('posts');

    //create the posts
    $post = Post::create([
        'image' => $image,
        'category_id' => $request->category,
        'organizer' => $request->organizer,
        'title' => $request->title,
        'place' => $request->place,
        'map' => $request->map,
        'date' => $request->date,
        'published_at' => $request->published_at,
        'description' => $request->description
    ]);

    if($request->tags) {
        $post->tags()->attach($request->tags);
    }

    return redirect(route('posts.index'));
}

post.php
 public function category()
{
    return $this->belongsTo(Category::class);
}

public function tags()
{
    return $this->belongsToMany(Tag::class);
}

posts table
Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('image');
            $table->integer('category_id');
            $table->string('organizer');
            $table->string('title');
            $table->string('place');
            $table->string('map');
            $table->date('date');
            $table->timestamp('published_at')->nullable();
            $table->text('description');
            $table->timestamps();
        });

categories table
Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });

tags table
Schema::create('tags', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });

ResultsController.php
public function show($id,Post $post)
    {
        $post= Post::find($id);
        $category = Category::find($id);
        $tag = Tag::find($id);
        return view('posts.show',compact('post'));
    }

show.blade.php
Category: "I want to show category name here !"

        Tags:

        "I want to show tag's name here !"

Comment: in `ResultsController.php` use `$post->category` to get the category. for tags create a pivot table.
Comment: you are using a `belongsToMany` relationship. do you have a pivot table for posts and tags??
Answer:
Create migration with pivot table "post_tag" table name; Details here
In your migration for "posts" table, please change
$table->unsignedBigInteger('category_id');
Adjust your controller. You can use $post->category or $post->tags;

Laravel5.8 : Retrieving data from table


What (basically) does views/includes/plugins.inc line 9 views_include('base') actually do?

Question: I ran into an issue today where I started getting the following white screen of death error:

PHP Fatal error:  Call to undefined function views_include() in /*/sites/all/modules/views/includes/plugins.inc on line 9

I found several various bug reports and questions with similar errors. Some said it was a bug in views, some said it was a bug in VBO, and some reported it being issues with a specific module (like finder) none of which am I really concerned about.
My question is, since most of the solutions had to do with either commenting or uncommenting a particular line. Line 9 in views/views/includes/plugins.inc views_include('base'), what does this line actually do? Furthermore, what is the harm/benefit of having it commented or uncommented?
For my personal part, I was able to comment out the line (which cleared the error) then clear my cache and uncomment the line without the error returning, which seems awfully bizarre.
I the code is generally something with including (libraries/functions?) for views plugins, but further explanation would be much appreciated.
Answer: From views.module:
/**
 * Include views .inc files as necessary.
 */
function views_include($file) {
  static $used = array();
  if (!isset($used[$file])) {
    require_once './' . drupal_get_path('module', 'views') . "/includes/$file.inc";
  }

  $used[$file] = TRUE;
}

so to your question, it is trying to load up base.inc out of the Views module includes directory.  Unfortunately, for whatever reason, the views module itself doesn't appear to be loading up (and thus defining the function to begin with).
Comment: Thanks for the response, but I was really hoping for a bit higher level. "Why is that code there" in other words "what is the harm/benefit of having it commented or uncommented"?
Comment: This is really beyond my scope, but basically this line is needed to bring in the functions defined in base.inc.  Without them, I am assuming Views won't work.  However, for whatever reason, the views.module file isn't being loaded on your system, yet the plugins.inc file is.  Given that you can comment out the line, clear caches, and put it back in and then things run again fine seems to me to suggest that there is a bug somewhere and should be put in the Views issue queue, not here. IMHO.


Odd order n smaller than 27

Question: I have a group $G$ that is a group of matrices of the form
$$\left( \begin{array}{ccc}
1 & a & b \\
0 & 1 & c \\
0 & 0 & 1 \end{array} \right)$$
where $a,b,c \in \Bbb Z_3$.
I have shown it is of order $27$ and non-abelian. How do I show that there's only one non-abelian group of order $n$ less than $27$, and how do I find $n$?
Comment: Can you be more precise on where you are stuck?
Comment: really on how to begin. and what would it look like?
Comment: You could take $\Bbb Z_3\ltimes \Bbb Z_7$, since $3\mid 6$.
Answer: First, enumerate the odd numbers beneath $27$. You'll notice something: everything is either a prime $p$, of the form $p^2$ for a prime $p$, or of the form $pq$ for primes $p<q$. You should prove and then use the following theorems.

A group of order $p$ prime is cyclic, hence abelian.
A group of order $p^2$, $p$ prime, is abelian. (There are also precisely two of them). To prove this, use that $p$-groups have nontrivial center; then think about $G/Z(G)$.
If $p<q$ are prime and $p \mid q-1$, then there are precisely two groups of order $pq$, one of them non-abelian. If $p<q$ are prime and $p \nmid q-1$, then there is only one group of order $pq$, and it is abelian. To prove this, think about semidirect products.

Odd order n smaller than 27


How to change the background image of a QMainWindow central widget?

Question: I'm trying to change the background image of the QMainWindow central widget. The QMainWindow's background is fairly easy to change but I can't get the same result with it's central widget. What I tried is the code
self.mdi = QMdiArea()
self.options_window = Options()
self.central_widget = QStackedWidget()
self.mdi.setStyleSheet("{background-image: url(ninja.png);}")
self.setCentralWidget(self.central_widget)
self.central_widget.addWidget(self.mdi)
self.central_widget.addWidget(self.options_window)
self.central_widget.setCurrentWidget(self.mdi)

I also tried with this one
self.mdi = QMdiArea()
self.options_window = Options()
self.central_widget = QStackedWidget()
self.central_widget.setStyleSheet("{background-image: url(ninja.png);}")
self.setCentralWidget(self.central_widget)
self.central_widget.addWidget(self.mdi)
self.central_widget.addWidget(self.options_window)
self.central_widget.setCurrentWidget(self.mdi)

Could anyone give me a light in this problem?
Comment: try with my answer
Answer: To change the background image of a QWidget you should override the paintEvent method, in your case yours in a QStackedWidget, we create a class that inherits from this:
class StackedWidget(QStackedWidget):
    def __init__(self, parent=None):
        QStackedWidget.__init__(self, parent=parent)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), QPixmap("ninja.png"))
        QStackedWidget.paintEvent(self, event)

And then you change:
self.central_widget = QStackedWidget()

to:
self.central_widget = StackedWidget()

Example:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class StackedWidget(QStackedWidget):
    def __init__(self, parent=None):
        QStackedWidget.__init__(self, parent=parent)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), QPixmap("image.png"))
        QStackedWidget.paintEvent(self, event)

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent=parent)
        self.setCentralWidget(StackedWidget())

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

Screenshot:

The case of QStackedWidget is a special case since this is not shown, this serves to show other widgets, to those widgets you must change the background image.
From your code, the first widget they attach is a QMdiArea, this is also a special case since it has a viewport and this should be changed.
class MdiArea(QMdiArea):
    def __init__(self, parent=None):
        QMdiArea.__init__(self, parent=parent)

    def paintEvent(self, event):
        QMdiArea.paintEvent(self, event)
        painter = QPainter(self.viewport())
        painter.drawPixmap(self.rect(), QPixmap("image.png"))

In your code change:
self.mdi = QMdiArea()

to:
self.mdi = MdiArea()

Screenshots:
Comment: the `QPainter(self)` is complaining with the `self` argument, then I don't know if it didn't work because of this or anything else. Warning: Expected QPaintDevice, got StackedWidget instead
Comment: I think you implemented it wrong, you could share your code through github, drive or similar to show you how to do it please
Comment: @MatheusFernando Look at the example I've placed.
Comment: here's the drive link: https://drive.google.com/open?id=0B17RZyeHhRfZZTNiZ1N1cFhfdG8
Comment: Please the code you are missing certain classes or functions, you could share that too. One question, the QStackedWidget is never displayed, that widget is used to display other widgets, maybe you want QMainWindow to have that background?
Comment: I uploaded the whole code, here's a picture of where I want to change: https://drive.google.com/open?id=0B17RZyeHhRfZM0VoNEx1cjNWNFE
Comment: It's working perfectly now, thank you very much @eyllanesc


Xml Parse in php

Question: Hi I am trying to make code for parse xml in php but didn't get solution or might be i am wrong somewhere
<code>$url="";
$dom=simplexml_load_file($url);
$dom->Metadata->@attribute->keywords // we need output New Car Loan New

SimpleXMLElement Object
(
    [MetaData] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [keywords] => New Car Loan New
                )

            [Market] => in
            [CategoryRating] => clean
            [Label] => Yes
        )

    [PageStatus] => SimpleXMLElement Object
        (
            [StatusItem] => OK
        )

    [ResultSet] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [id] => adListings
                            [numResults] => 3
                        )

                    [Listing] => Array
                        (
                            [0] => SimpleXMLElement Object
                                (
                                    [@attributes] => Array
                                        (
                                            [rank] => 1
                                            [title] => Buying a new car?
                                            [description] => Invest with Principal MF kyonki apne dad ki maruti kab tak chaloge
                                            [siteHost] => www.principalindia.com
                                            [biddedListing] => true
                                        )

                                    [ClickUrl] => http://0.r.msn.com/?ld=DvX_oqthqPCPYaraY0mBzOYzVUCUxVW1UeJRbKtha6zY0gA59KPpZZcQv0Zc0u0WmcHXAqU0uYrQ-CTdzipnYsvM3mGlXNUt_4DjcdCmZ-fc8bLQ0dTKcyrImSVVxPgT_Lm-gFjA&u=principalindia.orionadeas.com%2fpmf-IEbolly%2fvisit.asp%3fIE-Bolly_car_yahoo-bing_text_ad
                                )

                            [1] => SimpleXMLElement Object
                                (
                                    [@attributes] => Array
                                        (
                                            [rank] => 2
                                            [title] => Car Loan Calculator
                                            [description] => Calculate Your Monthly Car Loan Payment w/ Free Car Loan Calculator
                                            [siteHost] => CarCalculator.Bankrate.com
                                            [biddedListing] => true
                                        )

                                    [ClickUrl] => http://11372.r.msn.com/?ld=Dv5wS7MX7KTUpIO4Ld6a7xpjVUCUzZSCBVc7n1kAMyrCmSdPWYcbAwRbmZ1mVeszjKoc1ch9KzCxet5xv9k5HWCQeZmpLhNizyo3v3mN2DoJfVktX8_jPx3tidYGml00XbKTC7Gw&u=http%3a%2f%2fpixel.everesttech.net%2f1325%2fcq%3fev_sid%3d10%26ev_ltx%3d%26ev_lx%3d20581378696%26ev_crx%3d4263677231%26ev_mt%3dp%26ev_dvc%3dc%26url%3dhttp%253A%2f%2fwww.bankrate.com%2fcalculators%2findex-of-auto-calculators.aspx%253Fpid%253Dp%3asem_bs%2526ec_id%253Dm1176606%2526s_kwcid%253DAL%25211325%252110%25214263677231%252120581378696
                                )

                            [2] => SimpleXMLElement Object
                                (
                                    [@attributes] => Array
                                        (
                                            [rank] => 3
                                            [title] => Looking to Buy a New Car?
                                            [description] => OLX.in Sab kuch bikta hain. 100% FREE Classified. Post Your Ad
                                            [siteHost] => www.OLX.in/Cars
                                            [biddedListing] => true
                                        )

                                    [ClickUrl] => http://1348940.r.msn.com/?ld=DvGAMOap4YGw-rpEjRLeTMDDVUCUxvLI3yeYRoUO4StfJm-cLP74OC3sJGuLV-kLUTYA2Yo9ttcjCqgujqjiBGtMum5GkgQ-JuENgP7gnfkz5eY6mOhBfSaAaecyT8vZfFBS_W4A&u=www.olx.in%2fcars-cat-378%3finvite%3dysm-in_Search_New_Cars_Oct13%26utm_source%3dYSM%26utm_medium%3dCPC%26utm_content%3dSearch_New_Cars_Oct13%26utm_campaign%3dYSM_Search_OLX_Cars
                                )

                        )

                )

            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [id] => searchBox
                            [queryParams] => qs=06oENya4ZG1YS6vOLJwpLiFdjG91IC5fjJvO7uny1mKMONfD6NBfD7_Nc1hQlYP0RdFkPDXePNHCEQkEuEq_Fy6u1xuEO8NR4PQBX00f3-RkiHCW4F9IB_y5nKk_2uEROgSm9uWoplOYRS8OoTNkFJyHey2SqqhbOu_7Jxwf0FpS7v6yYyu6WtWNm76mHqtwb2YtA5vfsDUcFnLvWrwDjRlpB5icwbFDTiPIsIxs1mDuFacViNYZI5HCBgG5_FYBwxkPaNO4olaNROjK6TNMWkV2599PodCwrNedHqwwZQDf9CNWOR3BonrR6sFGr7GeOJNQY.,YT0zO2s9NTtoPTM0NTUyYjViNmY5NjNkZWQ.
                            [numResults] => 0
                        )

                )

        )

    [NextArgs] => qs=06oENya4ZGM2qEjAyqVAwH9kTIhmx0scq8mtrUZw1fiD9lYwAMyvDH_G0LRXOodvNK0DeZwnzpVAdrtI1S0tCOAmYRb6hF1Zva5jjqiYb4cQCYF1zeE8IGTnPsxobRLRShAsdKzOASDhzPHEmHBb5870FxGf5CWEiVIHr_fTu4MtYgrgfw6UKYNI-_0GJFM03E2RE3sL01DDgZi2e_d9sOtPVXKImFpAUnN-7A3nfJnMBVsaVZO3yefk-reMDzFHM5NltK0e92utiXHZINw5UThyvjogHgsBkH9SuQ04gqXzJcYWhatCskUb-PtGgI5Wvudfaac8E-0aMKLFGuIG_CIGu87mifjQnCwYbcbVrQNrNdEs4zuDMSfCHW1uRxFlqJwzmbD8YNdjsHPxecSfNZmGEWTSAL297olKIGaUtCkQr2EgW45kWowdTQbq5MukSxaY5CXT1D8LUgC4gTOcb28xGMs9LRn0YJr9MfGpifOKXsRh9cJrEspJr8BkKpqbowk5-9BV3M5ZEaQIsOVrcEGEKJqF1MFtOYCC4m4UzlQzn1Tge0vc9pfLpp19DAVHr6gGRL
)
</code>
Comment: I don't understand what the problem is.
Comment: i need to echo keywords position  [@attributes] => Array
                (
                    [keywords] => New Car Loan New
                )
Answer: Try this:
$dom->Metadata->attributes()->keywords
http://php.net/manual/it/simplexmlelement.attributes.php
Comment: Please share the original XML file
Answer: You need to use the method <code>->attributes()</code> to access them: Example:
<code>$xml = simplexml_load_file($xml_string);
// php 5.4 dereference
$keywords = (string) $xml->MetaData->attributes()['keywords'];
</code>

Xml Parse in php


how to add multiple different controls(ex-TextBox,Button etc) dynamically to the window through xaml

Question: I am having  a set of buttons on window. when I clicked on that buttons I want to add Different controls dynamically.
consider I am having two buttons
1> AddTextBox
2>AddButton
When I click on AddTextButton the TextBox should be added to window
when I click on AddButton the Button should be added
Comment: *"through xaml"* ? Dynamically usually means programmatically (see [this answer](https://stackoverflow.com/a/7885604/1997232)).
Answer: You can add like below code snippet,
private void AddButtonClick(object sender, RoutedEventArgs e)
    {
        var rowCount = this.grid.RowDefinitions.Count;
        this.grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
        var button = new Button() { Content = "Button1", Height = 20, Width = 50 };
        Grid.SetRow(button, rowCount + 1);
        this.grid.Children.Add(button);
    }

Answer: If you mean you want to dynamically add buttons via binding the following approach may help you.
At first you add a ItemsControl section to your xaml defining an ItemTemplate.
<ItemsControl ItemsSource="{Binding DynamicControlObjects}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Text}"
                     ToolTip="{Binding Tooltip}"
                     IsEnabled="{Binding IsEnabled}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The DynamicControlObjects is just a simple IList<T> where T is a class containing the properties you want to bind.
For example what I am using in this case is my class DynamicControlHelper:
// ...

using Microsoft.Practices.Prism.ViewModel;

// ...

public class DynamicControlHelper : NotificationObject
{
    #region Backing Fields

    private string _text;
    private bool _isEnabled;
    private string _tooltip;

    #endregion Backing Fields

    #region Properties

    public string Text
    {
        get
        {
            return this._text;
        }

        set
        {
            if (!string.Equals(this._text, value))
            {
                this._text = value;
                this.RaisePropertyChanged(nameof(this.Text));
            }
        }
    }

    public bool IsEnabled
    {
        get
        {
            return this._isEnabled;
        }

        set
        {
            if (this._isEnabled != value)
            {
                this._isEnabled = value;
                this.RaisePropertyChanged(nameof(IsEnabled));
            }
        }
    }

    // ...

    public string Tooltip
    {
        get
        {
            return this._tooltip;
        }

        set
        {
            if (!string.Equals(this._tooltip, value))
            {
                this._tooltip = value;
                this.RaisePropertyChanged(nameof(this.Tooltip));
            }
        }
    }

    #endregion Properties
}

When I needed this approach the first time. The answer from H.B. leads me to my solution.


String.Format Is it possible to display file name for Path string in XAML

Question: Hi i am new to C# and WPF. The below is just example not tested.
Lets say i have
String path1 = "C:\Users\user\Desktop\File.ext"
String path2 = "C:\temp\text.txt"

String.Format(path1.Substring(path1.LastIndexOf('\')+1))
String.Format(path2.Substring(path1.LastIndexOf('\')+1))

I want to get the filename from the path without changing the original string and i want to do it preferably in XAML or do a value converter.
I am looking into this to know if I should do a value converter between one Observable collection and ListView or just stick with two Lists. One to contain filepaths in model manually and fileNames to display in a ListView and update both separately (Current approach).
My data model
private List<String> AttachedFiles;
public ObservableCollection<String> fileNames { get; set; }

    public void addFilePath(String filePath) {
        this.AttachedFiles.Add(filePath);
    }

    public void removeFilePath(String filePath)
    {
        this.AttachedFiles.Remove(filePath);
    }

The xaml
<ListView x:Name="DropList" ItemsSource="{Binding fileNames}"

I included very little code as this as to give an just an idea as I am thinking of refactoring. Can i use String methods inside String.Format for dipsplaying in XAML so it will still have the original filepath value in the model or is there some syntax for String.Format to do this?
EDIT
The answers are duplicated but I was asking if String.Format can be used in the XAML converter with methods like Trim Substring Etc and if I should refactor my code, but doing it properly creates more code and complexity than it removes.
EDIT 2
This is the code. Basically the list view has an X icon and text with file name next it, if the user clicks the icon the it will call this:
    private void r1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Rectangle r = sender as Rectangle;
        ticket.removeFilePath(r.DataContext.ToString());
        ticket.fileNames.Remove(r.DataContext.ToString());
    }

Comment: See the marked duplicate for working code to show only the file name. There are many ways to approach the problem. If you feel the marked duplicate doesn't address your question, post a new question that includes a good [mcve] showing clearly what you've tried, and explain _specifically_ what it is you're having trouble getting to work.
Answer: Use one collection, and don't use List<T>:
ObservableCollection<String> FilePaths { get; private set; }

If you replace the collection, you'll need to raise INotifyPropertyChanged.PropertyChanged.
Write a value converter (OK, just steal mine):
public class FileName : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider) => this;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return System.IO.Path.GetFileName(value.ToString());
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And use the value converter in a DataTemplate. Since FilePaths is a collection of String, the DataContext of your DataTemplate will be a String, so the binding won't specify a property for the binding to use. The value passed to the value converter will be the string itself.
<ListView x:Name="DropList" ItemsSource="{Binding FilePaths}">
    <ListView.ItemTemplate>
        <DataTemplate>

        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Comment: Unfortunately it doesnt work, the exemel is giving an erro that it expects the IValueConverter type The xaml is:
Comment: @RobertMazurowski What does the class definition for local:Ticket look like?
Comment: It is this class MyModel : MarkupExtension, IValueConverter, INotifyPropertyChanged. My class contructor is creating the list: public myModel() {
            this.fileNames = new ObservableCollection();
        }
Comment: @RobertMazurowski Why would you implement INotifyPropertyChanged? Try removing that. I've written a lot of value converters this way and never had an issue.
Comment: @RobertMazurowski wait, wait: was that a class named Ticket? Or MyModel? What does Ticket look like? Which one gave you the error?
Comment: The class was ticket, i forgot that i have showed the name. I should not show code outside of work:( Because the model class has a several other fields which are binded to other controls, The class has the interface and implements the methods so i fought this is not the issue. I come from Java:) Does this mean that I need to make the converter and file list a seprate class in C#?
Comment: @RobertMazurowski This is getting too weird for me. No idea what you're trying to do, sounds crazy, can't possibly help you fix it. My example works. Just follow it and you're fine. You used Ticket in the XAML you showed me, not MyModel. The converter must implement IValueConverter. The error says it doesn't.
Comment: @RobertMazurowski Don't use your model as a value converter. There's no reason to. If you need to give it multiple parameters use a MultiBinding with IMultiValueConverter.
Comment: Sorry for that I cannot show code used at work and I asked so many questions recently that i got lost in my "Abstract substitions". It is MyModel is just abstract of the ticket class, I have there 3 strings which are attached to notify property changed and this one list of fileNames. If I leave the fileNames in ticket class and make a separate value converter class what would i have to change in your converter and XAML?
Comment: @RobertMazurowski You would use my converter and XAML just the way I wrote them. In your viewmodel, you would have a property  `public ObservableCollection FilePaths { get {...} set {...} }` with the usual INotifyPropertyChanged stuff. That collection will contain the full complete paths. My converter takes a path and returns just the file name part of the path. If you're using Java-style casing everywhere, you may as call it `filePaths` for consistency.
Comment: Thank very much as soon as I will test this I will let you know how it works. Because there is also a function that deletes a file from the list when user clicks on an icon inside the list view so hopefully it will convert back:)
Comment: @RobertMazurowski How are you deleting the path from the collection?
Comment: I have edited the questions with this method
Comment: @RobertMazurowski I would expect that to work for removing the file path, IF and only if `sender` is actually a `Rectangle` and its `DataContext` is actually the path. Obviously it will fail to remove the filename from the filenames collection, because the DataContext there is the whole path, not the filename. But I don't know why you still have a filenames collection at all.
Comment: @RobertMazurowski Wait, is `removeFilePath` still what you quote in your question? If it is, of course nothing will work at all. I worry that you still have the filenames collection around. That should be gone, almost certainly.
Answer: If you are dealing with only one property here, you can just use a converter as other answer suggested. But you could also create a new Class for your Path object, and define a FilePath string property in this class to store the full path. (And more properties if you need.)
Then you can just override the ToString method in this Class to return just the filename.
By doing this, you don't need to change the XAML, but the binding list will just display the item as the result returned by your override ToString method.
Something like:
public ObservableCollection<MyPath> fileNames { get; set; }

public class MyPath: ObservableObject  //implement INotifyPropertyChanged
{
    private string _filepath;
    public string FilePath
    {
        get { return _filepath; }
        set
        {
            if (value != _filepath)
            {
                _filepath= value;
                RaisePropertyChanged("FilePath");
            }
        }
    }
    public override string ToString()
    {
        return System.IO.Path.GetFileName(FilePath);
    }
}


is there any alternative in C# NUnit for AssemblyTearDown

Question: It would be great to have an attribute that can decorate a static method called AssemblyTearDown. It would mark the method that should be called after all the tests within the assembly have run to allow resources obtained by the assembly to be freed.

It needs to be applied to a static method
It would be called after all the other TearDown's have been processed.
It should not need to be in a class that has test methods.
NUnit should only allow one method to be decorated with this attribute within an assembly.

[AssemblyTearDown] - this is not supported in nunit 3.0
Is there any alternative in c# nunit which we can use instead of AssemblyTearDown.  It would be called after all the other TearDown's have been processed
Comment: Possible duplicate of [Does NUnit support the concept of an Assembly Teardown?](https://stackoverflow.com/questions/14288454/does-nunit-support-the-concept-of-an-assembly-teardown)
Comment: Not a duplicate. The age of the other question, as well as the text, indicate that it refers to NUnit V2, not NUnit 3.
Answer: Despite this question being nearly a couple of years old, it seems it was left without an answer. After some research, I came across the answer to this today from NUnit's documentation for [SetUpFixture].
I think this should cover most bases when it comes to fulfilling the OP's requirements:
Essentially, if you decorate a class with the [SetUpFixture] attribute outside of any namespace, and create a method within that class decorated with the [OneTimeTearDown] attribute, this method will be executed once after all tests have completed execution.
Note that the [SetUpFixture] attribute can also be used to provide one-time setup/teardown for a set of tests in a given namespace too, whereas, as per the OP's requirements, if the attribute is applied to a class outside of any namespace, the one-time setup and teardown methods (decorated with [OneTimeSetUp] and [OneTimeTearDown] respectively) provide setup/teardown for the entire assembly.
Example code from the documentation:
using System;
using NUnit.Framework;

namespace NUnit.Tests
{
  [SetUpFixture]
  public class MySetUpClass
  {
    [OneTimeSetUp]
    public void RunBeforeAnyTests()
    {
      // ...
    }

    [OneTimeTearDown]
    public void RunAfterAnyTests()
    {
      // ...
    }
  }
}

Hopefully, this is useful to somebody down the road!
Answer: It took me some time to realize that outside any namespace means that no namespace should be present. Also I saw no difference if the method is static or not, the class and method names can be any valid names, here is the code that worked for me:
using NUnit.Framework;

[SetUpFixture]
public static class AssemblyCleanFixture
{
    [OneTimeTearDown]
    public static void RunOnAssemblyCleanUp()
    {
        //Your code here
    }
}


"Add to cart" form tweaks

Question: I am setting up a very simple Drupal commerce site for a few courses with 3 product variations for different price levels. I created a product type "Course Registration" and gave it these payment options:

DEP|Deposit
EB|Early Bird
FULL|Full Price

I have a content type "Course Display". On the bottom of a product display page I get this:
Payment Option
o Deposit
o Early Bird
o Full Price
[Add to Cart]
$250
From what I've been able to figure out the radio buttons and submit button are displayed part of the "Add to Cart form" widget for 'product' field. The price is coming from the 'Product: Price" field. I would like have the price show above the submit button like this:
Payment Option
o Deposit
o Early Bird
o Full Price
$250
[Add to Cart]
I assume this means getting the "Add to Card form" to show the price? I'm at a loss for how to proceed.
Answer: You can add the rendered field into the add to cart form like this:
<code>function mytheme_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
  $product = $form_state['default_product'];
  $view_mode = $form_state['context']['view_mode'];
  $form['price'] = field_view_field('commerce_product', $product, 'commerce_price', $view_mode);
}
</code>
Comment: Awesome. Thanks so much. Maybe I can start to understand how this works a little.  Next I want to add a 'Show Cart' button adjacent to the 'Add to Cart' button. If you could give any help on how to do that or how any of this is working in general I'd find that really useful.
Comment: Sure. You can add a link to the form by adding something like this to the hook I posted:

`$form['show_cart'] = array('#markup' => l(t('Show Cart'), 'cart'), '#weight' => 99);`

All we're doing is adding elements to the form's [render array](http://drupal.org/node/930760) after it's been built.
Comment: Okay this is starting to make more sense. I want a button that acts like an href to '{root}/cart/' `$form['show_cart'] = array('#type' => 'button',
  '#value' => t('View cart'),
  '#attributes' => array('onclick' => 'window.location.href=\'cart\''),
   '#weight' => 65,
   );` but can't figure out how to get rid of the "submit"
Comment: I figured out how to leave it as a link and style it to look like a button. Not that clean though since I have to duplicate the button css in the theme. Is there a better way?
Comment: You could add another submit button with its own submit handler that redirects to the cart page. I think that a link is more semantically correct though is it's not really related to submitting the form.

"Add to cart" form tweaks


Pandas - join two dataframes based on one column from table and combining two columns from another table

Question: I am trying to join two tables based on one column from one table and two column from other table
Table a
name, designation
Mr. james john, manager
Mr. jim james, tester
Mr. abe james, developer

Table b
first name, last name, emp id
james,john,1
jim, james,2
abe,james,3

I want to join table a name column with table b combining "Mr. "+first name+last name.
Comment: Please provide actual sample of data.
Answer: Here's a way to do what your question asks:
res = a.join(b.assign(name='Mr. ' + b['first name'] + ' ' + b['last name']).set_index('name'), on='name')

Input:
dataframe a:
             name designation
0  Mr. james john     manager
1   Mr. jim james      tester
2   Mr. abe james   developer

dataframe b:
  first name last name  emp id
0      james      john       1
1        jim     james       2
2        abe     james       3

Output:
             name designation first name last name  emp id
0  Mr. james john     manager      james      john       1
1   Mr. jim james      tester        jim     james       2
2   Mr. abe james   developer        abe     james       3


Google Universal Analytics Real-time not working

Question: I am trying to integrate Google Universal Analytics into my website. I have started to see basic reporting (page views, uniques, etc.) under Behavior > Overview
But still see nothing for real-time reporting under
Realtime > Overview
And I cannot seem to get any events to fire.
I have this code snippet at the very end of :

I have tried to move my sample event to other places with no luck ... also not sure which of the event lines is the one you're supposed to use with Universal, so have tried each one with no luck.
So frustrating. The old Google Analytics always worked so easily.
I have this site located at a directory under another site, does that matter?

Analytics code is on: http://dmlapps.com/dogpeople/index.html
Google Analytics is setup at: http://dmlapps.com/dogpeople
Website is at: http://dmlapps.com/dogpeople
Comment: I also have this in Google groups, but no answer yet.
https://groups.google.com/a/googleproductforums.com/d/msgid/analytics/00448269-e98f-4a46-ab94-8837c1622640%40googleproductforums.com?utm_medium=email&utm_source=footer
Comment: OK, as soon as I posted this question, I am now seeing real-time visits coming from StackOverflow. Is it ignoring my devices?
Comment: Have you set up any filtering to exclude your own visits? For example, IP-based filters?
Comment: No I have not setup anything specific. All I did was include that code snippet on the index.html file.
Comment: Someone from Canada just visited the site and showed up in Real Time reports, but it's yet to show my activity on Real Time reports.
Comment: Chances are that I am that Canadian. Do you have [GA Debugger](https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna?hl=en) installed? Can you see if Pageviews or other hits are sent from your browser?
Comment: Yes, I have that installed in Chrome, and it appears page views are being sent... my events are not firing still (if you select a category from the filter menu at left, it's supposed to send an event telling me you did that).

The other issue is I don't know why my personal activity is not being included in Real Time reports. I have tried a couple browsers and my phone.
Comment: Screenshot from GA Debugger:
http://davidmlester.com/samples/Screen%20Shot%202015-04-30%20at%209.21.29%20AM.png
Answer: Your Custom Events are not firing because at the time of the evaluation, $(".sub-menu li a") does not match any element in the DOM, as it has not finished loading.
You should wrap your call in a $(document).ready() callback:

Alternatively, you could also use the .on() method, for live evaluation:
$(document).on('click', '.sub-menu li a', function () {
    ga('send', 'event', 'nav', 'tap', 'filter');
});

Comment: That fixed everything!
Comment: Events firing and now my devices are registering!
Comment: Good job! Sent some Canadian sub-menu hits your way so you can validate :)


I'm trying to export a runnable jar in Eclipse, but I need it to include some other files necessary for running my program

Question: Specifically, I am using JDBC libraries to work with databases in my Java program. When I perform "Export Runnable Jar" in Eclipse, it includes the referenced libraries but I am never given an option to include my assets folder (containing the databases) in the runnable jar file. If I try to export a regular jar file via Eclipse, I can add the assets folder, but the referenced libraries are not included.
What should I do here?
Thanks a lot.
Answer: Try using Ant scripts or maven script to do this.
Where you can import all the referenced jar and files to your desired location.
Personally i liked ant script, since it was easier and you will surely get lot of results for the same if you google.
Comment: Reading up on this now. I'll get back to you with results, thanks a lot!
Answer: It's been some time since I last generated a JAR file with Eclipse, and back in the day I remember the Fat-Jar Eclipse Plug-in to be quite useful.
Comment: seems like Fat-Jar is the same as Runnable Jar File export option in eclipse. Thanks anyway though.
Comment: Oh. What a pity. Too much time without clicking on that option in Eclipse.
Answer: Are your asset directories declared as Source Folders in Eclipse?
Right Click on the folder, choose Build Path->Use as Source Folder. Then retry the export.
In the longer term, you should really be looking at a build tool such as maven or ant, they are much more flexible, and they are less dependent on Eclipse, so changes in your project configuration in Eclipse won't affect the final build so much.
Comment: This works, but I can only run the program within my main project directory, as it looks for a folder labeled /assets. I think that is on my code side though, thanks a lot! EDIT: Yea my code has this line: `mConn = DriverManager.getConnection("jdbc:sqlite:assets/database1.db");` which I believe means the project looks for a folder called assets/ then inside that looks for the db. I need to change this so it is looking in a source folder.


Lyndon words and Duval's algorithm

Question: Can you give me an simple explanation on how are Lyndon words constructed with Duval's algorithm? Simple, because I am not so math proficient in understanding some of the  notation and concepts, and also because I haven't study algorithms and programming, yet (this problem was in my graph theory lessons).
I tried understanding it from the wikipedia and this link  , but I only understood it in parts. Also,  this pseudocode from GitHub is not understandable to me, and I couldn't find another. Here it is:
    def LyndonWords(s,n):
    """Generate nonempty Lyndon words of length <= n over an s-symbol alphabet.
The words are generated in lexicographic order, using an algorithm from
J.-P. Duval, Theor. Comput. Sci. 1988, doi:10.1016/0304-3975(88)90113-2.
As shown by Berstel and Pocchiola, it takes constant average time
per generated word."""
    w = [-1] # set up for first increment
    while w:
        w[-1] += 1 # increment the last non-z symbol
        yield w
        m = len(w)
        while len(w) < n: # repeat word to fill exactly n syms
            w.append(w[-m])
        while w and w[-1] == s - 1: # delete trailing z's
            w.pop()

I would be thankful if you could show me by example, with some letters or numbers, so that I can intuitively comprehend it.
Answer: LyndonWords create a generator object given s and n:
type(LyndonWords(3,2))
# generator

To see what the code does, we can iterate over this generator and print each of the value:
for word in LyndonWords(3, 2):
    print(word)

# [0]
# [0, 1]
# [0, 2]
# [1]
# [1, 2]
# [2]

These lists are derived as follows. I only explain the computation of the first two, commenting step by step what the code does.
w = [-1]

The argument w is initialized to the list [-1]. This assignment is only evaluated once.
while w:

While the list w is not empty (i.e., w != []), do the following:
w[-1] += 1

Add one to the last element of w. The value of w is now [0].
yield w

Create an element for the generator. The first element will be [0], this is what we have printed above.
m = len(w)
while len(w) < n:
    w.append(w[-m])

Compute the size of w, and extend w to a size n by appending to it the value w[-m] as many times as needed. m is 1, n is 2, and w is [0], so the new value of w is [0, 0].
while w and w[-1] == s - 1:
   w.pop()

While w is not an empty list and its last element equals s - 1, remove the last element. The value of w, which is [0, 0] at this point, does not satisfy the last test, so we do not execute w.pop() and we go back to the outer while.
while w

The value of w ([0, 0]) is not an empty list, so we execute the body of the while loop.
w[-1] += 1
yield w

Add one to the last element of w. The value of w is now [0, 1]. Create another element for the generator. The second element will be [0, 1], which is what we have printed above.
From the above explanation, it should hopefully be clear how the next elements of the generator are created. Note that these elements are not all created when calling LyndonWords. They are computed one by one on the fly, only when requested. (This is one of the features of generators in Python.)

Lyndon words and Duval's algorithm


Scipy's fmin sticks only on inf only sometimes

Question: I'm using Scipy's fmin search to compute the log of the likelihood of a distribution's fit to some data. I'm using fmin to search for the parameters that maximize the log likelihood, like so:
j = fmin(lambda p:-sum(log(likelihood_calculator(data, p))), array([1.5]), full_output=True)

(likelihood_calculator takes data and a parameter and spits out an array of likelihood values for each data point.)
If we start that search with a parameter that yields a likelihood of 0, the loglikelihood is -inf, so the -sum is inf. fmin should run away from the initial parameter, but instead it sticks on that value for the maximum number of calls, then returns it:
In [268]: print j
(array([ 1.5]), inf, 67, 200, 1)

I thought this was perhaps a problem with fmin's handling of infs, but if we remove the likelihood calculator and just hand a 0 directly, we get better behavior:
In [269]: i = fmin(lambda p: -sum(log(p)), array([0]), full_output=1)
Warning: Maximum number of function evaluations has been exceeded.

In [270]: i
Out[270]: (array([  3.16912650e+26]), -61.020668415892501, 100, 200, 1)

This same correct behavior happens if we use an array of zeros, if those zeros are floats, or if we use fmin_bfgs. The same incorrect behavior with the function call continues if we use fmin_bfgs, but fmin works CORRECTLY if we start with a parameter that doesn't yield a 0 likelihood (and thus any infs).
Thoughts? Thanks!
Update:
If there's a broad area of parameters that result in zeros, we can push the parameter value up to the edge. If the parameter is near enough the edge, fmin will get out of zeroland and start searching.
Ex. p<1 = Inf, then at p=.99 fmin will work, but not at p=.95
Answer: Maybe your update answers the question. Since fmin uses a downhill gradient algorithm, it searches in a neighborhood of the initial guess for the direction of steepest descent. If you are deep enough into a parameter-region where the function always returns inf then the algorithm can not see which direction to go.
Comment: That seems to have been it. As only some of the data points in the array would return 0 (which then set the whole `sum` to `inf`), I instead set zeros to `sys.float_info.min`, which is sufficiently accurate for this use case. This meant the whole array of data points returned a coherent, non-`inf` `-sum(log(likelihood))`, which has a gradient `fmin` can search over


Operator that gives the size of range

Question: Let $A$ be the space of functions from $[0,1]$ to $\mathbb{R}$. Is there a well-defined operator, say $p$, that gives the size of $f\in A$'s range? For example, if $f(x)=\begin{cases}0&\text{ if }x\leq 0.5\\1&\text{ otherwise}\end{cases}$, then $p(f)=2$.
Is there a such operator that is easy to work with, i.e. $p(f)=\int_0^1 f(x)w(x)dx$ for some $w(x)$? (I think this would not be an answer, but just wanted to emphasize that I want the operator to be easy to work with).
Comment: In what way does that function's range is of size 2? You should probably explain what you mean by «size of the range», as I don't think it is clear.
Comment: All operators of the form you propose are linear, and whatever it is you mean by size it looks like it will not be a linear function...
Comment: By the way, your «the size of $f\in A$'s range» makes a great example of something one should never ever write! Try to read it aloud to see why.
Answer: If we don't assume anything about $A$ like it being a space of continuous functions, then your question doesn't make sense. If we make such an assumption, then one way would be $$p(f)=2\min_{t\in \Bbb R}\left(\lim_{n\to\infty}\sqrt[n]{\int_0^1|f(x)-t|^ndx}\right)$$in other words, move $f$ up or down until the sup norm is at its minimum, and then double that sup norm.

Operator that gives the size of range


Key event not fired when opening a view as sheet (or modal)

Question: I have a view controller with some controls (listview, buttons, etc.) called "ListaViewController"  where I capture key events with this code:
override func keyDown(with event: NSEvent) {

        if keyIsDown == true {
            return
        }
        keyIsDown = true
        if event.keyCode == 36  && abiertaLista == true && ventana == "Lista" {
             //do something
        }
}

I have another viewcontroller called SettingsViewController which I open from a button in the first controller with this code
self.presentAsSheet(BorrarViewController)

if I don't open the second controller, the capture key events function works well in the first controller, but if I open the second as sheet (or modal) and close it, then the capture event function is not fired in the first controller.
What am I doing wrong?
Thanks in advance
Update:
The process is like this I have a main controller, the init controller, called ViewController (as per default), which has a keyevent handler logic, then with a button I open ListaViewController which also have a keyEvent handler logic. When I try to open and close any alert or viewcontroller as modal or sheet, then in ListaviewController the keyevent handler fires nothing.
I´m sorry, but I deleted the button that load the alert or viewcontroller and its code (rage is bad...)
To clarify, in ViewController I have another code to handle the keyevents :
class ViewController: NSViewController {

    override var acceptsFirstResponder: Bool { return true }
    ///Lots of more code
}

Comment: WHY ARE WE YELLING?!
Comment: Tittle fixed, sorry
Comment: How do you close the sheet?
Comment: I think the issue is that your key events are being delivered to your `BorrarViewController` when it's open, and not your `ListaViewController` (which would no longer be the first responder). I would introduce a coordinator class, and make both VCs delegate to it, by making their `keyDown` events call a common method on the coordinator, which could be the central key-handling logic for this area of the UI.
Comment: @Alexander the `BorrarViewController` is closed.
Comment: The key event handle logic is made in ListaViewController, BorrarViewController has no key event logic. I close the BorrarViewControler with:

self.dismiss(self)

By the way, i tried with this code in the BorrarViewController CloseButton :

if let controller = self.storyboard?.instantiateController(withIdentifier: "ListaView") as? ListaViewController {
            abiertaLista = true
            cuentaPrincipio += 1

            self.view.window?.contentViewController = controller
         }

And it works, but it loads again ListaViewController...
Comment: @Willeke Oh I see.
Comment: @PabloJiménezRevilla What is the first responder at the moment after your `BorrarViewController` is closed?
Comment: @Aleksander i really dont know. Wich should be?? Im not too good with first responder handling
Comment: @PabloJiménezRevilla IDK, check it. That's why I'm asking :p
Comment: ok, i tried to know with: print("ES: \(view.window?.firstResponder)"), and before opening the BorrarViewController it prints: Optional()

It prints the same when i close BorrarViewController
Comment: @Aleksander Any ideas?
Comment: I tried your code but I can't reproduce the issue. Post a [mre] please.
Comment: @Willeke do you mean a video???? because if not i would have to make a new project... but i have mine on github https://github.com/pablormago/RetroMac

Can i send you a PM??

Edited: i can´t find a way to PM you, i´ll try to update my question with my code
Comment: No, not a video, just enough information the reproduce the issue. I'll take a look at the github code.
Comment: I deleted the way i open a modal alert or viewcontroller, and it´s not in github, sorry...
Answer: OK. So i removed this line in the view.willAppear :
self.view.window?.styleMask = [.borderless]

and it worked... don´t know why but it works now...
Comment: Could you please elaborate in more details how your question and your answer are connected to each other? Specifically, in the answer you're referencing some code being edited, which was not mentioned in the question.


fazer um submenu - exemplo em um site abaixo

Question: gostaria de adaptar o meu código para criar um submenu como este aqui :
http://red-team-design.com/wp-content/uploads/2011/03/css3-dropdown-menu-demo.html
por exemplo em "categories" - "css" depois aparece outro menu de lado com as mesmas propriedades do que o de cima e gostaria que o meu fosse assim.

Pagina Inicial

        Produtos

Inserir

Ver produtos no site

Caps

Camisas

Procurar

Eliminar

Listar

    A nossa Empresa

História

Valores

Localização

Contactos

Contacte-nos

#menu{

    width: 57%;
    margin: auto;
    padding: 15px 0 0 0;
    list-style: none;
    background: #111;
    background: -moz-linear-gradient(#444, #111);
    background: -webkit-gradient(linear,left bottom,left top,color-stop(0, #111),color-stop(1, #444));
    background: -webkit-linear-gradient(#444, #111);
    background: -o-linear-gradient(#444, #111);
    background: -ms-linear-gradient(#444, #111);
    background: linear-gradient(#444, #111);

}
#menu2{

    width:78%;
    border: medium none;
    float: center;
    text-decoration: none;
    margin: auto;
    background: #111;
    background: -moz-linear-gradient(#444, #111);
    background: -webkit-gradient(linear,left bottom,left top,color-stop(0, #111),color-stop(1, #444));
    background: -webkit-linear-gradient(#444, #111);
    background: -o-linear-gradient(#444, #111);
    background: -ms-linear-gradient(#444, #111);
    background: linear-gradient(#444, #111);
    -moz-border-radius: 20px;
    border-radius: 50px;
    -moz-box-shadow: 0 2px 1px #9c9c9c;
    -webkit-box-shadow: 0 2px 1px #9c9c9c;
    box-shadow: 0 2px 1px #9c9c9c;

    }

.imagem:hover{
    box-shadow: 0 3px 22px #9c9c9c;
    width:60;
    height:60;
}
 .alinhar {
     position: relative;
   width: 44%;
    }

.alinhar form{
    position: absolute;
    top: -2em;
    width: 150px;
    padding: 20px;
    font-weight: bold;
    right:50px;

}

#bodyy{
        margin-top: -38px;
        margin-right: 350px;
        margin-left: 350px;
    background: #111;
    background: -moz-linear-gradient(#444, #111);
        background: -webkit-gradient(linear,left bottom,left top,color-stop(0, #111),color-stop(1, #444));
    background: -webkit-linear-gradient(#444, #111);
    background: -o-linear-gradient(#444, #111);
    background: -ms-linear-gradient(#444, #111);
    background: linear-gradient(#444, #111);
    -moz-box-shadow: 0 2px 1px #9c9c9c;
    -webkit-box-shadow: 0 2px 1px #9c9c9c;
    box-shadow: 0 2px 1px #9c9c9c;

}
#btn {

  -webkit-border-radius: 28;
  -moz-border-radius: 28;
  border-radius: 28px;
  font-family: Courier New;
  font-size: 15px;
  background: #292c2e;
  padding: 13px 20px 10px 20px;
  text-decoration: none;
  float:left;

}

#btn:hover {
  background: #292c2e;
  cursor:hand;
    background: #fafafa;
    background: -moz-linear-gradient(#04acec,  #0186ba);
    background: -webkit-gradient(linear, left top, left bottom, from(#04acec), to(#0186ba));
    background: -webkit-linear-gradient(#04acec,  #0186ba);
    background: -o-linear-gradient(#04acec,  #0186ba);
    background: -ms-linear-gradient(#04acec,  #0186ba);
    background: linear-gradient(#04acec,  #0186ba);
}

#menu li{

    float: left;
    padding: 0 0 20px 0;
    position: relative;

}

#menu a{
    float: left;
    height: 20px;
    padding: 0 45px;
    color: #999;
    text-transform: uppercase;
    font: bold 12px/25px Arial, Helvetica;
    text-decoration: none;
#menu li:hover > a{
    color: #fafafa;
}

*html #menu li a:hover{ /* IE6 */
    color: #fafafa;
}

#menu li:hover > ul{
    display: block;
}

/* Sub-menu */

#menu ul{
    list-style: none;
    margin: 0;
    padding: 0;
    display: none;
    position: absolute;
    top: 35px;
    left: 0;
    z-index: 99999;
    background: #444;
    background: -moz-linear-gradient(#444, #111);
    background: -webkit-gradient(linear,left bottom,left top,color-stop(0, #111),color-stop(1, #444));
    background: -webkit-linear-gradient(#444, #111);
    background: -o-linear-gradient(#444, #111);
    background: -ms-linear-gradient(#444, #111);
    background: linear-gradient(#444, #111);
    -moz-border-radius: 5px;
    border-radius: 5px;
}

#menu ul li{
    float: none;
    margin: 0;
    padding: 0;
    display: block;
    -moz-box-shadow: 0 1px 0 #111111, 0 2px 0 #777777;
    -webkit-box-shadow: 0 1px 0 #111111, 0 2px 0 #777777;
    box-shadow: 0 1px 0 #111111, 0 2px 0 #777777;
}

#menu ul li:last-child{
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
}

#menu ul a{
    padding: 10px;
    height: auto;
    line-height: 1;
    display: block;
    white-space: nowrap;
    float: none;
    text-transform: none;

}

#menu ul a:hover{
        background: #0186ba;
    background: -moz-linear-gradient(#04acec,  #0186ba);
    background: -webkit-gradient(linear, left top, left bottom, from(#04acec), to(#0186ba));
    background: -webkit-linear-gradient(#04acec,  #0186ba);
    background: -o-linear-gradient(#04acec,  #0186ba);
    background: -ms-linear-gradient(#04acec,  #0186ba);
    background: linear-gradient(#04acec,  #0186ba);
}

#menu ul li:first-child a{
    -moz-border-radius: 5px 5px 0 0;
    -webkit-border-radius: 5px 5px 0 0;
    border-radius: 5px 5px 0 0;
}

#menu ul li:first-child a:after{
    content: '';
    position: absolute;
    left: 50px;
    top: -8px;
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 8px solid #444;
}

#menu ul li:first-child a:hover:after{
    border-bottom-color: #04acec;
}

#menu ul li:last-child a{
    -moz-border-radius: 0 0 5px 5px;
    -webkit-border-radius: 0 0 5px 5px;
    border-radius: 0 0 5px 5px;
}

/* Clear floated elements */
#menu:after{
    visibility: hidden;
    display: block;
    font-size: 0;
    content: " ";
    clear: both;
    height: 0;

}

Comment: Olá, bemvindo ao [pt.so]. Por favor, leia os guias [ask] e [about]. Você deve demonstrar que tentou resolver o problema, podemos ajudar com o código mas não escrever do zero para você. E se tem urgência é melhor contratar um profissional.
Comment: O site que você linkou é um tutorial completo de como fazer isso!
Comment: espero a sua resposta o mais rápido possível prf. Urgente
Answer: A resposta à sua pergunta está no artigo do próprio site do exemplo que compartilhou. Dê uma olhada com calma no material presente em: CSS3 Dropdown Menu. A resposta está ali, já montada e pronta pra uso.
Comment: Não é o tipo de resposta que merece voto positivo (por ser *link-only* e passível de ser convertida em comentário por um moderador). Mas neste caso é perfeita +1+


Configuration qualifers - Multiple screen size

Question: I'm creating an application for smartphone tablet and televison.
I'm creating my different displays, but I can not differentiate the tablet from the television.
I read https://developer.android.com/guide/practices/screens_support.html
I have tried many things, large,xlarge sw720dp, W1024dp.. but nothings works. I work with the emulator.
AndroidTv 1080p  API 25, Résolution 1920*1080:xhdpi
Nexus 5 API 24  Résolution 1080*1920:xxhdpi
Nexus 7  1200*1920 xhdpi
Thanks for your help !
Comment: Use `-television` to distinguish a television from a mobile device with respect to resources. See [the docs](https://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources).
Answer: The documentation you want is here: https://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources
The important parts of this page are Table 2 (configuration qualifier names) and the section titled How Android Finds the Best-matching Resource.
Reading these, it is clear that you will use the Smallest width qualifier to differentiate between phone and tablet devices, and the UI mode to differentiate between televisions and non-televisions. This directory structure should work:
res/
    layout/
        layout.xml (default (i.e. phones))
    layout-sw600dp/
        layout.xml (non-televisions 600dp or wider (i.e. tablets))
    layout-sw600dp-television/
        layout.xml (televisions 600dp or wider)

Because the Smallest width qualifier has a higher precedence than the UI mode qualifier, if you tried to just use layout-television you would find that your TV still used the -sw600dp layout.
Comment: Thank you for your help, but unfortunately the TV opens layout.xml (default) .
Comment: I don't know if it plays, but when I am in the layout "television" I can't choose android tv as device in design.
i mean when i  choose TV, this redirect me on activity_main (default) and change the device, and so the activity_main(television) keep Nexus4.
Nevertheless I have the nexus 7 on the tablet design and the nexus 5 on the default but I can not put the tv on Televesion
Comment: Finally, i used :
  res/
        layout/
            layout.xml (default (i.e. phones))
        layout-sw600dp/
            layout.xml (non-televisions 600dp or wider (i.e. tablets))
        layout-land-television-notouch/
            layout.xml (televisions)

                               And it works, I don't know why I had the problem with my previous review but good, it works now so thank you


cPanel & DirectoryIndex - server default page showing for domain root

Question: I'm pretty sure that I have a very trivial problem and that lots of you guys have answered this kind of question a thousand times. But I just can't find any of these answers. So here we go.
I am managing a hosting account via cPanel. But for some reason trying to access the website's index file by just typing in the domain name (e.g. www.mydomain.com) always shows the cPanel default page (i.e. www.mydomain.com/cgi-sys/defaultwebpage.cgi). The site works fine if I specifiy the index file name (i.e.  www.mydomain.com/index.php).
At first I thought it had somewhing to do with the DirectoryIndex configuration. So I checked the Apache conf, and everything seems to be in order (DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml). Just do be sure I added a .htaccess to the server root with the same directives.
But to no avail. What am I doing wrong?
Answer: Are you sure it's not cached at your client? Have you checked with a different browser or a cleared cache? I've found that at least firefox is pretty stubborn in caching the cpanel default redirect.
Comment: D'oh! That was exactly it!!!  I just trusted the the old Ctrl-F5 would do it in FF, but no. Just tried it in Chrome and all's good. FF's annoyance factor's rising...:(


Gravar Caminho do FileUpload dentro de um UpdatePanel ASP.NET

Question: Caros,
A pergunta da minha dúvida é bem simples. Como faço para gravar o caminho do meu arquivo do FileUpload em algum controle ou ViewState, com esse FileUpload estando dentro de um UpdatePanel?
Na verdade estou usando o controle AJAX do AsyncFileUpload, já que um simples FileUpload não funciona com Post Back parcial. Quanto a isso sem problemas. Então, eu gravo o arquivo selecionado na página no meu servidor, porém ao mesmo tempo que eu gravo eu preciso usar esse mesmo caminho (full path) para usar ele depois, em um evento de um botão. Já tentei usar ViewState, já tentei alterar algumas propriedades do UpdatePanel, já tentei encontrar uma forma de fazer isso com JavaScript, mas nenhum desses recursos surtiu efeito.
Alguém saberia me dizer como poderia resolver esse problema?
Agradeço desde já a ajuda de todos.
Abraços!
Comment: Caso tenho solucionado o seu problema, marcar como resposta.
Answer: Depois de buscas e buscas, finalmente eu consegui encontrar a única solução. Na verdade é até simples. Adicionei um controle do tipo hidden (HiddenField) na página para gravar a informação que eu quero. Tem um evento do AsyncFileUpload chamado OnUploadedComplete, onde trabalhando dentro desse evento bastou eu adicionar um ScriptManager para gravar o valor da variável que eu queria nesse controle hidden que coloquei na página, simples assim. Agora eu posso trabalhar dessa maneira que eu quero, e sinceramente me parece a única maneira de se fazer isso. De qualquer forma, se alguém souber outra maneira de fazer, por favor deixem seu comentário, sempre é bem vindo.
Este seria o script:
ScriptManager.RegisterStartupScript(this, this.GetType(), "path", "top.$get('" + hfCaminhoArquivo.ClientID + "').value = '" + filePath + "';", true);
Aqui foi onde encontrei a resposta:
Answer: Com panel também não consegui, e usando hiddenfield aqui deu certo!
Veja se o exemplo é útil. No final vai ficar o nome e a extensão:
string fileName;
 if (fuArquivo01.HasFile)
 {
  fileName = null;
  fileName = fuArquivo01.FileName;
  fileName += System.IO.Path.GetExtension(fuArquivo01.FileName).ToLower();
  HiddenField1.value = fileName;
 }

Comment: Caso tenho solucionado o seu problema, marcar como resposta.


Folders missing in project pane in Webstorm

Question: I've built a project in WebStorm and then submitted the project to GitHub.
When I rebooted the computer and relaunched WebStorm (and the project), all I can see in the project pane is the root files, and none of the folders (yes the folders are there)
See the image below for reference.
Does anyone know how I can get those folders to re-appear in the project pane of Webstorm?
Answer: It can be caused by the corrupted .idea/modules.xml project file. You can either try to fix it manually (restore from Local History, version control or backup) or create the new project from scratch.
Check this issue for the hints/workarounds.
Comment: Yup, just got an email back from Jetbrains. I had to do a terminal command `$ rm -r .idea` then open the directory in Webstorm. This rebuilt the project for me.
Comment: in fact, I got the email from you ;-) Thanks for the help and direction.
Comment: I was able to just delete the `modules.xml` file. It saved the rest of the project settings, which was welcome.
Comment: Sometimes, only `restarting IDE` helps!
Comment: For me, manually deleting .idea file didn't work but doing rm -rf did. Weird.
Comment: @dasfdsa a little late now, but it's because it's a folder not a file.
Answer: It happens sometimes in WebStorm 9.
The easiest way to fix it for me:

close WebStorm;
in project's folder remove .idea/ (hidden directory);
open your project, enjoy:)
Comment: so you're just repeating what the accepted answer states... 3 years later? http://stackoverflow.com/a/9302503/124069 (read the comments)
Comment: @ChaseFlorell in accepted answer you have to read comments, check links (spend extra time). This answer provides 3 simple steps and off you go.
Comment: I'm trying this but not getting any result in the latest Webstorm version 2021.1.1. anyone have faced the same? I just can't see the files in my project.
Answer: Solution:

Creating a new project from existing sources

File => New => Project
Select "Empty Project"
Browse to the location of your project with folder issues
Click "Create"
Select "Create from Existing Sources" in the "Directory Is Not Empty" dialog

Why this solution:

Editing and deleting in various combinations of .idea and XML files did not solve the issue for me. Hence the solution above. Back up your .idea directory in case you have project customizations you want to keep. This likely overwrites them.
Outcome:

All the various folders I had created were now visible and the project worked as expected. The .idea directory was now formatted correctly with all the necessary files.
Answer: Find the .idea/modules.xml in your project root
make sure that these lines are correct :
<modules>
  <module fileurl="file://$PROJECT_DIR$/.idea/NameOfYourProject.iml" filepath="$PROJECT_DIR$/.idea/NameOfYourProject.iml" />
</modules>

Replace NameOfYourProject.iml with the name of your project.
Then, make sure that the file .idea/NameOfYourProject.iml exists, if not , create it and put this in it :
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
  <component name="NewModuleRootManager">
    <content url="file://$MODULE_DIR$" />
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="module-library">
      <library name="PHP">
        <CLASSES>
          <root url="file://$MODULE_DIR$/../../php/PEAR" />
        </CLASSES>
        <SOURCES />
      </library>
    </orderEntry>
  </component>
</module>

Comment: For me `NameOfYourProject.iml` was pointing to the wrong file. Updating it to the correct file name fixed my issue and I didn't lose any settings.
Comment: Thanks, creating the new project was quick and painless.
Answer: You do not need to delete whole .idea folder and reconfigure your whole project, just

delete the .idea/modules.xml
restart the IDE and your folders are there again!
Answer: I ran into the same issue and resolved it by invalidating the cache.
The option is under File > Invalidate Caches/Restart.
On the prompt click Invalidate and restart.
Note: The project in concern needs to be open before you do this.
Answer: I see this from time to time. I use Git, and I have my .gitignore file set up as recommended, specifically:
.idea/workspace.xml
.idea/tasks.xml
.idea/*.iml

I sometimes see this after cloning the repository, and when trying to figure out why, I came across this post and read the accepted answer.
I deleted the modules.xml file and reopened WebStorm (2016.2.4), and it was resolved. I looked at the new modules.xml and found that its contents were exactly the same as before, but my <projectName>.iml file was bigger.
So it seems to be a corruption in the .iml file, not modules.xml. I assume that deleting modules.xml triggers a rebuild of the .iml file. Not sure if this helps anyone with anything, but thought I would offer the extra insight.
Answer: floor 36  solve my problem. in WebStrorm 11
It happens sometimes in WebStorm 9. The easiest way to fix it for me:

close WebStorm;
in project's folder remove .idea/ (hidden directory);
open your project, enjoy:)
Answer: Try deleting workspace.xml and watchertask.xml then just restart the IDE. You must see your full source code in all folders there.
Answer: Finally I found the culprit, it was Team Foundation Server - Version Control Integration plugin from https://plugins.jetbrains.com/plugin/7961-team-foundation-server--version-control-integration/
I looked at the system/log/idea.log file and found that this plugin was producing Null exception whenever I open a new folder as a new project and breaks the content root auto detection by the IDE, and after I uninstalled this plugin, all folders show up as it should.
You might have this issue because of a culprit plugin, and disabling those which you have just installed recently just before  this issue occurs, will resolve the issue. Check the log file and search for ERROR.
If it is found to be an important plugin you are actively using which you are not willing to disable, then a temporary fix is to open Settings->Directories and click Add content root button to add the root folder of your project, click Ok now folders will show up and indexing will begin, and of course you have to do this everytime you open a new folder as new project.


AJAX Views with filter as path component

Question: I have a view of Commerce products of type Print. The product type Print has a reference on a Taxonomy called Category. I setup the Category field as an exposed filter (dropdown) for my View page. The View uses AJAX and the URL is /prints.
If I want to load my View with a preselected category, I can go to http://d8.local/prints?category=1 which displays the View already filtered and with the corresponding category selected in the dropdown.
I could setup a contextual filter and a relationship on the View and set the path to prints/% so that I could filter and access it as http://d8.local/prints/landscapes where landscapes is one of the vocabulary terms, which feels better than ?category=1.
When I do so however, going to http://d8.local/prints/landscapes then using the exposed filter, it will filter the already filtered results. Also going to /landscapes doesn't select the option in the dropdown.
Is there a way to combine the 2 functionalities?
Edit:
To summarize the functionalities I am after:

I should be able to filter the products by category by adding the vocabulary term name as a path component, ie. /prints/landscapes.

When accessing the View with the category as the path component, the appropriate category exposed filter dropdown option should be selected, ie. Landscapes should be selected in the dropdown if accessing /prints/landscapes.

I should be able to filter the View using AJAX when manually selecting another category from the exposed filter dropdown.

The main page title must be updated based on the category whichever way the view was loaded (page load and AJAX reload)

Ideally, I would update the URL when manually selecting a category from the dropdown, but I suppose that's a separate question and it shouldn't be too hard to handle.
Comment: Can you clarify what exactly is your goal? How important is the link? You can make the term name appear in the Exposed filter (use Relationship). You could use Summary option of the Contextual filter instead of the Exposed filter, this would provide an interface for user to choose an option, and then when click through they would see the "nice" link. What do you want to achieve WRT user filtering a term, having a term preselected, having the URL show something in particular?
Comment: @prkos please see my edit in the question
Answer: There are many ways to solve this, you can take different approaches to the filtering part, the URL part, and the contextual part, and how they play together to get you to your goal. Here's one of the possibilities, probably the easiest route:

This is solved by adding a Relationship for the category field, and then adding a Term "Name" Contextual filter (it will automatically use that Relationship). Be mindful how you configure the spaces/dashes options. This will give you the term name in the URL instead of the term ID.
To get the Exposed filter to match the Contextual you need to use the Views Filter Harmonizer module. There's no workable D8 version yet, you can try and help there, there is an issue open for it.
If you've set up the Exposed filter properly, and turned Ajax on, it should work without a page reload. The "harmonizer" module also claims to play well with that.
I might be missing something here, I wouldn't expect that the Addressbar updating without a page reload is easy, but again the "harnomizer" module claims to do just that, so it seems you're covered if you can get that module to D8.

Another module that might be relevant in another approach: (also no D8 yet) Query Parameters To URL , but similar outcome can be done through your server configuration.
Comment: Thanks for that. I'll investigate further then. I might try to achieve that without an additional module. I'll post my findings anyway.
Answer: I tried many different complicated approaches, before I found a much easier solution that suits my needs so I am posting this as a solution.
I setup my prints View this way:

Category is added as an exposed filter
No contextual filter, no relationship
Set the view path to prints/%
Use AJAX: Yes

I created a module and used hook_views_pre_build() to get the category from the url parts, ie. get landscapes from the path /prints/landscapes then load the vocabulary term by name and if the term exists, set the exposed filter to the term id.
/**
 * Implements hook_views_pre_build().
 */
function MYMODULE_views_pre_build(\Drupal\views\ViewExecutable $view) {

  $view_ids = ['prints'];

  if (isset($view) && in_array($view->id(), $view_ids)) {

    // Get exposed input
    $exposedInput = $view->getExposedInput();

    // If exposed input is not set
    if (empty($exposedInput['category'])) {

      // Get current path
      $current_path = \Drupal::service('path.current')->getPath();
      $uri_segments = explode('/', $current_path);

      // 2nd uri segment is the category (term name)
      $current_category = isset($uri_segments[2]) ? $uri_segments[2] : NULL;

      if ($current_category !== NULL) {

        // Set vocabulary id
        $vid = 'photo_category';

        // Load term by name from vocabulary
        $term = \Drupal::entityTypeManager()
          ->getStorage('taxonomy_term')
          ->loadByProperties(['vid' => $vid, 'name' => $current_category]);

        // If term was found
        if ($term) {

          // Get first array element
          $term = reset($term);

          // Filter view by setting exposed input to term id
          $view->setExposedInput(['category' => $term->id()]);
        }
      }
    }
  }
}

This fixes filtering the view on page load when the category is in the URL.
As I also wanted to update the page title based on the selected category, I created an EventSubscriber for the AJAX response. All I do here is load the Category term name based on the exposed filter value, then use an HtmlCommand to update the page title.
<?php

namespace Drupal\MYMODULE\EventSubscriber;

use Drupal\views\Ajax\ViewAjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\taxonomy\Entity\Term;

/**
 * Response subscriber to handle View AJAX responses.
 */
class ViewAjaxResponseSubscriber implements EventSubscriberInterface {

  /**
   * Adds an AJAX command to ViewAjaxResponse.
   */
  public function onResponse(FilterResponseEvent $event) {

    $response = $event->getResponse();

    if ($response instanceof ViewAjaxResponse) {

      $view_ids = ['prints'];
      $view = $response->getView();

      if (isset($view) && in_array($view->id(), $view_ids)) {

        $titleSelector = '.page__header h1';

        if ($view->exposed_data['category'] !== 'All') {

          $term = Term::load($view->exposed_data['category']);
          $name = $term->getName();

          $title = 'Prints in category ' . $name . '';

          $response->addCommand(new HtmlCommand($titleSelector, $title));
        } else {

          $response->addCommand(new HtmlCommand($titleSelector, 'Prints - All categories'));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
  }

}

I'll do the same for when I load the view with the category in the URL, using hook_views_pre_render():
/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(\Drupal\views\ViewExecutable $view) {

  $view_ids = ['prints'];

  if (isset($view) && in_array($view->id(), $view_ids)) {

    if ($view->exposed_data['category'] !== 'All') {

      // Load category (term name) from View exposed filter data
      $term = Term::load($view->exposed_data['category']);
      $name = $term->getName();

      // Update View title with category (term name)
      $view->setTitle('Prints in category ' . $name . '');
    }
  }
}

My last requirement was to update the URL when the view would be filtered with AJAX so in my module Javascript file:
Drupal.behaviors.viewsAjax = {

    attach: function (context, settings) {

        // Attach action to Drupal Ajax Views event
        $(document).once('#views-exposed-form-prints-page-1', context).ajaxSuccess(function (event, data) {

            if ($('#views-exposed-form-prints-page-1').length) {

                let stateUri = '/prints/' + $('#views-exposed-form-prints-page-1 select[name="category"] > option:selected').text().toLowerCase();
                window.history.replaceState('', '', stateUri);
            }
        });
    }
};


Replay button script in unity3d

Question: I am working on an android app in unity it's allowed the user to enter voice or text(through the text field) then the user will get the animation that matches with the word entered by the character, also there is a repeat button that replay the animation if the user touches the button.
but now I am stuck in the repeat button code and I don't know where is the mistake.
Comment: I want the repeat button work and replay the animation but it doesn't.
Comment: It is not working at all? Did you set the logs (e.g. `Debug.Log("OnGUI() is called");)` in OnGUI() method? Is it called?
Answer: You can try to add listener to the button in Start() method:
void Start () {
    gameObject.GetComponent<Button>().onClick.AddListener(() =>
    {
        var animator = GetComponent<Animator>();
        animator.Play("BeginMove");
    });
}

Comment: in this line:                                          SomeButton.GetComponent().onClick.AddListener(() =>
{
Comment: You need to get the instance of the button and add listener to it. Something like in my edited answer.
Comment: I tried that but this error shown at the console:                                          MissingComponentException: There is no 'Animator' attached to the "Button (2)" game object, but a script is trying to access it.
You probably need to add a Animator to the game object "Button (2)". Or your script needs to check if the component is attached before using it.
Comment: I fix this problem by adding the animator component to the button Inspector... but the repeat button still did not work when I pressing it nothing happened, please if anyone knows how can I fix that help me.
Comment: is there another solution or code I can try it instead of what I write?
Comment: any suggestion?
Comment: maybe your Animation State Machine is not configured properly.
Comment: how can I know?
Comment: maybe docs will help you https://docs.unity3d.com/Manual/AnimationSection.html. It's hard to say without seeing the project.
Comment: do you think my repeat button code is written by correct way or should I change something in unity scene or in event system for the button?
Comment: You can set logs and you will see what's wrong. E.g. set logs to OnClick method and look if it is called. If it is called then you have to config animation scene, if it is not called - the problem in button event handling.
Answer: Can you try to get the reference of the object which has animator component attached to it.
You're trying to get the animator component from the button script, is the animator component attached to the gameobject?
      Try this
    public words CurrentObjectWithAnimator; //Take Reference for Animator

        void OnGUI()
          {
            if (GUI.Button(new Rect(10, 70, 50, 30), "Replay"))
            {
              //CurrentObjectWithAnimator = GameObject.Find("Current object with animator");
                var animator = CurrentObjectWithAnimator.GetComponent<Animator>();
                animator.Play("BeginMove");
            }
            }
           }

Comment: are you sure I have to use OnGUI while I create the button on the scene!

Replay button script in unity3d


TFS 2017 - Is there a way to create a NET NEW standalone WorkItem (form)?

Question: My manager has asked me to look into creating a whole new form for TFS - Change Request
I would imagine this is possible, but I really have no idea where to begin building this.
This is not part of the Agile Workflow form set that TFS comes with. It should stand on it's own.
I suppose they may want to integrate this later, so I will have to keep that in mind.
Comment: See: https://learn.microsoft.com/nl-nl/vsts/reference/add-modify-field?view=tfs-2018&viewFallbackFrom=vsts
Answer: I suspect that the "Change Request" you mentioned is a new Work Item Type. So you can follow the instruction here to do this: Add or modify a work item type.


Pull an item from all arrays MongoDB

Question: idk if this is possible but need some help with mongo, I have the following document, and I want to make it so I can use $addToSet to add a value to one of the items in votes, but remove that item from all the other items in votes but have no idea how
{
  _id: '872952643117518909',
  questions: [
    { question: 'a', number: 1, dropDownInfo: [Object] },
    { question: 'b', number: 2, dropDownInfo: [Object] },
    { question: 'c', number: 3, dropDownInfo: [Object] }
  ],
  votes: {
    '1': [ '619284841187246090', '662697094104219678' ],
    '2': [ '619284841187246090', '662697094104219678' ],
    '3': [ '662697094104219678', '619284841187246090' ]
  },
  question: 'abc',
  timestamp: 1628198528903,
  finished: false,
  channel: '812038854302892064'
}

Answer: The bellow pipeline adds a vote('619284841187246090') to a specific field,here randomly "2" was chosen,and removes that vote from "1" and "3" array.
Solution is general,can work with any vote fields not just "1" "2" "3".
You can use this pipeline in aggregation or update with pipeline (Mongodb>=4.2)
$addToSet doesn't work in arrays, it works when grouping and
in some other places in MongoDB 5.
I think your schema has a problem, because you are saving data in the schema, and that makes querying harder and creating indexing harder etc.
But we can still do it converting the object to array and back to object.
I think its best to keep data in arrays,and fields to be the known schema.
You can run the bellow code here
Query
db.collection.aggregate( [ {
    "$addFields" : {
      "votes" : {
        "$arrayToObject" : {
          "$map" : {
            "input" : {
              "$map" : {
                "input" : {
                  "$objectToArray" : "$votes"
                },
                "as" : "m",
                "in" : [ "$$m.k", "$$m.v" ]
              }
            },
            "as" : "vote",
            "in" : {
              "$cond" : [ {
                "$eq" : [ {
                  "$arrayElemAt" : [ "$$vote", 0 ]
                }, "2" ]
              }, [ {
                "$arrayElemAt" : [ "$$vote", 0 ]
              }, {
                "$cond" : [ {
                  "$in" : [ "619284841187246090", {
                    "$arrayElemAt" : [ "$$vote", 1 ]
                  } ]
                }, {
                  "$arrayElemAt" : [ "$$vote", 1 ]
                }, {
                  "$concatArrays" : [ {
                    "$arrayElemAt" : [ "$$vote", 1 ]
                  }, [ "619284841187246090" ] ]
                } ]
              } ], [ {
                "$arrayElemAt" : [ "$$vote", 0 ]
              }, {
                "$filter" : {
                  "input" : {
                    "$arrayElemAt" : [ "$$vote", 1 ]
                  },
                  "as" : "v",
                  "cond" : {
                    "$not" : [ {
                      "$eq" : [ "$$v", "619284841187246090" ]
                    } ]
                  }
                }
              } ] ]
            }
          }
        }
      }
    }
  } ])

Results
[
  {
    "_id": "872952643117518909",
    "channel": "812038854302892064",
    "finished": false,
    "question": "abc",
    "questions": [
      {
        "dropDownInfo": "",
        "number": 1,
        "question": "a"
      },
      {
        "dropDownInfo": "",
        "number": 2,
        "question": "b"
      },
      {
        "dropDownInfo": "",
        "number": 3,
        "question": "c"
      }
    ],
    "timestamp": 1.628198528903e+12,
    "votes": {
      "1": [
        "662697094104219678"
      ],
      "2": [
        "619284841187246090",
        "662697094104219678"
      ],
      "3": [
        "662697094104219678"
      ]
    }
  }
]

Pull an item from all arrays MongoDB


Uniform integrability and Lebesgue convergence

Question: A). Given that $ |X_n| \leq Y $ and $Y \in L$. Try to show $X_n$ is lebesgue integrable.
b). Try to give any example for which $X_n \longrightarrow^{L} X$ yet $\not\exists Y \in L$ with $|X_n| \leq Y$.
c). Try to give any example for which $X_n \to X$ w.p.1, and $X_n, X \in L$ yet $X_n \not\longrightarrow^L X$.
d). If $X_n$ is uniform integrable, does it follow that $g(X_n)$ is uniform integrable if g is continuous?
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Also, many find the use of imperative ("Prove", "Solve", etc.) to be rude when asking for help; please consider rewriting your post.
Comment: Maybe $L$ denote the set of integrable random variables defined on a probability space. In b), you have to give more precisions about what $X_n\to X$ means (in which sense), even if we can guess it.
Comment: Dear David, I have rewrite my description. In part b) what I mean is  $X_n \longrightarrow^L X$.
Answer:
There is no need of the parameter $n$: if $0\leq X\leq Y$ and $Y$ is integrable, it follows from the definition of Lebesgue integral that $X$ is integrable. If $0\leq s\leq X$ is a simple function, then $0\leq s\leq Y$ so $\sup\{\int S,0\leq S\leq X,S\mbox{ simple}\}$ is finite.
Try $X_n:=\sqrt n\chi_{((n+1)^{—1},n^{-1})}$.
Try $X_n:=n\chi_{((n+1)^{—1},n^{-1})}$.
Take $f$ an integrable function which is not in $L^2$. Then $X_n(x):=f(x+n)$ and $g(x)=x^2$.
Comment: Thanks for your answer, David. I have two wonderings: Is $\chi$ in part 2 means chi-square density? And how to show g(x) is not uniform integrable in part 4?
Comment: No, it's the characteristic function of a set. You have to show that $\{f(\cdot +n)^2\}$  is not uniformly integrable. If it was, it would be bounded $L^1$, so each function would be in $L^1$.
Comment: hi, david, can you please be more specific about what does $\chi_{(n+1)^{-1}, n^{-1}}$ mean?
Comment: Sorry, parenthesis where missing. $\chi_A(x)$ is $1$ if $x\in A$ and $0$ otherwise.


Android round button with shadow

Question: I am new to android I have a button in my app:
<Button android:elevation="10dp"
        android:id="@+id/btnAddJob"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/round_btn"
        android:drawableLeft="@drawable/plus"
        android:paddingLeft="9dp"
        android:gravity="center"
        android:layout_marginLeft="300dp" />

and the round_btn:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="oval" android:thickness="24dp" >
        <stroke android:color="@color/colorText" android:width="24dp" />
        <solid android:color="@color/colorText"/>
        <size android:width="150dp" android:height="150dp"/>
    </shape>
</item>

The problem is I want it to have shadow so the button seems higher than other elements. Can anybody help please?
Comment: Why not use a FloatingActionButton? https://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html
Comment: refer here : http://belencruz.com/2012/12/rounded-button-with-shadow-in-android/
Comment: @DanielNugent Yeah I had to use FloatingActionButton I don't know why I thought it's not best practice in my case
Answer: round.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:angle="90"
        android:endColor="@color/lgt_button"
        android:startColor="@color/drk_button" />

    <corners android:radius="20dip" />

    <stroke
        android:width="1px"
        android:color="@color/drk_button" />
</shape>

shadow.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@color/black_alpha" />

    <corners android:radius="20dip" />
</shape>

buttonbordershadow.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/shadow" />

    <item
        android:bottom="4px"
        android:drawable="@drawable/round" />
</layer-list>

set button background
android:background="@drawable/buttonbordershadow"

Source: Rounded button with shadow in Android
Comment: Please always mention the source from where you're taking the snippets.
Answer: just add material library :

implementation 'com.google.android.material:material:1.2.0-alpha03'

and use MaterialButton :
 <com.google.android.material.button.MaterialButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:textStyle="bold"
        app:cornerRadius="20dp" //you can set radius easily
/>

Answer: For API>=21 you can use ViewOutlineProvider
public class CustomViewOutlineProvider extends ViewOutlineProvider {
    int roundCorner;

    public CustomViewOutlineProvider(int round) {
        roundCorner = round;
    }

    @Override
    public void getOutline(View view, Outline outline) {
        outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), roundCorner);
    }
}

UI
    TextView textView = (TextView) findViewById(R.id.shadow_txt);
    textView.setOutlineProvider(new CustomViewOutlineProvider(30));
    textView.setClipToOutline(true);

Android round button with shadow


True Bypass Looper and Effects Loop

Question: I am thinking of getting myself a looper to control my effect pedals.
Right now some of my pedals are connected via the effects looper and some of them are in the amp front.
My question is, if I buy a looper and connect all pedals through the looper, will I only have to put all pedals through the front of the amp?
Answer: If you want all the effects to be loopable, then they will all be either in the amp input or the effects loop. I would tend to put them all in the effects loop.
To split them out you would need two loopers.
The only exception to this would be if there was a multi-track looper that let you route tracks from different inputs to different outputs. I haven't seen such a thing outside of a full featured DAW.
Comment: In which case, keep the compressor out front (you don't want to recompress every time the signal path loops) and use the looper with all the other effects in the amplifier's effects loop.
Comment: So, the standard practice is to not have to split them? (Put all pedals through Effects loop OR amp front)
Comment: it depends on what you need to loop. If you want everything you do to loop, then you need it in the looper, which means you can't split it.
Comment: Without looping, it is easier - you put effects where you want them to sound. It is different adding effects before the preamp and after - we have a question on that here somewhere.
Comment: BTW ... The only pedal I use in front is a Compressor
Answer: The looper I use is stereo (two channel). As these are discrete I guess you could incorporate each channel in each of your effects loops.This will keep everything separate, as it was before. I use it either for keyboards (stereo) or in conjunction with a pedalboard (also stereo), but if yours is for guitar alone, it'll maybe be mono, in which case my answer won't help ! As the good doctor says, any effect you want to loop/record will have to be routed through the looper.
Just realised you haven't bought it yet ! Consider a dual track looper - dearer, but probably more future-proof !

True Bypass Looper and Effects Loop


adding php to .tpl to check cookie value

Question: I'm trying to add a php script to a .tpl file that checks whether or not a cookie has been set:
<?php if (isset($_COOKIE['IA'])) echo "?campaign=333"; if (isset($_COOKIE['IA']) && isset($_COOKIE['Ptag'])) echo "&p=" . $_COOKIE['Ptag'] ;?>
I've tried including the php in {php} code {/php} and also {php} /file/function.php {/php}.
I've also tried code.
However, nothing seems to work. can any one help?
Comment: That's missing the point of templates. Put the cookie check in the PHP that *calls* the template, and add the result of that check to the data you inject into the template.
Comment: What is the code? Did you include smarty? Normally [{php}](http://www.smarty.net/docsv2/en/language.function.php.tpl) works
Comment: never add a php script in .tpl file. Just pass the output of your php script to ..tpl using $smarty->assign....
Answer: Use the smarty predefined variables:
http://www.smarty.net/docsv2/en/language.variables.smarty.tpl
for example:
{if $smarty.cookies.IA}?campaign=333{/if}{if $smarty.cookies.IA && $smarty.cookies.Ptag}&p={$smarty.cookies.Ptag}{/id}
this reveals some security problem such as XSS, so you better validate this params out of the template and pass only valid values to the template - but in general, the way I mentioned is the way to reach the $_COOKIE global