text:
Q: C# The type or namespace name could not be found I have a problem that has been driving me nuts.
I have 2 ASPX pages in which the parent use Server.Transfer() function. The parent is called Submit.aspx whereas child is called Review.aspx
In Submit.aspx.cs, I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Contacts_Submit : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Review_Click(object sender, EventArgs e)
    {
        Server.Transfer("Review.aspx", true);
    }

    /*
     * Sequence of functions that will server as a Get functionality that will
     * return the text inside each textbox.
     * These information will be used by "Review.aspx" to validate the
     * information given by the user before final submission takes place.
     */
    public string GetFirstName { get { return FirstName.Text; } }
    public string GetLastName { get { return LastName.Text; } }
    public string GetAddress { get { return Address.Text; } }
    public string GetCountry { get { return Country.SelectedValue; } }
    public string GetProvince { get { return Province.SelectedValue; } }
    public string GetCity { get { return City.Text; } }
    public string GetZipCode { get { return ZipCode.Text; } }
    public string GetWorkPhone { get { return WorkPhone.Text; } }
    public string GetMobilePhone { get { return MobilePhone.Text; } }
    public string GetFax { get { return Fax.Text; } }
    public string GetEmail { get { return Email.Text; } }
    public string GetCompany { get { return Company.Text; } }
    public string GetWebsite { get { return Website.Text; } }
    public string GetRelationship { get { return Relationship.SelectedValue; } }
}

Whereas on the Review.aspx.cs, I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Contacts_Review : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(PreviousPage != null)
        {
            Contacts_Submit prevpage = PreviousPage as Contacts_Submit;
            //FirstName.Text = PreviousPage.GetFirstName;
        }
    }
}

The problem is when I declare "Contacts_Submit prevpage = PreviousPage as Contacts_Submit". The system is giving me an error that says "The type or namespace name 'Contacts_Submit' could not be found (are you missing a using directive or an assembly reference?)".
I am a beginner in both ASP.NET and C#, can anyone help me with this? Thank you SOOO MUCH.

A: I think you just want
Contacts_Submit prevpage = PreviousPage as Contacts_Submit;

instead of
Contacts_Submit prevpage = PreviousPage as System.Data.DataSet Contacts_Submit;

A: Contacts_Submit is type of Page and not in any way related to Dataset, so your cast is invalid.
remove that and it should be fine


text:
Q: BizTalk 2020 SFTP Receive adapter not deleting files after downloading from MoveIT SFTP servers The issue is the BizTalk 2020 SFTP receive adapter does not delete the SFTP file after downloading it from a MoveIT SFTP server.
This issue has already been reported but I cannot find any resolution on-line yet:
https://winscp.net/forum/viewtopic.php?t=29529
Apparently it's an issue with different timestamps being returned from the stat and ls commands from MoveIT SFTP servers:
https://community.progress.com/s/question/0D54Q00007uR3uASAS/ls-and-stat-commands-return-different-timestamps
I am thinking of writing some C# code to manually delete the file as a temporary work around.
However, I would like to know if there are any plans to fix this issue in a future BizTalk Cumulative Update?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Box-shadow no funciona de la forma esperada para grandes valores en Safari Estoy desarrollando una pequeña librería/plugin en JavaScript que sirve para resaltar diferentes partes de una página (con la intención de crear instrucciones o similares). Pero me estoy encontrando con algunos problemas, especialmente con Safari.
Para el resaltado uso box-shadow porque presenta mejor compatibilidad que clip-path. Creo un elemento con dos sombras: una interna (para dar efecto de difuminado) y otra externa (que sombreará todo la página menos el objeto centrado).
Aquí dejo un ejemplo mínimo, completo y verificable del código que tengo:

#sp-frame {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

#sp-focus {
  position: absolute;
  top: 50px;
  left: 100px;
  width: 80px;
  height: 50px;
  border-radius: 100%;
  box-shadow: inset 0 0 8px 0 rgba(0,0,0,0.8), 0 0 0 200vmax rgba(0,0,0,0.4);
}

La idea es que se vea así:

Pero el problema es que en iPhone y Safari se ve así:

Probé las soluciones propuestas en Problema de compatibilidad con box-shadow, añadiendo los prefijos de navegador -webkit-box-shadow y -moz-box-shadow... Sin obtener un resultado positivo. También probé -webkit-appearance como se sugiere en Apariencia diferente de botones en safari iOS. También sin obtener el resultado esperado.
Para iPhone, encontré una solución un poco rara: si en lugar de poner border-radius: 100%, uso border-radius: 99%, entonces el sombreado externo se ve bien (como en la primera imagen). Pero eso no funciona en Safari.
Inicialmente pensaba que era un problema con la unidad vmax porque si ponía un valor en px (p.e. 200px) sí se veía bien. Por eso traté de calcular el ancho de pantalla con JavaScript y asignar ese valor * 2 a la sombra... Pero después de hacer algunas pruebas, me encuentro con que eso tampoco sirve.
Safari soporta vmax en la sombra, el verdadero problema es que si el valor generado es mayor que X (con X alrededor del tamaño de la pantalla aproximadamente), esa sombra deja de verse. Y eso es un problema, porque necesito que sea mayor que el tamaño de pantalla para asegurarme que no se van a quedar zonas de la pantalla sin sombrear.
¿Cómo puedo solucionar esto? ¿Existe alguna alternativa?

A: Kosh Very me envió una pregunta con un problema parecido en el sitio en inglés. En ella, responde que esto es un fallo que se produce en Safari cuando se usa un box-shadow con un valor muy grande combinado con un border-radius (probé y efectivamente si quito el border-radius, la sombra se ve bien incluso con 200vmax). Parece un bug de Safari, aunque no encontré referencia.
La solución que propone en su respuesta es usar un borde con el tamaño grande en lugar de usar un box-shadow. Esa solución requiere un cambio adicional (añadir una transformación con una translación), pero me sirve como alternativa porque funciona en Chrome también.
Aquí dejo el código:

#sp-frame {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

#sp-focus {
  position: absolute;
  top: 75px;
  left: 140px;
  width: 80px;
  height: 50px;
  border-radius: 100%;
  box-shadow: inset 0 0 8px 0 rgba(0,0,0,0.8);
  border: 200vmax solid rgba(0,0,0,0.4);
  transform: translate(-50%, -50%);
}


text:
Q: Pass the api key along with the request in Rails I have two Rails apps. One generates the API key, contains the api and requires the api key for some controller actions.
The second app is just an app for interacting with said api.
My question is, how do I - in the second app's controller - say "post to the first app's controller action and oh by the way pass this api key though for authentication"
I am not using oauth or anything else, just simple
  def restrict_api_access
    authenticate_or_request_with_http_token do |token, options|
      @api_key = ApiKey.find_by(api_key: token)
    end unless current_user
  end

So how do I - on each post , put or update (or even) delete - pass the api key along with the action request?


text:
Q: Installing Ruby on Godaddy Shared Hosting I'm trying to use Linuxbrew to manage my dependencies; however, when I attempt to install I receive an error.
Error: No such file or directory - /usr/local/bin/rub

I have attempted to install using the source files and running
./configur-prefix=$Home/env
make
make install

which gives the following report:
installing binary commands:   /env/bin
/home/tmiles199/downloads/ruby-2.4.1/lib/fileutils.rb:226:in `mkdir': Permission denied @ dir_s_mkdir - /env (Errno::EACCES)
from /home/tmiles199/downloads/ruby-2.4.1/lib/fileutils.rb:226:in `fu_mkdir'
from /home/tmiles199/downloads/ruby-2.4.1/lib/fileutils.rb:207:in `block (2 levels) in mkdir_p'
from /home/tmiles199/downloads/ruby-2.4.1/lib/fileutils.rb:205:in `reverse_each'
from /home/tmiles199/downloads/ruby-2.4.1/lib/fileutils.rb:205:in `block in mkdir_p'
from /home/tmiles199/downloads/ruby-2.4.1/lib/fileutils.rb:191:in `each'
from /home/tmiles199/downloads/ruby-2.4.1/lib/fileutils.rb:191:in `mkdir_p'
from ./tool/rbinstall.rb:194:in `makedirs'
from ./tool/rbinstall.rb:306:in `prepare'
from ./tool/rbinstall.rb:344:in `block in <main>'
from ./tool/rbinstall.rb:822:in `block in <main>'
from ./tool/rbinstall.rb:819:in `each'
from ./tool/rbinstall.rb:819:in `<main>'
make: *** [do-install-all] Error 1

Godaddy does not allow sudo or su access. The server info
gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-17)

I need Homebrew to install xz and glibc before I can install Ruby, or update the gcc version. Unfortunately, both produce the first error.
Could anyone help me install this package? My real endgoal is updating gcc through brew.

A: You don't have needed permissions to do that in the shared hosting:

in `mkdir': Permission denied @ dir_s_mkdir - /env (Errno::EACCES)

When you try to create the directory, the installation fails.
You need a VPS, a dedicated server or a shared hosting preconfigurated.

A: I have found out a workaround for this issue to be able to install homebrew without root and sudo access.
Just follow the instruction on the Alternative Installation section of brew.sh and it will wonderfully work with no mayor issues at all.
This option will not work if you do not meet the minimum requirements regarding the glibc version.


text:
Q: how to find the max in a datacolumn of datetime? I have a DataColumn of DateTime, I would like to know how I can have only the sooner date (min) and the later date (max).
Thanks

A: This would give what you are looking for:
// Initial Code for Testing
DataTable dt = new DataTable();

dt.Columns.Add("Dates", typeof(DateTime));
dt.Rows.Add(new object[] { DateTime.Now });
dt.Rows.Add(new object[] { DateTime.Now.AddDays(1) });
dt.Rows.Add(new object[] { DateTime.Now.AddDays(2) });

This is the code you would use:
// Actual Code
DataColumn col = dt.Columns[0]; // Call this the one you have

DataTable tbl = col.Table;

var first = tbl.AsEnumerable()
               .Select(cols => cols.Field<DateTime>(col.ColumnName))
               .OrderBy(p => p.Ticks)
               .FirstOrDefault();

var last = tbl.AsEnumerable()
              .Select(cols => cols.Field<DateTime>(col.ColumnName))
              .OrderByDescending(p => p.Ticks)
              .FirstOrDefault();

A: To add to the answer from kyle, isn't it easier to just do:
for greatest date:
var last = tbl.AsEnumerable()
               .Max(r => r.Field<DateTime>(col.ColumnName));

and for earliestdate:
var first = tbl.AsEnumerable()
               .Min(r => r.Field<DateTime>(col.ColumnName));

A: object maxDate = dataTable.Compute("MAX(TheDateColumnName)", null);
object minDate = dataTable.Compute("MIN(TheDateColumnName)", null);

A: Just retreive a List of DateTime from your DataColumn,
Foreach row in your DataColumn add the current element to your List of DateTime.
List<DateTime> and use Sort method then get the first and the last values.
Depending of your framework version, for 2.0 use above, for >=3.5
you can use Max and Min
or
With linq  .OrderByDesc(p => p.X).FirstOrDefault(); on your DateTime List

A: DataTable dt = new DataTable("MyDataTable");
DataColumn dc = new DataColumn("DateColumn");
dc.DataType = typeof(DateTime);
dt.Columns.Add(dc);
for (int i = 0; i <= 5; i++)
{
    DataRow newRow = dt.NewRow();
    newRow[0] = DateTime.Now.AddDays(i);
    dt.Rows.Add(newRow);
}

DateTime maxDate =
    Convert.ToDateTime(
                        ((from DataRow dr in dt.Rows
                          orderby Convert.ToDateTime(dr["DateColumn"]) descending
                          select dr).FirstOrDefault()["DateColumn"]
                          )
                        );

DateTime minDate =
    Convert.ToDateTime(
                        ((from DataRow dr in dt.Rows
                          orderby Convert.ToDateTime(dr["DateColumn"]) ascending
                          select dr).FirstOrDefault()["DateColumn"]
                          )
                        );

A: Simpliest for me:
make a dataset with a Table "Tablename" and a column "itemDate" ,set Datatyp System.DateTime
you can read all elements in a list of datetime and search for minDate
Dim List_Date As New List(Of DateTime)
Dim minDate As DateTime

For Each elem As DataRow In DataSet1.Tables("Tablename").Rows
            List_Date.Add(elem.Item("itemDate"))
Next

minDate = List_Date.Min


text:
Q: Click to edit fires all events again everytime I am trying to make a simple click to edit function for a page. Most of it works apart from when you click and edit multiple events. It always wanted to send the previous events again with the new click. Here's the code:
    $('.editable').click(function() {

        var that = $(this);
        if (that.find('input').length > 0) {
            return;
        }

        var currentText = that.text();
        var name = that.data('field');
        var contact_id = that.closest('[data-id]').data('id');
        console.log(contact_id);
        console.log(that);
        that.empty();

        console.log(name);

        var $input = $('<input>').val( $.trim(currentText))
            .css({
                'position': 'relative',
                top: '0px',
                //left: '0px',
                width: that.width(),
                height: that.height(),
                opacity: 1,
                padding: '15px',
                'margin-bottom': '0'
            });

        $(this).append($input);

        $(document).on('blur','.editable', function(){

            that.text( $input.val());
            console.log(contact_id);
            console.log(name);

            that.find('input').remove();

        });

p.s would you know why the on blur makes you need to click the element twice before clicking off to close it?
<div class="large-12" id="reviewsNeeded--main" data-id="<?php echo $result['id']; ?>">

                    <?php echo $result['first_name'] . " " . $result['last_name']; ?>

                    <?php echo get_term_by('id', $result['company'], 'publishers')->name; ?>

                    <button class="delete-btn" data-id="<?php echo $result['id'] ?>">
                        Delete
                    </button>

                        <button>Show More</button>

A: Every time you click you are adding a new blur handler on any .editable, with that scoped to the current context.  It sounds like you want to change:
$(document).on('blur','.editable', function(){

to
$(that).one('blur', function(){

so that it fires only once (.one) and only on the current input.


text:
Q: NCR unix system v/386 release 4 recover root password we have NCR 3455 system from long time as attached all information for server (images)  ,
so  we need your help to assist us to get root password which lost it , really we appreciate your efforts  if you can send us the procedure for resting the administrator (root) password
which this server handle data base application writing in COBOL language
your fast response and concerns highly appreciated

A: Boot from the installation media and then mount the disk and edit /etc/passwd, /etc/shadow if needed.
If you don't have the media, try to connect the disk to another system which can mount an old sysv-ufs in rw mode.


text:
Q: Use pyInstaller 2.0 to create executable of python script with specific arguments I have had success using pyInstaller 2.0 to create executables from simple python scripts. I have a python script which runs different searches and produces different output based on command line arguments. Is there a way to use pyInstaller to create an executable of the script assuming certain arguments? As in, I want to produce an exe file that will run and produce the same output as if I were to run it from the command line as follows:
python pacman.py --layout mediumMaze --pacman SearchAgent
Is this possible with pyInstaller 2.0? I have not been able to find this addressed in the provided manual. Thank you in advance.

A: This is sort of a roundabout way to do it, but you could import pacman.py in a separate python file, and call it in such a way that it does the things the command line arguments specify. Then, using pyinstaller, you would compile the separate python file.
If it's not possible to use pacman.py in that manner, you could try creating the following Python file and letting pyinstaller compile that.
import sys

sys.argv.extend(['--layout', 'mediumMaze', '--pacman', 'SearchAgent'])

import pacman
pacman.main() # if your file has a `main` function

(In both cases, pyinstaller would still combine the two files together into one exe)


text:
Q: How Do I display information from the joins table with the new Rails 3 query interface I have two models Horse and Race.
class Horse < ActiveRecord::Base
has_many :races
end

class Race < ActiveRecord::Base
belongs_to :horse
end

Now I want to use the new rails 3 query interface to see the Horse name and all its races.
Horse.joins(:races)  # I get an active record relation that only displays horse data

Horse.joins(:races).count #Yields 31 the exact number of races.

Horse.joins(:races).all #Yields an Array of 31 Horse, but no race data

Horse.joins(:races).all.select("horses.*, starters.*") #Yields active record relation with only Horse data.

Question 1: What's the correct query to yield complete horse and race records.
Question 2: What's the correct query to yield the horse name and all of the race record.
I know this is very basic, but I'm stumped. I sense I'd doing something wrong with the relation.

A: From what I can see I don't thing you're doing anything wrong with your relations.
If you want to see all horses with each of their races:
Horse.includes(:races).each do |horse|
  puts horse.name
  horse.races.each do |race|
    puts race.name
  end
end

Assuming I understand your question, your use of joins(:races) is irrelevant here. First, it will not automatically pull any data from the races table. It will simply add an inner join between horses and races. If horse N has 10 races, that query will then return 10 instances of horses N, which is probably not useful in this instance.
The includes(:races) above isn't strictly necessary - it just loads all the races at once with one query, as opposed to n queries (n being the number of horses). Just saves time and resources.


text:
Q: Sort Posts By Custom Field Date? I have the following code displaying evarying posts from a custom post type, however i need them displayed in date order from information put in a custom field, can this be done?
I try this code :-
      <?php $course = new wp_query( array ( 'posts_per_page' => '10' , 'post_type' => 'course','orderby' => 'meta_value_num',
'meta_key' => 'course_date','order' => 'DESC' ) ); ?>

But its show me data like this :-
30-12-2014
28-9-2014
26-10-2014
19-12-2014

It must be like :-
30-12-2014
19-12-2014
26-10-2014
28-9-2014

What can i do ?!


text:
Q: Clearing up common terminology for functions I am currently a M.S. of applied mathematics student and a working TA for an axiomatic set theory course. I have helped teach this course in the past, however in my graduate program, the TA usually teaches a lot of the course to gain experience. We are currently covering maps and I had some questions about common terminology and phrases when talking about functions.
To begin I usually start with the following definition:

Let $A$ and $B$ be sets. A map $\phi : A \to B$ is a relation such that for each $a \in A$ there exists a unique $b \in B$ such that $(a,b) \in \phi$.

Then I follow with this remark:

Remark: From the definition of a map if $\phi : A \to B$, the $\phi$ can be viewed as an assignment, to each element $a \in A$, of a unique element $b \in B$.

This sits well, usually, since before we start even talking about sets we cover propositional and predicate logic and the students are familiar with the concept of assigning a truth value to a predicate of some variable(s).

Here is where I start to have questions: in many mathematics textbooks for set theory, sometimes one reads "the map $\phi$ sends/maps/associates $a$ to $b$". While in others, such as the ones I have based my teaching style after, one reads "a map $\phi$ assigns to every $a \in A$ exactly one $b \in B$." Are all these sentences equivalent? Meaning if a student asks if saying "the map $\phi$ sends/maps/associates $a$ to $b$ and "a map $\phi$ assigns to every $a \in A$ exactly one $b \in B$" are interchangeable I can answer with: "yes, they are all just different ways of talking about maps". I understand the definition of a map is unambiguous and the important take away is that $\phi$ is a relation such that $(a,b) \in \phi$ means "$a$ is related to $b$" -  but I wanted to clarify some common vernacular.
Disclaimer: This was originally posted on Mathematics Educators.SE but I felt I would get more precise answers from the community here.

A: I think the confusion comes from not always clearly distinguishing between a function $\phi:A\to B$ and the graph of $\phi$, which is the set $\{(a,\phi (a)): a\in A\}$. Specifically, a function specifies its codomain while its graph does not.
For example, let $g:\mathbb{R}\to \mathbb{R}, g(x)=|x|+1$ and $h:\mathbb{R}\to \mathbb{R}^+, h(x)=|x|+1$. Although $g(x)=h(x)$, the functions $g$ and $h$ are different since they have different codomains.
Saying that "the map sends $a$ to $b$" seems to refer to the map's graph rather than the map itself, although the distinction is not usually important.
One way to define a function is as an ordered triple $(X,f,Y)$ where $f \subseteq X\times Y$ satisfying for all $x\in X$ there exists a unique $y\in Y$ such that $(x,y)\in f$.
See Difference between a function and a graph of a function?


text:
Q: How to make a round button? I'm trying to make a round button, but I don't know how can I do it. I can make button with rounded corners, but how can I can round circle. It's not the same. Please, tell me, is it possible on Android? Thank you.

A: <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
    android:color="#ffffff"
    />
</shape>

Set that on your XML drawable resources, and simple use and image button with an round image, using your drawable as background.

A:
<corners android:bottomRightRadius="180dip"
    android:bottomLeftRadius="180dip"
    android:topRightRadius="180dip"
    android:topLeftRadius="180dip"/>

<solid android:color="#6E6E6E"/> <!-- this one is ths color of the Rounded Button -->

and add this to the button code
    android:layout_width="50dp"
    android:layout_height="50dp"

A: If using Android Studio you can just use:
<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
        <solid android:color="#FFFFFF"/>

    </shape>

this works fine for me, hope this helps someone.

A: Used the shape as oval. This makes the button oval

<item>
    <shape android:shape="oval" >
        <stroke
            android:height="1.0dip"
            android:width="1.0dip"
            android:color="#ffee82ee" />

        <solid android:color="#ffee82ee" />

        <corners
            android:bottomLeftRadius="12.0dip"
            android:bottomRightRadius="12.0dip"
            android:radius="12.0dip"
            android:topLeftRadius="12.0dip"
            android:topRightRadius="12.0dip" />
    </shape>
</item>

A: You can use a MaterialButton:
     <com.google.android.material.button.MaterialButton
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:insetTop="0dp"
            android:insetBottom="0dp"
            android:text="A"
            app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.App.Rounded"
            />

and apply a circular ShapeAppearanceOverlay with:
<style name="ShapeAppearanceOverlay.App.rounded" parent="">
    <item name="cornerSize">50%</item>
</style>

A: *

*Create a drawable/button_states.xml file containing:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="rectangle">
        <corners android:radius="1000dp" />
        <solid android:color="#41ba7a" />
        <stroke
            android:width="2dip"
            android:color="#03ae3c" />
        <padding
            android:bottom="4dp"
            android:left="4dp"
            android:right="4dp"
            android:top="4dp" />
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
        <corners android:radius="1000dp" />
        <solid android:color="#3AA76D" />
        <stroke
            android:width="2dip"
            android:color="#03ae3c" />
        <padding
            android:bottom="4dp"
            android:left="4dp"
            android:right="4dp"
            android:top="4dp" />
        </shape>
    </item>
</selector>

*Use it in button tag in any layout file
<Button
    android:layout_width="220dp"
    android:layout_height="220dp"
    android:background="@drawable/button_states"
    android:text="@string/btn_scan_qr"
    android:id="@+id/btn_scan_qr"
    android:textSize="15dp"
/>

A: Create an xml file named roundedbutton.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
    <solid android:color="#eeffffff" />
    <corners android:bottomRightRadius="8dp"
        android:bottomLeftRadius="8dp"
        android:topRightRadius="8dp"
        android:topLeftRadius="8dp"/>
</shape>

Finally set that as background to your Button as android:background = "@drawable/roundedbutton"
If you want to make it completely rounded, alter the radius and settle for something that is ok for you.

A: Round button in Android
You can make a ImageButton with circular background image.

A: use ImageButton instead of Button....
and make Round image with transparent background

A: Update 2021:
Just use the MaterialButton
<com.google.android.material.button.MaterialButton
    app:cornerRadius="30dp"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:text="test" />

*

*width equal height

*cornerRadius is half of the width or height

A: For a round button create a shape:
<?xml version="1.0" encoding="utf-8"?>

<stroke
    android:width="8dp"
    android:color="#FFFFFF" />

<solid android:color="#ffee82ee" />

<corners
    android:bottomLeftRadius="45dp"
    android:bottomRightRadius="45dp"
    android:topLeftRadius="45dp"
    android:topRightRadius="45dp" />

use it as a background of your button link

A: Markushi's android circlebutton:
(This library is deprecated and no new development is taking place. Consider using a FAB instead.)

A: If you want a FAB looking circular button and you are using the official Material Component library you can easily do it like this:
<com.google.android.material.button.MaterialButton
    style="@style/Widget.MaterialComponents.ExtendedFloatingActionButton"
    app:cornerRadius="28dp"
    android:layout_width="56dp"
    android:layout_height="56dp"
    android:text="1" />

Result:

If you change the size of the button, just be careful to use half of the button size as app:cornerRadius.

A: Yes it's possible, look for 9-patch on google. Good articles :
http://radleymarx.com/blog/simple-guide-to-9-patch/
http://ogrelab.ikratko.com/custom-color-buttons-for-android/

A: You can use google's FloatingActionButton
XMl:
<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@android:drawable/ic_dialog_email" />

Java:
  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FloatingActionButton bold = (FloatingActionButton) findViewById(R.id.fab);
    bold.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        // Do Stuff
        }
    });
}

Gradle:
    compile 'com.android.support:design:23.4.0'

A: I simply use a FloatingActionButton with elevation = 0dp to remove the shadow:
<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_send"
    app:elevation="0dp" />

A: I like this solution
            <androidx.cardview.widget.CardView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:cardCornerRadius="18dp"
                app:cardElevation="0dp"
                >
                <ImageButton
                        android:layout_width="35dp"
                        android:layout_height="35dp"
                        android:background="@null"
                       android:scaleType="centerCrop"
              android:src="@drawable/social_facebook"
                        />
            </androidx.cardview.widget.CardView>

A: It is
android.R.drawable.expander_ic_minimized

look into built in android drawables:
http://androiddrawableexplorer.appspot.com/

A: *

*Use the Image Buttons and make the background as the image you want.

*Create the images from the android asset studio link -

" https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html#foreground.type=image&foreground.space.trim=0&foreground.space.pad=0.25&foreColor=rgba(94%2C%20126%2C%20142%2C%200)&backColor=rgb(96%2C%20125%2C%20139)&crop=1&backgroundShape=circle&effects=none&name=ic_home "
and download it, extraxt it , inside that look for mipmap-hdpi folder.

*copy the image from the mipmap-hdpi folder and paste it in the drwable folder of your android project.

*Now set the background as that image.

A: I went through all the answers. But none of them is beginner friendly. So here I have given a very detailed answers fully explained with pictures.
Open Android Studio. Go to Project Window and scroll to drawable folder under res folder

Right click, select New --> drawable resource folder

In the window that appears, name the file rounded_corners and click on OK

A new file rounded_corners.xml gets created
Open the file. You are presented with the following code -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://android.com/apk/res/android">

</selector>

Replace it with the following code -->
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="8dp" />
    <solid android:color="#66b3ff" />
</shape>

Here the design view can be seen on the right side
Adjust the value in android:radius to make the button more or less rounded.
Then go to activity_main.xml
Put the following code -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:padding="10dp">

    <Button
        android:id="@+id/_1"
        android:text="1"
        android:textSize="25dp"
        android:textColor="#ffffff"
        android:background="@drawable/rounded_corners"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"/>

</RelativeLayout>

Here I have placed the Button inside a RelativeLayout. You can use any Layout you want.
For reference purpose MainActivity.java code is as follows -->
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

I have a Pixel 4 API 30 avd installed.
After running the code in the avd the display is as follows -->

A: Fully rounded circle shape.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#FFFFFF" />
    <stroke
        android:width="1dp"
        android:color="#F0F0F0" />
    <corners
        android:radius="90dp"/>
</shape>

Happy Coding!

A: In case someone needs a floating action button, but doesn't want to depend on the entire material library, here's a minimal implementation that looks exactly the same, has ripple animation, the shadow, and show()/hide() methods with animation.

Widget code:
class CircularImageButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
) : AppCompatImageButton(context, attrs) {
    init {
        background = null
        outlineProvider = pillOutlineProvider
        clipToOutline = true
    }

    fun show() {
        if (visibility != VISIBLE) {
            visibility = VISIBLE
            startAnimation(showAnimation)
        }
    }

    fun hide() {
        if (visibility != INVISIBLE) {
            visibility = INVISIBLE
            startAnimation(hideAnimation)
        }
    }

    override fun setBackgroundColor(color: Int) {
        if (backgroundPaint.color != color) {
            backgroundPaint.color = color
            invalidate()
        }
    }

    private val backgroundPaint = Paint().apply { style = Paint.Style.FILL }

    override fun onDraw(canvas: Canvas?) {
        canvas?.drawPaint(backgroundPaint)
        super.onDraw(canvas)
    }
}

val pillOutlineProvider = object : ViewOutlineProvider() {
    override fun getOutline(view: View, outline: Outline) {
        outline.setRoundRect(0, 0, view.width, view.height, view.height.f / 2)
    }
}

private val animationDuration = applicationContext
        .resources.getInteger(android.R.integer.config_shortAnimTime).toLong()

val showAnimation = ScaleAnimation(
        0f, 1f, 0f, 1f,
        Animation.RELATIVE_TO_SELF, 0.5f,
        Animation.RELATIVE_TO_SELF, 0.5f)
        .apply { duration = animationDuration }

val hideAnimation = ScaleAnimation(
        1f, .5f, 1f, 0.5f,
        Animation.RELATIVE_TO_SELF, 0.5f,
        Animation.RELATIVE_TO_SELF, 0.5f)
        .apply { duration = animationDuration }

And the xml, where 40dp is the "mini" version of the FAB.
<CircularImageButton
    android:id="@+id/fab"
    android:layout_width="40dp"
    android:layout_height="40dp"

    android:src="@drawable/ic_your_drawable"
    android:scaleType="center"

    android:layout_margin="12dp"
    android:elevation="3dp"

    android:outlineAmbientShadowColor="#7000"
    android:outlineSpotShadowColor="#7000"
    android:foreground="?attr/selectableItemBackgroundBorderless" />

A: With jetpack compose, you can customize your button without requiring any 3-party lib or boilerplate code.
  Button(
        onClick = { /* do something when button clicked*/ },
        modifier = Modifier
            .width(64.dp)
            .height(64.dp),
        shape = CircleShape
    ) {
        Icon(Icons.Default.Star, "")
    }


text:
Q: getUserMedia image capture resolution vs. html video element size Is there a way to capture a higher resolution image than the actual width of my onscreen video element which is showing my webcam image that I intend to capture?
Currently, I have set the width in getUserMedia to 1280, but my  element is constrained to 640px. I'd like to still be storing images of 1280px wide so that I'm getting higher quality images.
Code:

Add Photos

        <video id="video" autoplay playsinline></video>
    <select id="videoSource"></select>

TAKE PHOTO

    <canvas  id="myCanvas" style="display:none;"></canvas>

SAVE ORDER


text:
Q: javascript confirm doesnt stop submitting form i am trying to do a confirm function using javascript in php which it worked only in showing the buttons but whatever you press the form will submit heres the code and the function
<form action='Allocated.php' method='post'  >
    <input type='submit' name='disc' value='Discontue Asset'    formnovalidate='formnovalidate' onclick='myFunction()' />
    <input type='hidden' name='alloc' value='$AllocID' />
    </td>
</form>

and the function
function myFunction() {
    var r = confirm("Press a button!");
    if (r == true) {
        return true;
    } else {
        return false;
    }
}

any help would be appreciated
THanks

A: Change onclick='myFunction()' to onsubmit='return myFunction()' so that the returned value from the function can be returned to the event.

A: Put this function at attribute onsubmit (with return keyword, thx Scott) on form and change to button

<form action="Allocated.php" method="post" onsubmit="return myFunction()">
    <input type="hidden" name="alloc" value="$AllocID" />
    <button type="submit">Discontue Asset</button>
</form>

A: use this:
function myFunction() {
    var r = confirm("Press a button!");
    if (r) {
        return true;
    } else {
        return false;
    }
}

or:
for booleans you must use === instead of == :
function myFunction() {
    var r = confirm("Press a button!");
    if (r == true) {
        return true;
    } else {
        return false;
    }
}

or
function myFunction() {
    var r = confirm("Press a button!");
    if (r === 1) {
        return true;
    } else {
        return false;
    }
}

A: You can try code below, It's much simpler
Give an id to your form
<form action='Allocated.php' method='post' id="myform">
<input type='submit' name='disc' value='Discontue Asset'    formnovalidate='formnovalidate' onclick='myFunction()' />
<input type='hidden' name='alloc' value='$AllocID' />
</td>

Then write your javascript like this
function myFunction() {
var r = confirm("Press a button!");
if (r) {
    document.getElementById('myform').submit();
} else {
    return false;
}

}


text:
Q: function that returns the string after "," I need to write a function that returns the second expression from a comma-separated string.
I tried to write with an array
Function ReturnSecString() As Variant
    Dim myarr As Variant

    ReDim myarr(2)

    myarr(0) = "My"
    myarr(1) = "Name"
    myarr(2) = "Is"

    ReturnSecString = myarr
End Function

Sub TestTransposeArray()
    Dim outputArr As Variant
    'Call Return Function

    outputArr = ReturnSecString()
    MsgBox outputArr(2)
End Sub

It does print the second word for me, but I need a function that will print the second word in the entire line after a comma.

A: Return Nth Substring

*

*This will allow you to choose which substring to return and which delimiter to use.

The Code
Option Explicit

Function returnNthString(ByVal InitialString As String, _
                         Optional ByVal NthSubString As Long = 1, _
                         Optional ByVal Delimiter As String = ",") _
         As String
    Dim myArr As Variant
    myArr = Split(InitialString, Delimiter)
    On Error Resume Next
    returnNthString = myArr(NthSubString - 1)
End Function

Sub TESTreturnNthString()
    Const InitialString As String = "Apple, Banana , Orange, Plum"
    Debug.Print returnNthString(InitialString, 2)
    ' Result: Banana
End Sub

A: Option Explicit

Sub test()

   Dim t As String
   t = "String1, I am String2, String3"

   Dim x As String
   x = SecondStringAfterComma(t)

   Debug.Print x

End Sub

Function SecondStringAfterComma(sent As String) As String

    Dim ret As String
    ret = Split(sent, ",")(1)

    SecondStringAfterComma = ret

End Function

Result
 I am String2


text:
Q: Selenium find xpath of select node I am trying to generate the xpath for the following:
    <select data-bind="options: PrinterLabelTypes, optionsValue: 'value', optionsText:
    'value', value: NewPrinterLabelTypeText, optionsCaption: GetText('SelectLabelType')">.
     <option value="">Choose Printer Label Type...</option><option
    value="Batch">Batch</option><option value="Despatch">Despatch</option>
    </select>

I have tried the following:
    //select[@data-bind='value: NewPrinterLabelTypeText']

But i am not getting anything back. Have i missed something. Is there a way to do it using the format above?

A: You have to use contains when your locator is using part of the attribute value.
//select[contains(@data-bind,'value: NewPrinterLabelTypeText')]


text:
Q: How can I require at least one record to exist in a subform? I have a form with a subform on it that queries a many-to-many relationship (but this would apply to a one-to-many relationship as well).  I want to require that the user adds at least one record to this subform.
I believe the issue will be that the main form must update/insert before the subform even gets focus.  This means I can't use BeforeUpdate to check the RecordCount on the subform.
Has anyone found a decent way around this?

A: In such situations, I use to open a dialog form, where the user must enter the basic information required to insert both records. This form has an OK and a Cancel button. Enable the OK button only when the requested fields have been entered. Then insert both records (the master record and the detail record) programmatically. Only then, you open your main master/detail form (the one with the subform) which now will display both records. The user can now add additional data, if he wants.


text:
Q: ¿Alguien me puede explicar bien JSON y como utilizarlo para refrescar la información he probado con ajax pero no lo entiendo? Hola buenas la variable de reservas tiene guardas las horas que están en la base de datos y necesito mostrarlas en el párrafo del id horasDb. El problema es el siguiente tengo un Calendario con Jquery y necesito comparar las horas que tengo guardas en la base de datos y las que hay libres para bloquearlas...
El problema es que no me refresca el parrafo de id horasDb hasta que no se le da por segunda vez a elegir la fecha......
Haber si alguien me puede ayudar a refrescar la informacion  me han comentado que hay que utilizar ajax  para eso pero estoy perdido alguna ayuda porfavor
De ajax he probado eso y no me funciona..
$("#enviar").click(function () {
  $.ajax({
    url: "reservar1.php",
    type: "post",
    data: $($reservas).serialize(),
    success: function(horasDb) {
      $("#horasDb").html(horasDb);
    }
  });
});

     <?php
           $fechacliente=$_POST["fechacliente"];
           $consultahora = "SELECT date_format(hora,'%H:%i') as 'hora' from reservas
            where fechareserva=str_to_date('".$fechacliente."','%d/%m/%Y') and idpeluqueros=1;";
           $resultado1 = $conexion->prepare($consultahora);
           $resultado1->execute();
           $horas=$resultado1->fetchAll(PDO::FETCH_ASSOC);

                 $reservas=[];
                 foreach($horas as $hora){

                    array_push($reservas,$hora["hora"]);

                   }
    ?>
        $(function() {

        const dias_semana = {
          0: 0,1: 1,2: 2,3: 3,4: 4,5: 5,6: 6
        }

        $("#fecha").datepicker({
            dateFormat: 'dd/mm/yy',
            onSelect: function(dia_semm) {
              const [day, month, year] = dia_semm.split('/');
              const date = new Date(year, (month - 1), day);
              const num_dia_sem = date.getDay();

              var horasDb = JSON.parse(`<?php echo json_encode($reservas); ?>`);
              document.getElementById("horasDb").innerHTML = horasDb;

              if((dias_semana[num_dia_sem])==1){
                var dia= new Array();
                var barra_horas = '';
                dia=horaslune();
                var long = dia.length;
                // alert(long);
                for(i=0;i<long;i++)
                {
                     barra_horas = barra_horas+dia[i] ;
                }
                document.getElementById("dia").innerHTML = barra_horas;
              }
              if((dias_semana[num_dia_sem])==6){
                var dias= new Array();
                var barra_horas = '';
                dias=horassabad();
                var long = dias.length;
                // alert(long);
                for(i=0;i<long;i++)
                {
                     barra_horas = barra_horas+dias[i] ;
                }
                document.getElementById("dia").innerHTML = barra_horas;

              }
              if((dias_semana[num_dia_sem])==2 || (dias_semana[num_dia_sem])==3 || (dias_semana[num_dia_sem])==4 || (dias_semana[num_dia_sem])==5 ){
                var diass= new Array();
                var barra_horas = '';
                diass=horas();
                var long = diass.length;
                // alert(long);
                for(i=0;i<long;i++)
                {
                     barra_horas = barra_horas+diass[i] ;
                }
                document.getElementById("dia").innerHTML = barra_horas;
              }

            },
            changeMonth: true,
            changeYear: true,
                   minDate: today,
                   maxDate: end_day,
            //  beforeShowDay: my_check,
                   beforeShowDay: my_check

          });
        });

            <form id="formulario" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
                    <fieldset >

                        Fecha:

<input type="text" value="" id="fecha" name="fechacliente" size="20"/

                  <input type="burron" id="enviar"  value="Comprobar horas disponibles" />

            </form>


text:
Q: How to split a string with two continuous spaces I have a string that consists of continuous spaces like
a(double space)b c d (Double space) e f g h (double space) i

split like
a
b c d
e f g h
i

at present i am trying like this
   Regex r = new Regex(" +");
        string[] splitString = r.Split(strt);

A: string s = "a  b c d  e f g h  i";
var test = s.Split(new String[] { "  " }, StringSplitOptions.RemoveEmptyEntries);

Console.WriteLine(test[0]); // a
Console.WriteLine(test[1]); // b c d
Console.WriteLine(test[2]); // e f g h
Console.WriteLine(test[3]); // i

Example
Another way would be to use Regular Expressions, which would allow you to split on any whitespace over two characters:
string s = "a      b c d   e f g h      \t\t i";
var test = Regex.Split(s, @"\s{2,}");

Console.WriteLine(test[0]); // a
Console.WriteLine(test[1]); // b c d
Console.WriteLine(test[2]); // e f g h
Console.WriteLine(test[3]); // i

Example

A: You can use String.Split method.

Returns a string array that contains the substrings in this string
  that are delimited by elements of a specified string array. A
  parameter specifies whether to return empty array elements.

string s = "a  b c d  e f g h  i";
var array = s.Split(new string[] {"  "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var element in array)
{
    Console.WriteLine (element);
}

Output will be;
a
b c d
e f g h
i

Here a DEMO.

A: You can use String.Split:
var items = theString.Split(new[] {"  "}, StringSplitOptions.None);

A: Use regular expression is an elegant solution
string[] match = Regex.Split("a  b c d  e f g h  i", @"/\s{2,}/",  RegexOptions.IgnoreCase);


text:
Q: Python 3.x - Tkinter treeview change from one style to another Below I define two different treeveiw styles. Initially I assign one of them to the a treeview. Is it possible, later on, to shift to the other style?
from tkinter import *
from tkinter import ttk

if __name__ == '__main__':
    root = Tk()
    style = ttk.Style()

    #Defining style 1
    style.configure('myStyle1.Treeview', rowheight=75)
    #Defining style 2
    style.configure('myStyle2.Treeview', rowheight=25)

    tree = ttk.Treeview(root, style='myStyle1.Treeview')
    tree.pack()

    for i in range(5):
        tree.insert(parent='',
               index=END,
               text='item {}'.format(i))

    root.mainloop()

A: Like with any other widget, you can change almost any configuration option at any time. The style is no different in this regard.
tree.configure(style='myStyle2.Treeview')


text:
Q: Can a PL/pgSQL function contain a dynamic subquery? I am writing a PL/pgSQL function. The function has input parameters which specify (indirectly), which tables to read filtering information from.
The function embeds business logic which allows it to select data from different tables based on the input arguments. The function dynamically builds a subquery which returns filtering data which is then used to run the main query.
My questions are:

*

*Is it 'legal' to use a dynamic subquery in a PL/pgSQL function. I cant see why not - but this question is related to the next one.

*AFAIK, PL/pgSQL are cached or precompiled by the query engine. How does having a function that generates dynamic subqueries impact the work of the query engine?

A: "38.5.4. Executing Dynamic Commands"


text:
Q: Multiply rows in single query Table1 has the following 2 columns and 4 rows:
Entity Number
------ ------
Car    4
Shop   1
Apple  3
Pear   1

I'd like to have one set based SQL query, which produces the below desired results. Basically duplicating the Entities by the Number of times in the Number column.
I could only do it by loop through the rows one by one, which is not really elegant, neither set based.
Desired result:
Entity
------
Car
Car
Car
Car
Shop
Apple
Apple
Apple
Pear

A: One method uses recursive CTEs:
with cte as (
      select t1.entity, t1.number
      from table1 t1
      union all
      select cte.entity, cte.number - 1
      from cte
      where cte.number > 0
     )
select entity
from cte;

Note:  Using the default settings, this is limited to 100 rows per entity.  You can use OPTION (MAXRECURSION 0) to get around this.
You can also solve this with a numbers table, but such a problem is a good introduction to recursive CTEs.

A: Use this
;WITH CTE
AS
(
    SELECT
        SeqNo = 1,
        Entity,
        Number
        FROM YourTable

    UNION ALL

    SELECT
        SeqNo = SeqNo+1,
        Entity,
        Number
        FROM CTE
            WHERE SeqNo < Number
)
SELECT
    Entity
    FROM CTE
        ORDER BY 1

A: A non-recursion solution, will be using a fixed sequence number, then join the table based on this number like this:
WITH numbers
AS
(
  SELECT n
  FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9), (10)) AS numbers(n)
)
SELECT t.Entity
FROM Table1 AS t
INNER JOIN numbers as n ON t.number >= n.n;

This will support up to 10 times duplication, you can add extra numbers to support extra duplication times.
Demo

A: You can use spt_values as source for numbers table
select EntityList.*
from EntityList
, (
select number as n from master..spt_values WHERE Type = 'P' and Number between 1 and (select max(number) from EntityList)
) t
where n <= number
order by entity


text:
Q: Finding divisions I'm quite new to programming and I've heard this is a good place to get started. I'm working with python through the Project Euler Questions and I'm stuck on question 7. I have a way of completing it but it is extremely inefficient and the main question I'm asking is if there is a way to check for all factors of an integer in a way that doesn't mean typing them all in.
So far this is what I have:
counter=0

prime_counter=0

for x in range(1,10000):

    if x%2 and x%3 and x%4 and x%5 and x%6 and x%7 and x%8 and x%9 and x%10 and x%11 and x%12 and x%13 and x%14 and x%15 and x%16 and x%17 and x%18 and x%19 and x%20 and x%21 and x%22 and x%23 and x%24 and x%25 and x%26 and x%27 and x%28 and x%29 and x%30 and x%31 and x%32 and x%33 and x%34 and x%35 and x%36 and x%37 and x%38 and x%39 and x%40 and x%41 and x%42 and x%43 and x%44 and x%45 and x%46 and x%47 and x%48 and x%49 and x%50 !=0:
        counter+=1
        prime_counter+=x

    if counter==10001:
        break
print(counter)

print(prime_counter)

You can see my issue here and feel free to laugh but I'm quite new and I was wondering if I could get some help.
I completely forgot, the whole purpose of the code is to figure out the 10,001st prime number

A: It looks like you want to mark a number as non-prime if it has a modulus of 0 with a factor. So instead of hardcoding all the factors, you could use some function to generate all these numbers... like range.
The other question is "what should the range of factors for testing be, given a number?". It turns out that you need to only test for the numbers in [2, sqrt(n)]. Also, note that we only need to check if any prime number is a factor
Putting these two pieces together:
primes = [2]  # list of all the prime numbers
n = 3
while len(primes) < 10001:  # until we find the required number of prime numbers
    F = n**0.5
    prime = True
    for f in (p for p in primes if p<=F):
        if not n%f:  # found a factor
            prime = False
            break
    if prime:
        primes.append(n)
    n += 2  # test only the odd numbers

print(primes)


text:
Q: Error 26 on SQL Server Express on local (non-networked) machine An SQL server exception error 26 has occurred in a program that uses a local instance of SQL Server Express, on a machine that is stand-alone and not a part of any network. Anonymized screenshot is below. It's a legacy program that's been around for a long time and this is the first time (to my knowledge) that this exception has occurred.
Everything I've seen online about this error points to an attempt to access a remote machine, which of course is not the case here.
The connection string is Data Source=(local)\\SQLEXPRESS;Integrated Security=True;MultipleActiveResultSets=True;Initial Catalog=AppDb5_0; This is set when the program starts and is never changed. To get to the point in the program where the exception occurred, the database would have been accessed many times, so it can't be a problem with the connection string.
EDIT: I do see this related question: SQL Server: cannot connect from local website (SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified). However, in that case it's related to the connection string, a problem that would have shown up almost immediately in my program.
What might have happened to cause this exception?

EDIT. Here's a zip of all the log files: https://www.dropbox.com/s/jyi8atc92e81hpv/SqlServerErrorLogs.zip?dl=0
EDIT
Here's one of the log files from the affected computer.

2018-08-22 12:01:18.22 Server      Microsoft SQL Server 2016 (SP1-GDR)
  (KB4293801) - 13.0.4223.10 (X64)
Jul 26 2018 18:39:45
Copyright (c) Microsoft Corporation
Express Edition (64-bit) on Windows 10 Pro 6.3  (Build 17134: )
2018-08-22 12:01:18.22 Server      UTC adjustment: 10:00
2018-08-22 12:01:18.22 Server      (c) Microsoft Corporation.
2018-08-22 12:01:18.22 Server      All rights reserved.
2018-08-22 12:01:18.22 Server      Server process ID is 3888.
2018-08-22 12:01:18.22 Server      System Manufacturer: 'MSI', System
  Model: 'MS-7851'.
2018-08-22 12:01:18.22 Server      Authentication mode is
  WINDOWS-ONLY.
2018-08-22 12:01:18.22 Server      Logging SQL Server messages in file
  'C:\Program Files\Microsoft SQL
  Server\MSSQL13.SQLEXPRESS\MSSQL\Log\ERRORLOG'.
2018-08-22 12:01:18.22 Server      The service account is 'NT
  Service\MSSQL$SQLEXPRESS'. This is an informational message; no user
  action is required.
2018-08-22 12:01:18.22 Server      Registry startup parameters:
-d C:\Program Files\Microsoft SQL
  Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\master.mdf
-e C:\Program Files\Microsoft SQL
  Server\MSSQL13.SQLEXPRESS\MSSQL\Log\ERRORLOG
-l C:\Program Files\Microsoft SQL
  Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\mastlog.ldf
2018-08-22 12:01:18.22 Server      Command Line Startup Parameters:
-s "SQLEXPRESS"
2018-08-22 12:01:21.30 Server      SQL Server detected 1 sockets with
  2 cores per socket and 2 logical processors per socket, 2 total
  logical processors; using 2 logical processors based on SQL Server
  licensing. This is an informational message; no user action is
  required.
2018-08-22 12:01:21.30 Server      SQL Server is starting at normal
  priority base (=7). This is an informational message only. No user
  action is required.
2018-08-22 12:01:21.30 Server      Detected 3972 MB of RAM. This is an
  informational message; no user action is required.
2018-08-22 12:01:21.30 Server      Using conventional memory in the
  memory manager.
2018-08-22 12:01:21.93 Server      Default collation:
  SQL_Latin1_General_CP1_CI_AS (us_english 1033)
2018-08-22 12:01:23.00 Server      Buffer pool extension is already
  disabled. No action is necessary.
2018-08-22 12:01:24.58 Server      InitializeExternalUserGroupSid
  failed. Implied authentication will be disabled.
2018-08-22 12:01:24.58 Server      Implied authentication manager
  initialization failed. Implied authentication will be disabled.
2018-08-22 12:01:25.37 Server      The maximum number of dedicated
  administrator connections for this instance is '1'
2018-08-22 12:01:25.38 Server      This instance of SQL Server last
  reported using a process ID of 3900 at 8/22/2018 11:59:45 AM (local)
  8/22/2018 1:59:45 AM (UTC). This is an informational message only; no
  user action is required.
2018-08-22 12:01:25.41 Server      Node configuration: node 0: CPU
  mask: 0x0000000000000003:0 Active CPU mask: 0x0000000000000003:0. This
  message provides a description of the NUMA configuration for this
  computer. This is an informational message only. No user action is
  required.
2018-08-22 12:01:25.44 Server      Using dynamic lock allocation.
  Initial allocation of 2500 Lock blocks and 5000 Lock Owner blocks per
  node.  This is an informational message only.  No user action is
  required.
2018-08-22 12:01:25.47 Server      Database Instant File
  Initialization: disabled. For security and performance considerations
  see the topic 'Database Instant File Initialization' in SQL Server
  Books Online. This is an informational message only. No user action is
  required.
2018-08-22 12:01:25.58 Server      CLR version v4.0.30319 loaded.
2018-08-22 12:01:26.02 Server      Query Store settings initialized
  with enabled = 1,
2018-08-22 12:01:27.03 spid4s      Starting up database 'master'.
2018-08-22 12:01:27.07 Server      Common language runtime (CLR)
  functionality initialized using CLR version v4.0.30319 from
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319.
2018-08-22 12:01:27.68 spid4s      SQL Server Audit is starting the
  audits. This is an informational message. No user action is required.
2018-08-22 12:01:27.69 spid4s      SQL Server Audit has started the
  audits. This is an informational message. No user action is required.
2018-08-22 12:01:27.83 spid4s      SQL Trace ID 1 was started by login
  "sa".
2018-08-22 12:01:27.84 spid4s      Server name is 'Lab-PC\SQLEXPRESS'.
  This is an informational message only. No user action is required.
2018-08-22 12:01:27.94 spid4s      Starting up database 'msdb'.
2018-08-22 12:01:27.94 spid7s      Starting up database
  'mssqlsystemresource'.
2018-08-22 12:01:28.02 spid7s      The resource database build version
  is 13.00.4223. This is an informational message only. No user action
  is required.
2018-08-22 12:01:28.05 spid10s     A self-generated certificate was
  successfully loaded for encryption.
2018-08-22 12:01:28.05 spid10s     Server local connection provider is
  ready to accept connection on [ \.\pipe\SQLLocal\SQLEXPRESS ].
2018-08-22 12:01:28.06 spid10s     Server local connection provider is
  ready to accept connection on [ \.\pipe\MSSQL$SQLEXPRESS\sql\query ].
2018-08-22 12:01:28.06 spid10s     Dedicated administrator connection
  support was not started because it is disabled on this edition of SQL
  Server. If you want to use a dedicated administrator connection,
  restart SQL Server using the trace flag 7806. This is an informational
  message only. No user action is required.
2018-08-22 12:01:28.07 spid10s     SQL Server is now ready for client
  connections. This is an informational message; no user action is
  required.
2018-08-22 12:01:28.07 Server      SQL Server is attempting to
  register a Service Principal Name (SPN) for the SQL Server service.
  Kerberos authentication will not be possible until a SPN is registered
  for the SQL Server service. This is an informational message. No user
  action is required.
2018-08-22 12:01:28.08 Server      The SQL Server Network Interface
  library could not register the Service Principal Name (SPN) [
  MSSQLSvc/Lab-PC:SQLEXPRESS ] for the SQL Server service. Windows
  return code: 0xffffffff, state: 63. Failure to register a SPN might
  cause integrated authentication to use NTLM instead of Kerberos. This
  is an informational message. Further action is only required if
  Kerberos authentication is required by authentication policies and if
  the SPN has not been manually registered.
2018-08-22 12:01:28.17 spid7s      Starting up database 'model'.
2018-08-22 12:01:28.36 spid7s      Polybase feature disabled.
2018-08-22 12:01:28.37 spid7s      Clearing tempdb database.
2018-08-22 12:01:28.66 spid7s      Starting up database 'tempdb'.
2018-08-22 12:01:28.98 spid13s     The Service Broker endpoint is in
  disabled or stopped state.
2018-08-22 12:01:28.98 spid13s     The Database Mirroring endpoint is
  in disabled or stopped state.
2018-08-22 12:01:29.06 spid13s     Service Broker manager has started.
2018-08-22 12:01:29.11 spid4s      Recovery is complete. This is an
  informational message only. No user action is required.
2018-08-22 12:01:32.06 Server      Software Usage Metrics is disabled.
2018-08-22 12:36:42.09 spid51      Starting up database 'AppDb5_0'.
2018-08-22 14:38:05.09 Server      SQL Server is terminating because
  of a system shutdown. This is an informational message only. No user
  action is required.
2018-08-22 14:38:06.48 spid13s     Service Broker manager has shut
  down.
2018-08-22 14:38:06.48 spid13s     Error: 17054, Severity: 16, State:
  1.
2018-08-22 14:38:06.48 spid13s     The current event was not reported
  to the Windows Events log. Operating system error = (null). You may
  need to clear the Windows Events log if it is full.
2018-08-22 14:38:06.50 spid4s      .NET Framework runtime has been
  stopped.
2018-08-22 14:38:06.57 spid4s      SQL Server shutdown has been
  initiated
2018-08-22 14:38:06.57 spid4s      SQL Trace was stopped due to server
  shutdown. Trace ID = '1'. This is an informational message only; no
  user action is required.

A:
What might have happened to cause [an intermittent connection faillure to a local instance]?

An intermittent connection failure to a local instance like this strongly suggests that the instance wasn't running when you tried to connect.  So check the SQL Logs.  They'll be in a folder like:
C:\Program Files\Microsoft SQL Server\MSSQLxx.SQLEXPRESS\MSSQL\Log

And will show all startup and shutdown events, in addition to failed logins.


text:
Q: PC BIOS doesn't boot after failed reset to defaults Good day.
I have bought brand new PC details and did a setup.
Firstly everything went fine, but I had some issues with installing W11, so I went to bios options, changed few things there, after reboot there was only my motherboard logo showing up, I thought something's going wrong and forced a reboot again (now I guess that I have interrupted the bios reset to factory settings).
After this my PC launches, but there is no signal, no working USB etc.

*

*I tried to clear CMOS by touching 2 pins with the screwdriver while the PSU off,

*tried holding the turn on button for 10-15 seconds both alone and with the reset button,

*tried taking the battery out for 15 minutes

*tried replacing the RAM to other slots

What I still haven't tried is shorting the 1st and 8th pin of M_BIOS chip.
After the night I turned the PC on and saw the connected keyboard working (but no signal, because there was no graphics card connected at this moment). So I turned the PC off, inserted the graphics card and tried again, but came back to my problem. After that the same without the graphics card and after checking all pins connected.
It seems that after long period of time the bios has boot one from the backup and continued to boot from main after that one time.
What could possibly help? Have I bricked my motherboard?
Configuration:
Motherboard: Gigabyte AM4 Aorus B450M
CPU: Ryzen 3600
RAM: Patriot Viper Steel 2x8GB PC25600 3200MHz
SSD: M.2 Kingston NV1 250GB
Graphics card: Radeon RX580
PSU: Proton BDF-500S 500W


text:
Q: How to list unused AWS S3 buckets and empty bucket using shell script? I am looking for list of unused s3 buckets from last 90 days and also for empty bucket list.
In order to get it, I have tried writing code as below:
#/bin/sh
for bucketlist in  $(aws s3api list-buckets --query "Buckets[].Name");
do
  listobjects=$(\
    aws s3api list-objects --bucket $bucketlist \
    --query 'Contents[?contains(LastModified, `2020-08-06`)]')
done

This code prints following output: [I have added results for only one bucket for reference]
{
    "Contents": [
        {
            "Key": "test2/image.png",
            "LastModified": "2020-08-06T17:19:10.000Z",
            "ETag": "\"xxxxxx\"",
            "Size": 179008,,
            "StorageClass": "STANDARD",
        }
    ]
}

Expectations:

*

*In above code I want to print only bucket list which objects are not modified/used in last 90 days.

*I am also looking for empty bucket list

I am not good in programming, Can anyone guide me on this?
Thank you in advance for your support.

A: I made this small bash script to find empty buckets in my account:
#!/bin/zsh
for b in $(aws s3 ls | cut -d" " -f3)
do
  echo -n $b
  if [[ "$(aws s3api list-objects-v2 --bucket $b --max-items 1)" == "" ]]
  then
    echo " BUCKET EMPTY"
  else
    echo ""
  fi
done

I listed the objects using the list-objects-v2 with maximum items of 1. If there are no items - the result is empty and I print "BUCKET EMPTY" alongside the bucket name.

*

*Note 1: You must have access to list the objects.

*Note 2: I'm not sure how it'll work for versioned buckets with deleted objects (appears to be empty, but actually contains older versions of deleted objects)

A: Here's a script I wrote today.  It doesn't change anything, but it does give you the commandlines to make the changes.
#!/bin/bash
profile="default"
olddate="2020-01-01"
smallbucketsize=10

emptybucketlist=()
oldbucketlist=()
smallbucketlist=()

#for bucketlist in  $(aws s3api list-buckets  --profile $profile  | jq --raw-output '.Buckets[6,7,8,9].Name'); # test this script on just a few buckets
for bucketlist in  $(aws s3api list-buckets  --profile $profile  | jq --raw-output '.Buckets[].Name');
do
  echo "* $bucketlist"
  if [[ ! "$bucketlist" == *"shmr-logs" ]]; then
    listobjects=$(\
      aws s3api list-objects --bucket $bucketlist \
      --query 'Contents[*].Key' \
      --profile $profile)
#echo "==$listobjects=="
    if [[ "$listobjects" == "null" ]]; then
          echo "$bucketlist is empty"
          emptybucketlist+=("$bucketlist")
    else
      # get size
      aws s3 ls --summarize  --human-readable --recursive --profile $profile s3://$bucketlist | tail -n1

      # get number of files
      filecount=$(echo $listobjects | jq length )
      echo "contains $filecount files"
      if [[ $filecount -lt $smallbucketsize ]]; then
          smallbucketlist+=("$bucketlist")
      fi

      # get number of files older than $olddate
      listoldobjects=$(\
        aws s3api list-objects --bucket $bucketlist \
        --query "Contents[?LastModified<=\`$olddate\`]" \
        --profile $profile)
      oldfilecount=$(echo $listoldobjects | jq length )
      echo "contains $oldfilecount old files"

      # check if all files are old
      if [[ $filecount -eq $oldfilecount ]]; then
        echo "all the files are old"
        oldbucketlist+=("$bucketlist")

      fi
    fi
  fi
done
echo -e "\n\n"

echo "check the contents of these buckets which only contain old files"
for oldbuckets in ${oldbucketlist[@]};
do
  echo "$oldbuckets"
done
echo -e "\n\n"

echo "check the contents of these buckets which don't have many files"
for smallbuckets in ${smallbucketlist[@]};
do
  echo "aws s3api list-objects --bucket $smallbuckets --query 'Contents[*].Key' --profile $profile"
done
echo -e "\n\n"

echo "consider deleting these empty buckets"
for emptybuckets in "${emptybucketlist[@]}";
do
  echo "aws s3api delete-bucket --profile $profile --bucket $emptybuckets"
done


text:
Q: Adding colored faces to plotly network plot I want to plot some topological complexes using plotly and python. The challenge is that the complexes have colored triangular panels or faces in certain sections of the network. I included a picture below to demonstrate.
Is there a way to plot these colored faces using plotly? I can get the network diagram working, but was not sure how to color the faces.

A: Assuming you were using a scatter plot to plot your nodes and edges, you could add the triangles as shapes via layout.
Just add a path the shapes key in layout
layout = plotly.graph_objs.Layout(
    shapes=[{'type': 'graph',
             'path': 'M 0 0 L 1 2 L 3 4 Z'
           }]
)

to draw a triangle from the x/y-coordinates 0; 0 to 1; 2 to 3; 4.
The code below was modified from here, it creates a random graph and draws a triangle for all nodes which have exactly 2 edges.

import plotly
import networkx as nx

def scatter_nodes(pos, labels=None, color=None, size=20, opacity=1):
    L = len(pos)
    trace = plotly.graph_objs.Scatter(x=list(), y=list(), mode='markers', marker=plotly.graph_objs.Marker(size=list()))
    for k in range(L):
        trace['x'].append(pos[k][0])
        trace['y'].append(pos[k][1])
    attrib = dict(name='', text=labels , hoverinfo='text', opacity=opacity)
    trace = dict(trace, **attrib)
    trace['marker']['size']=size
    return trace

def scatter_edges(G, pos, line_color=None, line_width=1):
    trace = plotly.graph_objs.Scatter(x=list(), y=list(), mode='lines')
    for edge in G.edges():
        trace['x'] += [pos[edge[0]][0],pos[edge[1]][0], None]
        trace['y'] += [pos[edge[0]][1],pos[edge[1]][1], None]
        trace['hoverinfo'] = 'none'
        trace['line']['width'] = line_width
        if line_color:
            trace['line']['color'] = line_color
    return trace

G = nx.Graph()
n = 13
Nodes = range(n)
G.add_nodes_from(Nodes)
Edges=[(0,7), (0,2), (1,3), (1,4), (1,7), (2,5), (2,8), (3, 4), (3,5), (4,6), (4,8), (5,7), (7,8), (9, 10), (9, 11), (6,10), (10, 11)]
G.add_edges_from(Edges)

axis = dict(showline=False,
          zeroline=False,
          showgrid=False,
          showticklabels=False,
          title=''
          )
layout = plotly.graph_objs.Layout(
    showlegend=False,
    xaxis=plotly.graph_objs.XAxis(axis),
    yaxis=plotly.graph_objs.YAxis(axis),
    )

pos = nx.fruchterman_reingold_layout(G)

labels = [str(k) for k in range(len(pos))]
trace1 = scatter_edges(G, pos)
trace2 = scatter_nodes(pos, labels=labels)

data = plotly.graph_objs.Data([trace1, trace2])

#let's get the triangles
triangles = list()
for i in range(n):
    if len(G.neighbors(i)) == 2:
        neighbors = G.neighbors(i)
        triangles.append(dict(type='path',
                              path='M {0} {1} L {2} {3} L {4} {5} Z'.format(
                                  pos[i][0],
                                  pos[i][1],
                                  pos[neighbors[0]][0],
                                  pos[neighbors[0]][1],
                                  pos[neighbors[1]][0],
                                  pos[neighbors[1]][1]),
                              fillcolor='rgba(44, 160, 101, 0.5)',
                              line=dict(color='rgb(44, 160, 101)')
                        ))
layout.update(shapes=triangles)
fig = plotly.graph_objs.Figure(data=data, layout=layout)
plotly.offline.plot(fig)


text:
Q: File changed event being called twice I use a combination of IVsFileChangeEvents and IVsFileChangeEx to monitor, whether file edited in my custom editor extension was modified outside the IDE. However, for some unknown reason, I get the notification twice - thus resulting in asking user for reload twice.
The implementation of FilesChanged looks like the following:
    public int FilesChanged(uint cChanges, string[] rgpszFile, uint[] rggrfChange) {

        foreach (var file in rgpszFile)
        {
            if (file.ToLowerInvariant() == documentPath.ToLowerInvariant()) {

                System.Diagnostics.Debug.WriteLine("File changed - asking for reload");

                if (MessageBox.Show("The file {0} was changed outside the editor. Do you want to reload it?".FillWith(file),
                    "MyEditor",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question) == MessageBoxResult.Yes) {

                    fileChangeEx.IgnoreFile(fileCookie, null, 1);

                    // Unloading document
                    DoCloseDocument();

                    // Loading document
                    DoLoadDocument(file);

                    fileChangeEx.SyncFile(documentPath);
                    fileChangeEx.IgnoreFile(fileCookie, null, 0);
                }
            }
        }
        return VSConstants.S_OK;
    }

I test this code by saving the same file in Notepad++.
This is a log from SysInternals' ProcMon:
09:05:21,2272369    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 08:50:27, ChangeTime: 2014-05-23 08:50:27, AllocationSize: 4 096, EndOfFile: 1 740, FileAttributes: A
09:05:21,2273658    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 08:50:27, ChangeTime: 2014-05-23 08:50:27, AllocationSize: 4 096, EndOfFile: 1 740, FileAttributes: A
09:05:21,2275512    notepad++.exe   256 QueryDirectory  D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Filter: settings.definition, 1: settings.definition
09:05:28,7692878    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 08:50:27, ChangeTime: 2014-05-23 08:50:27, AllocationSize: 4 096, EndOfFile: 1 740, FileAttributes: A
09:05:28,7694244    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 08:50:27, ChangeTime: 2014-05-23 08:50:27, AllocationSize: 4 096, EndOfFile: 1 740, FileAttributes: A
09:05:28,7696066    notepad++.exe   256 QueryDirectory  D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Filter: settings.definition, 1: settings.definition
09:05:44,0463636    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 08:50:27, ChangeTime: 2014-05-23 08:50:27, AllocationSize: 4 096, EndOfFile: 1 740, FileAttributes: A
09:05:46,4087520    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 08:50:27, ChangeTime: 2014-05-23 08:50:27, AllocationSize: 4 096, EndOfFile: 1 740, FileAttributes: A
09:05:46,4088700    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 08:50:27, ChangeTime: 2014-05-23 08:50:27, AllocationSize: 4 096, EndOfFile: 1 740, FileAttributes: A
09:05:46,4089646    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 08:50:27, ChangeTime: 2014-05-23 08:50:27, AllocationSize: 4 096, EndOfFile: 1 740, FileAttributes: A
09:05:46,4090631    notepad++.exe   256 CreateFile  D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Desired Access: Generic Write, Read Attributes, Dis, Options: Synchronous IO Non-Alert, Non-Directory File, Attributes: N, ShareMode: Read, Write, AllocationSize: 0, OpenResult: Overwritten
09:05:46,4100654    notepad++.exe   256 WriteFile   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Offset: 0, Length: 1 742, Priority: Normal
09:05:46,4101850    notepad++.exe   256 CloseFile   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS
09:05:46,4102751    devenv.exe  6884    QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:05:46,4103088    MsMpEng.exe 956 CreateFileMapping   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   FILE LOCKED WITH WRITERS    SyncType: SyncTypeCreateSection, PageProtection:
09:05:46,4103322    MsMpEng.exe 956 QueryStandardInformationFile    D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS AllocationSize: 4 096, EndOfFile: 1 742, NumberOfLinks: 1, DeletePending: False, Directory: False
09:05:46,4144664    notepad++.exe   256 QueryDirectory  D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Filter: settings.definition, 1: settings.definition
09:05:46,4160238    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:05:46,4172362    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:05:46,4173472    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:05:46,4175063    notepad++.exe   256 QueryDirectory  D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Filter: settings.definition, 1: settings.definition
09:05:46,4178437    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:05:46,4185672    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:05:46,4186404    devenv.exe  6884    QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:06:06,8788282    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:06:06,8789555    notepad++.exe   256 QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:06:06,8791373    notepad++.exe   256 QueryDirectory  D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Filter: settings.definition, 1: settings.definition
09:06:50,6465883    devenv.exe  6884    CreateFile  D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Desired Access: Generic Read, Dis, Options: Synchronous IO Non-Alert, Non-Directory File, Open No Recall, Attributes: n/a, ShareMode: Read, AllocationSize: n/a, OpenResult: Opened
09:06:50,6466482    devenv.exe  6884    QueryStandardInformationFile    D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS AllocationSize: 4 096, EndOfFile: 1 742, NumberOfLinks: 1, DeletePending: False, Directory: False
09:06:50,6466665    devenv.exe  6884    ReadFile    D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Offset: 0, Length: 1 742, Priority: Normal
09:06:50,6467374    devenv.exe  6884    ReadFile    D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   END OF FILE Offset: 1 742, Length: 4 096
09:06:50,6469314    devenv.exe  6884    CloseFile   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS
09:06:50,6477175    devenv.exe  6884    QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:06:50,6963339    devenv.exe  6884    QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:07:02,3340501    devenv.exe  6884    CreateFile  D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Desired Access: Generic Read, Dis, Options: Synchronous IO Non-Alert, Non-Directory File, Open No Recall, Attributes: n/a, ShareMode: Read, AllocationSize: n/a, OpenResult: Opened
09:07:02,3341050    devenv.exe  6884    QueryStandardInformationFile    D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS AllocationSize: 4 096, EndOfFile: 1 742, NumberOfLinks: 1, DeletePending: False, Directory: False
09:07:02,3341200    devenv.exe  6884    ReadFile    D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS Offset: 0, Length: 1 742, Priority: Normal
09:07:02,3341887    devenv.exe  6884    ReadFile    D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   END OF FILE Offset: 1 742, Length: 4 096
09:07:02,3343792    devenv.exe  6884    CloseFile   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS
09:07:02,3351733    devenv.exe  6884    QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A
09:07:02,3626280    devenv.exe  6884    QueryOpen   D:\VS Projects\Temporary\WindowsFormsApplication1\WindowsFormsApplication1\NewFolder1\settings.definition   SUCCESS CreationTime: 2014-05-21 13:08:34, LastAccessTime: 2014-05-21 13:08:34, LastWriteTime: 2014-05-23 09:05:46, ChangeTime: 2014-05-23 09:05:46, AllocationSize: 4 096, EndOfFile: 1 742, FileAttributes: A

It seems like the MessageBox.Show call is the main reason for the second notification.
The call stack looks like the following:
MyAssembly.dll!MyClass.FilesChanged(uint cChanges = 1, string[] rgpszFile = {string[1]}, uint[] rggrfChange = {uint[1]}) Line 284   C#
Microsoft.VisualStudio.Shell.UI.Internal.dll!Microsoft.VisualStudio.Services.FileChangeSubscription.Notify.AnonymousMethod__0() Unknown
Microsoft.VisualStudio.Shell.12.0.dll!Microsoft.VisualStudio.ErrorHandler.CallWithCOMConvention(System.Func<int> method, bool reportError = false, bool setShellErrorInfo = true)   Unknown
Microsoft.VisualStudio.Shell.UI.Internal.dll!Microsoft.VisualStudio.Services.FileChangeSubscription.Notify(Microsoft.VisualStudio.Shell.Interop._VSFILECHANGEFLAGS changes) Unknown
Microsoft.VisualStudio.Shell.UI.Internal.dll!Microsoft.VisualStudio.Services.FileChangeSubscription.Notify(System.IO.WatcherChangeTypes changeTypes, Microsoft.VisualStudio.Services.FileProperties props)  Unknown
Microsoft.VisualStudio.Shell.UI.Internal.dll!Microsoft.VisualStudio.Services.FileWatcher.Notify(Microsoft.VisualStudio.Services.ChangeStreamDigest digest)  Unknown
Microsoft.VisualStudio.Shell.UI.Internal.dll!Microsoft.VisualStudio.Services.DirectoryWatcher.ProcessFileChanges(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,Microsoft.VisualStudio.Services.ChangeStreamDigest>> digests, int depth) Unknown
Microsoft.VisualStudio.Shell.UI.Internal.dll!Microsoft.VisualStudio.Services.DirectoryWatcher.ProcessChanges(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,Microsoft.VisualStudio.Services.ChangeStreamDigest>> digests = Count = 1, int depth = 3) Unknown
Microsoft.VisualStudio.Shell.UI.Internal.dll!Microsoft.VisualStudio.Services.DirectoryWatcher.ProcessChanges(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,Microsoft.VisualStudio.Services.ChangeStreamDigest>> digests = Count = 1, int depth = 2) Unknown
Microsoft.VisualStudio.Shell.UI.Internal.dll!Microsoft.VisualStudio.Services.DirectoryWatcher.ProcessChanges(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,Microsoft.VisualStudio.Services.ChangeStreamDigest>> digests = {Microsoft.Internal.VisualStudio.PlatformUI.HybridDictionary<string,Microsoft.VisualStudio.Services.ChangeStreamDigest>}, int depth = 1)  Unknown
Microsoft.VisualStudio.Shell.UI.Internal.dll!Microsoft.VisualStudio.Services.DirectoryWatcher.OnChangedAsync()  Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs)  Unknown
WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object source = {System.Windows.Threading.Dispatcher}, System.Delegate method, object args, int numArgs, System.Delegate catchHandler = null)  Unknown
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeImpl()   Unknown
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(object state)  Unknown
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.Invoke()   Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.ProcessQueue()  Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.WndProcHook(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)  Unknown
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd = 264738, int msg = 49778, System.IntPtr wParam = 0, System.IntPtr lParam = 0, ref bool handled = false)    Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs)  Unknown
WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object source = {System.Windows.Threading.Dispatcher}, System.Delegate method, object args, int numArgs, System.Delegate catchHandler = null)  Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs)   Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd = 264738, int msg = 49778, System.IntPtr wParam = 0, System.IntPtr lParam = 0) Unknown
[Native to Managed Transition]
[Managed to Native Transition]
PresentationFramework.dll!System.Windows.MessageBox.ShowCore(System.IntPtr owner, string messageBoxText, string caption, System.Windows.MessageBoxButton button, System.Windows.MessageBoxImage icon, System.Windows.MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options)  Unknown
PresentationFramework.dll!System.Windows.MessageBox.Show(string messageBoxText, string caption, System.Windows.MessageBoxButton button, System.Windows.MessageBoxImage icon)    Unknown
MyAssembly.dll!MyClass.FilesChanged(uint cChanges = 1, string[] rgpszFile = {string[1]}, uint[] rggrfChange = {uint[1]}) Line 290   C#

What should I do to receive the event only once?

A: I got it to work by detaching the notifications in the method and re-attaching them at the end.
Looks something like this (note that I omitted some details regardingserviceProvider, fileChangeCookie, filesChanged-array, ...)
int IVsFileChangeEvents.FilesChanged(uint numberOfFilesChanged, string[] filesChanged, uint[] flags)
{
    IVsFileChangeEx fileChangeService = yourServiceProvider.GetService(typeof(SVsFileChangeEx));
    // Detach from notifications
    fileChangeService.UnadviseFileChange(GetCookieFromFile(filesChanged[0]));
    // Do your stuff with the file
    ...
    // Re-attach to notifications
    fileChangeService.AdviseFileChange(filesChanged[0], (uint)(_VSFILECHANGEFLAGS.VSFILECHG_Time | _VSFILECHANGEFLAGS.VSFILECHG_Del), this, out fileChangeCookie);
}

A: I've had similar problems with the Win32-level file changed events. There are a lot of things you can to do reduce the problems (like disconnecting the events). In reality, you have no idea how many times a file might get "changed" during the handling of the event. For message-based events, all it takes is a call to anything that processes messages to get reentered, for multithreaded events, you don't even have to call something--it can happen no matter what you do. As a result, you should be very careful about what you do when you receive the notification. Ideally your event handler should be written in a way that it can handle being called again while it's still processing the previous event. Depending on what the dialog and subsequent processing does, you may be able to just keep track of whether or not it is open and/or processing and ignore any concurrent events, or you may need to notify the dialog or processing code that another change has occurred.  Disconnecting and reconnecting the notifications works for message-based events, but not if there is any threading going on.

A: By showing a message box, you're effectively creating a new message loop, allowing for potential reentrancy. This combined with the fact that the FilesChanged event hasn't finished running from a VS point of view (you haven't returned from your function yet) could lead to weird behaviors.
Return immediately in your handler. Queue the MessageBox and document reloading using ThreadHelper.Generic.BeginInvoke.


text:
Q: Extract string from variable passed in parameter My Perl script needs ARG 0 and ARG 1 which are gived by web application ./telnet 10.10.10.10 78-0/1/1
i want to take from ARG1 only 0/1/1 and not 78-0/1/1
and these value are different each time here on other exemple :
./telnet 10.10.10.10 90-0/2/2   so i need only 0/2/2
Some one help please !!!!!

A: You can use substitution to remove everything up to a dash:
my $string = '90-0/2/2';
$string = s/^.+-//;

If you want to be more specific, you can remove only digits:
$string =~ s/^[0-9]+-//;

*

*^ matches the beginning of the string.

*. matches anything (except for newline).

*+ means the previous thing should be repeated at least once.

A: You can use Perl's split subroutine.
my $ARG1 = '90-0/2/2';
my $required_part = (split(/-/,$ARG1))[1];

Now, $required_part contains 0/2/2

A: Instead of removing the part you don't want, you can capture the part that you do want
my ($param) = $ARGV[1] =~ /-(.+)/


text:
Q: Perform functions with the value user selects from a dropdown in Javascript Can I get some help to perform some functions when a user selects an item in dropdown list?
First, below code shows a dropdown with locales one can select from.
Code that shows a dropdown with different locales:

Please select a locale.

<button onclick="myFunction()" class="dropbtn">Locales</button>

    en-US
    ja-JP
    de-DE

And now if a user selects en-US from dropdown, it will need to perform a function that shows different data based on the selected locale like below. If a user selects ja-JP, it will perform the same thing based on 'ja-JP' locale.
Intl.DateTimeFormat('en-US').format(new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
Intl.NumberFormat('en-US').format(1234.56));

Thank you!

A: Probably the most straightforward is:
en-US

A: For starters, I wouldn't prefer this method; if you have the liberty to use jQuery, it's my sincere request that you please do. It'll make your life much easier.
Moving onto what you've given us: if I understand this correctly, you want to trigger an event based on the user's drop down selection? If that's the case, the code's actually pretty simple:
<select id="locale">

  <option>en-US</option>
  <option>jp-JP</option>

</select>

Then some javascript to detect for changes:
$( document ).ready( function() {

  $( "#locale" )
    .change( function() {

      var selectedLocale = $( "#locale option:selected" ).text();

      Intl.DateTimeFormat( selectedLocale ).format(new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
      Intl.NumberFormat( selectedLocale ).format(1234.56));

    } );

} );

That should do the trick.
The fiddle: https://jsfiddle.net/owsrr6dk/1/

A: For dropdown better to use select html element
HTML

Please select a locale.

  <button onclick="myFunction()" class="dropbtn">Locales</button>
  <select id="locale" class="dropdown-content">
    <option value="en-US">en-US</option>
    <option value="ja-JP">ja-JP</option>
    <option value="de-DE">de-DE</option>
  </select>

If you still want  link then attach onlcick event i.e change
en-US

to
en-US

Javascript
Attach event listener to select
function eventFire(val) {
  alert(val);
  //  Intl.DateTimeFormat(val).format(new Date(Date.UTC(2012, 11, 20, 3, 0, 0)));
  //  Intl.NumberFormat(val).format(1234.56));
}

// add this only if you use select else eventFire will be sufficient
var elm = document.getElementById('locale');
elm.addEventListener('change', function(e) {
  eventFire(e.target.value);
})

Demo