text:
Q: "Remember me" test fails when using custom user provider, user entity, etc I have a custom user provider and user entity that I have used successfully in Symfony 2.2. But now I upgraded to 2.3, and I realized the "remember me" functionality is broken. So I created a new sf2 app, and a functional test. The test passed when I used the Acme\DemoBundle defaults. But when I added my provider it started failing again. Here is the test:
<?php

namespace Acme\DemoBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;

class DemoControllerTest extends WebTestCase
{
    public function testRemember()
    {
        $client = static::createClient();

        $securedPageUri = '/user/settings/account';
        $securedPageFilter = 'html:contains("New Password")';
        $loginPageFilter = 'html:contains("Login")';
        $username = 'test@test.com';
        $password = 'test';
        /*
        $securedPageUri = '/demo/secured/hello/World';
        $securedPageFilter = 'html:contains("Hello resource secured for admin only.")';
        $loginPageFilter = 'html:contains("Login")';
        $username = 'admin';
        $password = 'adminpass';
        */

        // Go to Secured page, and be redirected to Login page
        $client->request('GET', $securedPageUri);
        $crawler = $client->followRedirect();
        $this->assertGreaterThan(0, $crawler->filter($loginPageFilter)->count());

        // Try to log in, and be redirected to Secured page
        $form = $crawler->selectButton('Login')->form();
        $form['_username'] = $username;
        $form['_password'] = $password;
        $form['_remember_me'] = 1;
        $client->submit($form);
        $crawler = $client->followRedirect();
        $this->assertGreaterThan(0, $crawler->filter($securedPageFilter)->count());

        // Remove all the cookies, but keep the "remember me" cookie
        $remembermeCookie = $client->getCookieJar()->get('REMEMBERME');
        $client->restart();
        $client->getCookieJar()->set($remembermeCookie);

        // Go to Secured page, this time we should be allowed in
        $client->followRedirects();
        $crawler = $client->request('GET', $securedPageUri);
        //$this->assertTrue($client->getResponse()->isSuccessful());
        $this->assertEquals(0, $crawler->filter($loginPageFilter)->count(), "Redirected to Login page"); // THIS IS WHERE THE TEST FAILS
        $this->assertGreaterThan(0, $crawler->filter($securedPageFilter)->count());
    }
}

The test works fine, I have tried testing it manually too: I log in, delete the session cookie, and try to access the secured page with the remember me cookie. The remember me cookie gets deleted and I'm redirected to the login page :S
Any ideas why this could be happening? My provider does not do anything weird, it just grabs the user from the database as usual. Why on Earth is this affecting the "remember me" functionality? Have there been any changes that I'm not aware of? I'm not using a custom auth provider, just user provider.
Oh and here is the log, with grep security
[2013-07-17 15:18:49] security.DEBUG: Username "test@test.com" was reloaded from user provider. [] []
[2013-07-17 15:18:49] security.DEBUG: Write SecurityContext in the session [] []
[2013-07-17 15:18:49] security.DEBUG: Remember-me cookie detected. [] []
[2013-07-17 15:18:49] security.WARNING: User class for remember-me cookie not supported. [] []
[2013-07-17 15:18:49] security.DEBUG: Clearing remember-me cookie "REMEMBERME" [] []
[2013-07-17 15:18:49] security.INFO: Populated SecurityContext with an anonymous Token [] []
[2013-07-17 15:18:49] security.DEBUG: Access is denied (user is not fully authenticated) by "/srv/www/dev/public/remember/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/AccessListener.php" at line 73; redirecting to authentication entry point [] []
[2013-07-17 15:18:49] security.DEBUG: Calling Authentication entry point [] []
[2013-07-17 15:18:49] security.DEBUG: Write SecurityContext in the session [] []
[2013-07-17 15:18:49] security.INFO: Populated SecurityContext with an anonymous Token [] []
[2013-07-17 15:18:49] security.DEBUG: Write SecurityContext in the session [] []

UPDATE : And only when I pasted the log I noticed that warning. Anyway, do you know how to fix that?
UPDATE 2 : If I use the default user provider, but still my own User class, it works fine. The error message is very misleading.

A: Have a look at Symfony\Component\Security\Http\RememberMe\AbstractRememberMeServices.php#L130 where the security warning comes from.
The Service only provides an abstract method processAutoLoginCookie which you might need to add to your provider in order to process the cookie.


text:
Q: Get Listing Of All Photos (Even pictures stored online) - Picasa image database Uri? Anyone know how to get a listing of all images that show up in the Android Gallery?
This query is only gets pictures taken locally on the phone.  Does anyone know the URI where the Picasa image database is stored??  Appreciate the help.
private void getListOfAllPictures()
{
    final String[] filePathColumn = { MediaStore.Images.Media._ID, MediaColumns.DATA, MediaColumns.DISPLAY_NAME, Images.Media.ORIENTATION, Images.Media.LATITUDE, Images.Media.LONGITUDE };

    Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            filePathColumn, null, null, null);

    Vector<ImageDescriptor> imageDescriptors = new Vector<ImageDescriptor>();
    if(cursor != null)
    {
        cursor.moveToFirst();

        int IMG_ID_INDEX        = cursor.getColumnIndex(MediaStore.Images.Media._ID);
        int DATA_INDEX          = cursor.getColumnIndex(MediaColumns.DATA);
        int LATITUDE_INDEX      = cursor.getColumnIndex(Images.Media.LATITUDE);
        int LONGITUDE_INDEX     = cursor.getColumnIndex(Images.Media.LONGITUDE);
        int ORIENTATION_INDEX   = cursor.getColumnIndex(Images.Media.ORIENTATION);

        while(!cursor.isAfterLast())
        {
            //Blah Blah

            cursor.moveToNext();
        }
    }
    cursor.close();
    Log.v(TAG, "Found " + imageDescriptors.size() + " images.");
}

A: ok its my code and it work for me it give all images which i can see in Android Gallery
just call this function from this line
  getallimages(Environment.getExternalStorageDirectory());

and my function is below
private void getallimages(File dir)
    {

                String[] STAR = { "*" };

        final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
        Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
        int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        int count = imagecursor.getCount();
        for (int i = 0; i < count; i++) {
            imagecursor.moveToPosition(i);
            int id = imagecursor.getInt(image_column_index);
            ImageItem imageItem = new ImageItem();

                imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));

                    imageItem.id = id;
                    imageItem.selection = false; //newly added item will be selected by default
                    controller.images.add(imageItem);

 }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Design of Watchdog Alert System to Detect Missing Periodic Emails I'm looking for ideas on how to automatically receive an alert (by email would be nice) if a specific periodic email were not to arrive. I would not necessarily have access to the system that generates the email.
In a recent real world use case I have a  summary report that is sent daily to a half dozen or so technicians and managers giving system status of dozens of field locations.  We have a second channel that sends alarms, but there are many maintenance issues that can only be discovered by reviewing this report.
Last night I found that the script generating the report had stopped working weeks ago - and no one noticed.  Please, before anyone spends much time berating the people who failed to notice (and this would include me) understand that 90% to 100% of the people involved are very good at what they do, and really do care, but are on the border of information overload. I think it is just human nature not to notice when one of dozens of emails that aren't normally critical just happens not to arrive.  When it arrives that does seems to trigger us to review it with good results, but no arrival - no mental trigger.  We notice and act on emails but fail to notice and act on lack of emails.
My current thought is to send any report emails that I want to monitor to additional "watchdog" email addresses.  I would then have independent machines - maybe a couple of Raspberry Pis or VM in the cloud receive the emails and send an alert if too much time goes by without receiving the email. Sort of a watchdog timer for emails.
Maybe something like this already exists and I just don't have the right search terms and someone can point me to the information, but I'd also be interested in any suggestions on how others might approach it.  For now I'm heading in a specialized script direction, but would be interested in making it more general purpose.

A: Assuming that those tools are available to you, you could cobble something together via procmail and cron. If not, anything that can run shell commands when a specific e-mail arrives should be able to do something very similar.
First, set up a procmail (or whichever other mail filtering tool you use) rule that matches the e-mails you want to monitor, and touch a watchdog file. The c flag causes the rule to process a copy of the e-mail and for processing to continue even if there is a match; that way, the e-mails don't get lost.
:0 c
*^Subject: Regular Report
| /usr/local/bin/regular-report-received.sh

Then write a script to touch a file owned by the user, saving it as /usr/local/bin/regular-report-received.sh in this case:
#!/bin/bash
touch ~/.regular-report-received

(This could be done within the procmail rule, but I like to keep things separate, so there goes.)
Then, you'll need a cron job that regularly checks to make sure the file has been touched recently. For example, you could have, for each user:
 @daily /usr/local/bin/is-regular-report-received.sh

Then there is /usr/local/bin/is-regular-report-received.sh which goes along the lines of
#!/bin/bash
STALE_IF_BEFORE=$(date --date='-36 hours' +%s)
FILE_TIMESTAMP=$(stat -c '%Y' ~/.regular-report-received)
test "${FILE_TIMESTAMP}" -gt "${STALE_IF_BEFORE}" || printf 'Report not received!\n'

With this in place, cron should send each user an e-mail at midnight if they haven't received a report within the past 36 hours.
Adjust to taste.


text:
Q: Using Webpack file-loader to import static json file gives file path instead of json contents I'm trying to use Webpack file-loader to copy a static json resource file to dist/ so I can import that json file in a Vue.js component. Webpack is copying the file correctly when I run npm run build, but when I try to import the file (like import myJson from '@/static/runtimeConfig.json') then "myJSON" variable only gets the file path instead of the actual JSON file contents. Can anyone help me understand why this is?
My webpack file-loader config looks like this:
module: {
      //load runtimeConfig.json file through a custom loader
      rules: [
        {
          // set the type to javascript/auto to bypass webpack's built-in json importing
          type: 'javascript/auto',
          test: /(runtimeConfig\.json)$/i,
          // file-loader resolves imports on a file and emits that file to dist/
          loader: 'file-loader',
          // use filename runtimeConfig.json instead of a hashed filename
          options: {
            name: '[path][name].[ext]',
            outputPath: 'static',
          }
        }
      ],
    },

My intent is to import a json file in a vue.js components, like this:
import myJson from '@/static/runtimeConfig.json'

But, after I do that import, myJson is just the path to the file, not the actual json contents
console.log(myJson)
--> /static/src/static/runtimeConfig.json

A: That's exactly what file-loader does - it copies the file into dist and returns path to a file. Because its primarily used to process content of img href attributes. Now you can load it onto your running app at runtime by ajax request using the path provided...
If you just want to include JSON file into your app as an object, you can just import it without any Webpack configuration and it will be imported as JS object and included in your JS bundle. This happens at build time


text:
Q: The best way to create an activity that partially overlay the parent Immagine a blank activity. If you swipe from left to right another activity (I think) comes in partially covering the parent.
I would like to recreate this effect:

I'm new to android programming and the only thing that i could think to do that is to use fragment in some strange way.
Since i don't know how to call this "function" i didn't manage to find a lot on the web.
So, is there a method to easly accomplish this? Can you give me any info on where to start e what to search for to do that?
Thanks.

A: This can be done using the DrawerLayout. You can find a lot of help online about using DrawerLayouts, but this link is how I learned and it helped me so much:
https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer


text:
Q: call return inside GCC compound statement expressions Can I safely use return inside GCC compound statement expressions ?
For example I define macro
#define CHECK_FUNC_RESULT(func)    \
({                                 \
   int result = func();            \
   if (!result) return;            \
   result;                         \
})

and use it somewhere in code in such way:
int function1()
{
   if (some_condition)
     return 0;
   ...
   return 1;
}

void function2()
{
   if(CHECK_FUNC_RESULT(function1)) {
      ... to do something
   }
}

Can I expect returning from function2 (on some_condition == true) without any undefined behavior ?

A: It should work, but your if() statement will only be processed if function1 returns 1 (in your example: never). This looks like a dangerous construction, as an else would never be executed.

A: A cleaner way to achieve what you want, and you can also pass any number of arguments to func (in this example 3 args):
#define RET_IF_ZERO(func, args) \
do {                            \
    int result = func args;     \
    if (!result)                \
        return;                 \
} while (0)

Example of usage:
void function1(int arg1, int arg2, int arg3)
{
    if (some_condition)
        return 0;
    ...
    return 1;
}

void function2()
{
   RET_IF_ZERO(function1, (arg1, arg2, arg3)));

   ... do to something
}


text:
Q: Clusters are not showing I am using the below code to generate a graph with two clusters with four nodes each
For some reasons when I print the graph the clusters do not show up.
What am I doing wrong?
import pygraphviz as pgv

A=pgv.AGraph(bgcolor="#cccccc",layout='neato')
A.add_edge('R1','R2')
A.add_edge('R2','R3')
A.add_edge('R3','R4')
A.add_edge('R4','R5')
A.add_edge('R5','R6')
A.add_subgraph(['R1','R2','R3','R4'], 'pbd01')
A.add_subgraph(['R5','R6','R7','R8'], 'pbd02')

A.write('cluster.dot')
A.draw('Topology.png', prog='neato')

A: I believe there are two problems:

*

*The 'neato' rendering engine does not support clustering

*By convention, rendering engines that do support clustering require that the subgraph name starts with 'cluster'

The following code / image was produced with the 'dot' engine and correctly clusters the nodes:
import pygraphviz as pgv

A=pgv.AGraph(bgcolor="#cccccc",layout='dot')
A.add_edge('R1','R2')
A.add_edge('R2','R3')
A.add_edge('R3','R4')
A.add_edge('R4','R5')
A.add_edge('R5','R6')
A.add_subgraph(['R1','R2','R3','R4'], name='cluster_pbd01')
A.add_subgraph(['R5','R6','R7','R8'], name='cluster_pbd02')

A.write('cluster.dot')
A.draw('Topology.png', prog='dot')

Topology.png


text:
Q: Error en HTTP response, code 200 sin mostrar el resultado esperado Tengo una aplicación Symfony 3.4.8 que estaba funcionando perfectamente. Pero ha dejado de cargar mis archivos javascript/css sin más. En Chrome viene todo en código HTML sin cargar los archivos javascript y css. Ya en mozilla me carga algo pero me presenta un encabezado como esta en la figura abajo, y no me carga todos los archivos. Pensaba que era algun error en el response pero, en wikipedia Listado de status HTTP, me pone que el código 200 representa respuestas exitosas. Alguien me podría ayudar?
Ahora mismo ya no me aparece el caracter en ninguno de los archivos. Pero sigue sin leerlos además de que los caracteres en rojo siguen ahí
He seguido los pasos de este post que busca y remueve el BOM pero también no me ha resuelto el problema.
¿Aunque parezca dificil que ocurra, ¿eso podría ser algún error en el response?

A: No lo sé lo que me ha ocurrido, pero el software volvió a funcionar. Como hice vários intentos pondré aqui lo que hice, porque además de seguir todas las sugerencias intenté otras cosas que no me habían sugerido aquí aunque no tengo claro lo que me ha corregido el error, sí que el archivo poseía un algun error con la codifición de los caracteres. Así pongo abajo algunos pasos:

*

*Abrí todos los archivos css y javascript en notepad++ y los cambié uno a uno para UTF-8 (sin BOM). Aquellos que los tenía en UTF-8 sim BOM, los abrí y cambié para UTF-8 salvé, volví a cambiar por UTF-8 sin BOM y los salvé de nuevo.

*Hice lo mismo con todos mis archivos .twig

*Hice lo mismo con mis clases que estaban relacionadas con ese controller.

*Seguí los pasos que me ponen en este enlace que remueve el bom de archivos . Para eso he utilizado cygwin.

*En mi instalación php, borré el archivo php.ini. Cogí un archivo php.ini original y hice los cambios necesarios para que hacer que funcionara php.

*volvi a hacer el paso 1.

A cada paso limpiaba el caché y mas o menos ha sido eso que hice por estos días y como volvió a funcionar, hoy cierro el tema sin tener claro lo que hice que tuvo relevancia de hecho. Así que gracias @aloMalbarez y @OscarGarcia.


text:
Q: Apply custom pairwise function in PyTorch I have two 1D tensors
a = tensor([1, 2])

b = tensor([3, 4, 5])

I want to compute custom operation pairwise matrix, for example
"a + b" - adds every element from a to every element from b
tensor([4, 5, 6], [5, 6, 7])

"a / b" - divides every element from a by every element from b
tensor([1/3, 1/4, 1/5], [2/3, 2/4, 2/5])

Can this be done efficiently, without for cycles?

A: Yes, you can do that element-wise in a vectorised form.
First bring the operands to broadcastable shapes (You can read about the pytorch broadcasting semantics here)
a = a.unsqueeze(-1)   # a.shape == (2, 1)
b = b.unsqueeze(-2)   # b.shape == (1, 3)
# the last line is redundant in fact, according to the semantics

Then apply the operation you want:
c = a / b             # c.shape == (2, 3)


text:
Q: recreating menu existing menu, adding drop down on one item I have the following menu:

And here is my css for this menu:
.menu {
float:right;
}

.menu_item{
background: rgba(0, 0, 0, 0.0);
height:50px;
}

.menu li{
float:left;
height:25px;
padding:24px 10px 0 10px;
text-align: center;
font-size:12px;
}

.menu_img {
opacity:0.5;
filter:alpha(opacity=50); /* For IE8 and earlier */
}

Now, I would like to add drop down for one of the items in the menu, so I re-create the menu as follow:

What changes I should I do to add the drop down on the arrow icon?
I could easily find copy paste menu, but then It will be more difficult to understand how the css drop down is created...
Regards,Zoran

A: Is this what you need ? I have removed images since i didn't have them. Instead, I have just put some text.
http://jsfiddle.net/9ZBJG/
html:

            HOME

            ABOUT ME

            LISTENERS

            FAVORITES

            NOTIFICATIONS

        4

            ARROW

                    SETTINGS

                    SIGNOUT

CSS:
.menu {
float:right;
}

.menu_item{
background: rgba(0, 0, 0, 0.0);
}

.menu > li.menu_item{
float:left;
height:25px;
padding:24px 10px 0 10px;
text-align: center;
font-size:12px;
background-color:#f6f6f6;
position:relative;
}

.menu_item ul{
    display:none;
}

.menu_img {
opacity:0.5;
filter:alpha(opacity=50); /* For IE8 and earlier */
}

.menu_item ul{
    display:none;
}

.menu_item:hover ul{
    display:block;
    position:absolute;
    right:0px;
    top:100%;
}

.menu_item ul li{
    background-color:#f6f6f6;
    padding:5px;
}

EXPLANATION
The structure of css menus is generally as under :

* - MAIN MENU CONTAINER

* - MENU ITEM

* - SUB MENU CONTAINER

* - SUB MENU ITEM

* - SUB MENU ITEM

*

*

If you followed till here, great!
Now all our main menu items need to be next to each other on one line...which is why you used float:left; That's the correct way. But .menu_item is also a class given to sub-menu-items. So I had e a few adjustments so that float:left is only taken by direct children of the main menu container.
Now the SUB-MENU in your case is a , which you have to bring under it's parent
*
For that, you position the parent
* as absolute and position it's child -  - as relative and position accordingly using left and top value. top:100% would mean immediately under the main menu_item.
Now the menu_item in this sub-menu container need to be one below the other. For that, do not give float/position/display properties to these menu_items and the code works fine. (we did that before already)
I did a little CSS-play here with backgrounds and height to help you understand. Feel free to ask more questions. Cheers!


text:
Q: delete record from table only not affect in database If I try to delete record from table but how to use it, I don't know.
In a radgrid I hav use delete link if I have press delete it's I'll be work but I have try to next level of delete.
If I press delete that data I'll be delete on the grid but it's not affect on Sql database but we don't store data from other table can explain how to use it.
<Telerik:RadGrid ID="GVUpload" runat="server" AllowMultiRowSelection="false" GridLines="None"
                                                                      CellPadding="1" CellSpacing="1" HeaderStyle-HorizontalAlign="Center" Skin="WebBlue"
                                                                      AllowPaging="true" PageSize="1000" Height="360PX" Width="100%">

  <ClientSettings EnableRowHoverStyle="true">
    <Selecting AllowRowSelect="false" />
    <Scrolling AllowScroll="True" UseStaticHeaders="True" SaveScrollPosition="true" FrozenColumnsCount="2" />
    <Resizing AllowColumnResize="true" />
  </ClientSettings>
  <MasterTableView AutoGenerateColumns="false" DataKeyNames="pendingdump_gid">
    <Columns>
      <Telerik:GridTemplateColumn HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle" ItemStyle-Width="10%" HeaderStyle-Width="10%" >
        <HeaderTemplate>
          <asp:CheckBox id="chkall" Text="Select" runat="server" Checked="false" onclick="javascript:select_deselectAll (this.checked, this.id, 'chkall','chkupload');" />
        </HeaderTemplate>
        <ItemTemplate>
          <asp:CheckBox ID="chkupload" runat="server" CausesValidation="false" Checked="false" onclick="javascript:select_deselectAll (this.checked, this.id, 'chkall','chkupload');" />
        </ItemTemplate>
      </Telerik:GridTemplateColumn>
      <Telerik:GridBoundColumn DataField="pendingdump_gid" HeaderText="Cust ID" Visible="false"
          ItemStyle-HorizontalAlign="Center">
      </Telerik:GridBoundColumn>
      <Telerik:GridBoundColumn DataField="pendingdump_date" HeaderText="Date" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="10%" HeaderStyle-Width="10%"  ></Telerik:GridBoundColumn>
      <Telerik:GridBoundColumn DataField="pendingdump_refno" HeaderText="Ref.No." ItemStyle-HorizontalAlign="Left" ItemStyle-Width="30%" HeaderStyle-Width="20%" ></Telerik:GridBoundColumn>
      <Telerik:GridBoundColumn DataField="pendingdump_name" HeaderText="Party's Name" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" HeaderStyle-Width="10%" ></Telerik:GridBoundColumn>
      <Telerik:GridBoundColumn DataField="pendingdump_amount" HeaderText="Pending Amount" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" HeaderStyle-Width="10%" ></Telerik:GridBoundColumn>
      <Telerik:GridBoundColumn DataField="pendingdump_duedate" HeaderText="Due On" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" HeaderStyle-Width="10%" ></Telerik:GridBoundColumn>
      <Telerik:GridBoundColumn DataField="pendingdump_overduedays" HeaderText="Overdue by Days" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" HeaderStyle-Width="20%" ></Telerik:GridBoundColumn>
      <Telerik:GridTemplateColumn HeaderText="Action" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle" ItemStyle-Width="30%" HeaderStyle-Width="20%" >
        <ItemTemplate>
          <asp:LinkButton ID="lnkbtnDelete" runat="server" Text="Delete" CausesValidation="false" ToolTip="Click to Delete"
               OnClientClick="javascript:return confirmDelete();" CommandName="lnkbtnDelete" CommandArgument=''
            <%# DataBinder.Eval(Container.DataItem, "pendingdump_gid") %>'>
          </asp:LinkButton>
        </ItemTemplate>
      </Telerik:GridTemplateColumn>
    </Columns>
    <PagerStyle HorizontalAlign="Right" />
  </MasterTableView>
</Telerik:RadGrid>

      Protected Sub GVUpload_ItemCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles GVUpload.ItemCommand

            lblerrmsg.Text = ""

            If e.CommandName = "lnkbtnDelete" Then

                Gobjdbconn.OpenConn()

                MsSql = ""
                MsSql = "Delete vsolv_tmp_tpendingdump where pendingdump_gid = '" & e.CommandArgument() & "' and pendingdump_isremoved = 'N'"

                MnResult = Gobjdbconn.ExecuteNonQuerySQL(MsSql)

                If MnResult = 1 Then
                    lblerrmsg.Text = "Record Deleted Successfully"
                Else
                    lblerrmsg.Text = "Record not Deleted"
                End If

                POPSummary()

            End If

        End Sub


text:
Q: Invalid Hook Call with react-hook-form I am new to react hook form so this may be a simple issue. I just discovered that Controllers do not have the ability to use value as number. This was aggravating , but I eventually found this github issue #8068 which describes the solution as setting an onChange function like this:
<Controller
-    rules={{ valueAsNumber: true }}
      render={({ field }) => (
          <input
-             onChange={field.onChange}
+             onChange={(event) => field.onChange(+event.target.value)}
              type="number"
          />
  )}
/>

So I did some slight altering and came up with this code
import React, { ChangeEvent } from 'react'
import { Controller } from 'react-hook-form'
import { getPlaceholder } from './getPlaceholder'
import { IInput } from './types'

const NumberInput: React.FC<IInput> = ({ control, name, ...props }) => {
  const placeholder = getPlaceholder({ type: "number" });
  const numericalOnChange = (event: ChangeEvent<HTMLInputElement>) => {
    if (event.target.value === '') return null;
    return +event.target.value;
  }

  return (
    <Controller
      control={control}
      name={name}
      render={({ field: { onChange, ...field } }) => (
        <input
          {...props}
          {...field}
          type="number"
          placeholder={placeholder}
          onChange={(event) => {
            const value = numericalOnChange(event)
            onChange(value)
          }}
          className="h-[20px] pl-[4px] py-[8px] bg-transparent border-b
          border-b-[#646464] focus:border-b-[#3898EC] text-[13px]
          text-[#F00] placeholder-[#646464] outline-none m-1 w-full"
        />
      )}
    />
  )
}

export default NumberInput

which in theory should work, but ends up providing an Invalid Hook Call Error.


text:
Q: How to conditionally inline members in F#, or switch off inlining in Debug builds altogether I can't readily remember where I read it, but my understanding of inline was that it is "switched off" (except for statically resolving type constraints) during debug builds. But it isn't, a breakpoint on an inline member is never hit and stepping into is not possible.
Since there is a (slight) semantic difference between using inline and not using it, perhaps this is the reason that inlining is also enforced in debug builds? For inline functions that I do want to investigate during debugging I currently use something like this:
Original code:
type CE =
    static member inline map f = CE.bind (f >> Some)   // line is never hit

Updated code
type CE =
    static member
#if !DEBUG
            inline
#endif
                map f =
        CE.bind (f >> Some)    // gets hit now when debugging

While this works, it is ugly. Is there another possibility, i.e. with a compiler switch or attribute, to turn this on/off, or is that asking for too much trouble (i.e. the earlier mentioned statically resolved type parameters, and perhaps the auto-inlining of user-defined operators).
Note: my primary use-case is actually not debugging per se, but hit-counting of the functions or members, and in lieu of that, code-coverage reports.
Using F# 4.0, .NET 4.5 and Visual Studio 2015.

A: There is a real issue with not following inline directives in several cases. The F# core library offers functions, including the (+) operator, which require the use of statically-resolved type parameters, as you noted in your question. The CLR's generics runtime system doesn't support these types of generics. Instead, the F# compiler is inferring the generic type arguments at compile time and creating the IL necessary to execute for each type that was resolved.
This is a key feature and makes ignoring all inline directives a general non-starter since in many cases it means code won't compile. --nooptimizationdata generally removes optimization data from the generated assembly; it doesn't prevent inlining within the assembly, but it may inhibit other assemblies from inlining when referencing inline functions.
It should also be noted that Don Syme has stated that use of inline is not often required (outside of the SRTP) and may be a premature performance optimization that may actually get in the way of the compiler doing its own optimization.


text:
Q: Auto-click button element on page load using jQuery If I wanted to auto-click a button element on page load, how would I go about this using jQuery?
The button html is
<button class="md-trigger" id="modal" data-modal="modal"></button>

A: I tried the following ways in first jQuery, then JavaScript:
jQuery:
 window.location.href = $(".contact").attr('href');
 $('.contactformone').trigger('click');

This is the best way in JavaScript:
 document.getElementById("id").click();

A: You would simply use jQuery like so...

Use the click function to auto-click the #modal button

A: JavaScript Pure:

JQuery:

or

A: You can use that and adjust the time you want to launch 1= onload 2000= 2 sec

$(document).ready(function(){
 $('#click').click(function(){
        alert('button clicked');
    });
  // set time out 2 sec
     setTimeout(function(){
        $('#click').trigger('click');
    }, 2000);
});
.container{
padding-top:50px;
}

<button id="click" class="btn btn-danger">Jquery Auto Click</button>

A: Use the following code
$("#modal").trigger('click');

A: We should rather use Javascript.
    <button href="images/car.jpg" id="myButton">
        Here is the Button to be clicked
    </button>


text:
Q: View "invalidate" event not called if view not added to activity I have a background view not showed into main activity and I need to get the "invalidate" event for know when something into the view is changed.
The problem is the event "invalidate" is "emitted" by the view only if this view has been added to the main activity thorugh the "addView" call. I don't want to add this view to main UI since is managed in a separate thread but I have this problem of invalidate event not emitted and I don't know how to find a workaround. It seem the "addview" function unlock something that allow to generate invalidate call but still not found the reasons.
Someone know how to force a view to generate invalidate event also if not added to main activity?

A: I think you can't do this, because invalidate method is called by View framework, so this method would't be called if the view is not add to the window. But I think there's a trick: adding this view to the window and hide it below other view, so this view is invisible and the invalidate method will be called by system.

A: Why would you want to invalidate a view that is not there? Instead of finding a workaround I suggest to improve how your app works. Invalidate means that you want to redraw something that is on screen. I don't know your exact use case is but my guess is you want to do something that is not UI related in invalidate. You should not do that.


text:
Q: TypeError : unhashable type: list? I'm trying to write excel file using XLWT from a CSV file(zipcode to State) but when i open csv and take statename from there then get this error otherwise if i set some hardcode value then it's executing.
import xlwt
import csv
row = 1
excelFile = xlwt.Workbook(encoding='utf-8')
sheet1 = excelFile.add_sheet('SampleData')
sheet1.col(0).width = 5000
sheet1.col(1).width = 5000
sheet1.write(0, 0, "Zip")
sheet1.write(0, 1, "State")
zip = '43215'
with open("usZipToCity.csv", 'r', encoding='utf-8') as csvFile:
    reader = csv.reader(csvFile)
    for row in reader:
        if row:
            if zip in row:
                stateName = row[1]

sheet1.write(row, 0, zip)
sheet1.write(row, 1, stateName)
row += 1
excelFile.save("SampleData.xls")

Error Traceback:
Traceback (most recent call last):
  File "G:/scrapingtasks/toddkreal_property/Tester.py", line 47, in <module>
    sheet1.write(row, 0, zip)
  File "C:\Users\muhammadhamaadlatif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\xlwt\Worksheet.py", line 1088, in write
    self.row(r).write(c, label, style)
  File "C:\Users\muhammadhamaadlatif\AppData\Local\Programs\Python\Python37-32\lib\site-packages\xlwt\Worksheet.py", line 1139, in row
    if indx not in self.__rows:
TypeError: unhashable type: 'list'

A: As Martijn pointed out, you are using row for two different purposes:

*

*to hold a line of parsed csv ;

*to hold the index of the next row of the Excel file you will write.

The quickest way to fix this is to use a different variable name for each purposes. For example, you can rename row to csvrow in lines 13, 14, 15 and 16 of the code you provided.
If you have more time, I suggest you take a look at the following code. It includes a few stylistic fixes to your intial implementation as well as a write_row() function you might find interesting.
import xwlt
import csv

from itertools import count

if __name__ == "__main__":
    # Create an Excel file
    EXCELFILE = xwlt.WorkBook(encoding="utf-8")
    # Setup a sheet
    SHEET = EXCELFILE.add_sheet('SampleData')
    SHEET.col(0).width = 5000
    SHEET.col(1).width = 5000

    # Define an easy way to write a row of data to SHEET
    ROW_IDX = count()
    def write_row(*args):
        """Writes a row of data into SHEET"""
        row_idx = next(ROW_IDX)
        for col_idx, arg in enumerate(args):
            SHEET.write(row_idx, col_idx, arg)

    # Write the header (first row)
    write_row("Zip", "State")

    # Set ZIP to the zip code we are interested in
    ZIP = '43215'

    # Parse the csv file
    with open("usZipToCity.csv", encoding="utf-8") as CSVFILE:
        for CSVROW in csv.reader(CSVFILE):
            if ZIP in CSVROW:
                # CSVROW[1] contains a state name
                write_row(ZIP, CSVROW[1])

    # Write the Excel file to disk
    EXCEFILE.save("SampleData.xls")

Note: it is not clear to me from your code whether you expect to find several matching rows in the csv file. If not, you should probably use break after the first match.


text:
Q: Logrotate - nginx logs not rotating inside docker container I've a docker container running nginx which is writing logs to /var/log/nginx
Logrotate is installed in the docker container and the logrotate config file for nginx is set up correctly. Still, the logs are not being automatically rotated by logrotate. Manually forcing log rotate to rotate the logs via logrotate -f /path/to/conf-file works as expected.
My conclusion is that something is not triggering the cron to fire but I can't find the reason.
Here's the Dockerfile for the docker container running nginx:
FROM nginx:1.11

# Remove sym links from nginx image
RUN rm /var/log/nginx/access.log
RUN rm /var/log/nginx/error.log

# Install logrotate
RUN apt-get update && apt-get -y install logrotate

# Copy MyApp nginx config
COPY config/nginx.conf /etc/nginx/nginx.conf

#Copy logrotate nginx configuration
COPY config/logrotate.d/nginx /etc/logrotate.d/

And the docker-compose file:
version: '2'
services:
  nginx:
    build: ./build
    restart: always
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./auth:/etc/nginx/auth
      - ./certs:/etc/nginx/certs
      - ./conf:/etc/nginx/conf
      - ./sites-enabled:/etc/nginx/sites-enabled
      - ./web:/etc/nginx/web
      - nginx_logs:/var/log/nginx
    logging:
      driver: "json-file"
      options:
        max-size: "100m"
        max-file: "1"

volumes:
  nginx_logs:

networks:
  default:
    external:
      name: my-network

Here's the content of: /etc/logrotate.d/nginx
/var/log/nginx/*.log {
        daily
        dateext
        missingok
        rotate 30
        compress
        delaycompress
        notifempty
        create 0640 www-data adm
        sharedscripts
        prerotate
                if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
                        run-parts /etc/logrotate.d/httpd-prerotate; \
                fi \
        endscript
        postrotate
                [ -s /run/nginx.pid ] && kill -USR1 `cat /run/nginx.pid`
        endscript
}

Content of /etc/cron.daily/logrotate
#!/bin/sh

test -x /usr/sbin/logrotate || exit 0
/usr/sbin/logrotate /etc/logrotate.conf

Content of /etc/logrotate.conf
# see "man logrotate" for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create

# uncomment this if you want your log files compressed
#compress

# packages drop log rotation information into this directory
include /etc/logrotate.d

# no packages own wtmp, or btmp -- we'll rotate them here
/var/log/wtmp {
    missingok
    monthly
    create 0664 root utmp
    rotate 1
}

/var/log/btmp {
    missingok
    monthly
    create 0660 root utmp
    rotate 1
}

# system-specific logs may be configured here

Can someone point me in the right direction to why nginx logs are not being automatically rotated by logrotate?
EDIT
I can trace the root cause of this problem to the cron service not being run on the container. A possible solution is to find a way to make the container run both nginx and cron service at the same time.

A: As stated on the edit on my question the problem was that CMD from nginx:1.11 was only starting the nginx process. A work around is to place the following command on my Dockerfile
CMD service cron start && nginx -g 'daemon off;'

This will start nginx as nginx:1.11 starts it and well as start the cron service.
The Dockerfile would look something like:
FROM nginx:1.11

# Remove sym links from nginx image
RUN rm /var/log/nginx/access.log
RUN rm /var/log/nginx/error.log

# Install logrotate
RUN apt-get update && apt-get -y install logrotate

# Copy MyApp nginx config
COPY config/nginx.conf /etc/nginx/nginx.conf

#Copy logrotate nginx configuration
COPY config/logrotate.d/nginx /etc/logrotate.d/

# Start nginx and cron as a service
CMD service cron start && nginx -g 'daemon off;'

A: i found a method from this link, its core idea is use logrotate outside, and conf is as below:
$ sudo vi /etc/logrotate.d/test
/home/test/logs/*log {
    rotate 90
    missingok
    ifempty
    sharedscripts
    compress
    postrotate
        /usr/bin/docker exec nginx-test /bin/sh -c '/usr/sbin/nginx -s reopen > /dev/null 2>/dev/null'
    endscript
}

A: docker exec --user root `docker container ls --filter "name=nginx" --format "{{.Names}}"` nginx -s reopen


text:
Q: Calling API within Celery task never returns I want to get a value from web3.eth.getTransactionCount. It just hangs. This function works fine elsewhere(normal app, console).
To recreate this behavior simply create a new folder, add these 3 files to the folder, and inside that folder run docker-compose up. *Note that infura credentials are safe to use.
dockerfile
FROM python:3.7
WORKDIR /usr/src/app
RUN pip install flask celery[redis] web3

docker-compose.yml
version: "3"
services:
  redis:
    image: redis:5.0.7
    container_name: redis
    ports:
      - "6379:6379"
  myapp:
    build: .
    container_name: myapp
    ports:
      - "5000:5000"
    volumes:
      - .:/usr/src/app
    environment:
      - FLASK_ENV=development
      - WEB3_INFURA_PROJECT_ID=1cc71ab02b99475b8a3172b6a790c2f8
      - WEB3_INFURA_API_SECRET=6a343124ed8e4a6f9b36d28c50ad65ca
    entrypoint: |
      bash -c "python /usr/src/app/app.py"
  celery:
    build: .
    container_name: celery
    volumes:
      - .:/usr/src/app
    environment:
      - WEB3_INFURA_PROJECT_ID=1cc71ab02b99475b8a3172b6a790c2f8
      - WEB3_INFURA_API_SECRET=6a343124ed8e4a6f9b36d28c50ad65ca
    command: celery worker -A app.client -l info

app.py
from flask import Flask
from web3.auto.infura.rinkeby import w3 as web3
from celery import Celery

app = Flask(__name__)
client = Celery(app.name, broker='redis://redis:6379', backend='redis://redis:6379')

@client.task
def never_return():
    print('start')  # this is printed
    nonce = web3.eth.getTransactionCount('0x51cDD4A883144F01Bf0753b6189f3A034866465f')
    print('nonce', nonce)  # this is never printed

@app.route('/')
def index():
    never_return.apply_async()
    return "hello celery"

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

I found only 1 similar unresolved post here: Call to Google Cloud API in Celery task never returns
There seems to be something weird when making a request call by other library within Celery task. Everything works fine when I tried making post requests using request. Unfortunately I don't know how to work around this problem using this request library.
Any kind of suggestions are highly appreciated.

A: it seems to me this issue has something to do with websockets. so i tried to switch it to HTTP. and it works.
here is modified app.py
from flask import Flask
from web3 import Web3
from celery import Celery
from web3.middleware import geth_poa_middleware
import os

app = Flask(__name__)
client = Celery(app.name, broker='redis://redis:6379', backend='redis://redis:6379')

@client.task
def never_return():
    w3 = Web3(Web3.HTTPProvider(f"https://rinkeby.infura.io/v3/{os.getenv('WEB3_INFURA_PROJECT_ID')}", request_kwargs={'timeout': 60}))
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)
    print('started')
    l = w3.eth.getBlock('latest')
    print(f'block number: {l}')
    print('finished ok')

@app.route('/')
def index():
    never_return.apply_async()
    return f"hello celery"

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


text:
Q: jQuery Mobile Flip Switch difficulty Thanks for taking the time to answer my question.
I have the following code mark + jquery code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title></title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" />

        <form id="form1" runat="server">

                        The flip toggle switch is displayed like this:

                            Flip switch:
                        <select name="slider" id="my-slider" data-role="slider">
                            <option id="firstOption" data-test="" data-status="deactivated" value="off">Activated</option>
                            <option id="secondOption" data-test="" data-status="activated" value="on">Deactivated</option>
                        </select>

        </form>

When I click on the flip switch it executes the jquery code (the two alerts). However, I want to be able to set the default value of the flip switch based on a value provided by a web service (i'm using a dummy value for this example => x). However, i cannot make the second element selected... It always defaults to 'Activated'. Any suggestions? Thank you very much!


text:
Q: Past simple or present perfect in these sentences
*

*I have tried to order this book, but it did not work out that way

or

*

*I have tried to order this book, but it has not worked out that way

I don't think that the former is correct, because the past simple excludes the present, so the form "does not work" will be more appropriate here.

A: I completely agree that the present should be used in your first example since both of the sentences, as they are now, sound just a bit off.
With that being said, we cannot deny the fact the latter is correct as it collocates with the action of "trying" and might be able to "work out", while the former makes the meaning empathic since we are talking about a terminated action of " working out", and using the present perfect.
The following could be synonymous with your second example.

I've tried to order the book, but it has yet to work out that way.
(Perhaps the store or website isn't able to provide you with that
service now, but it may be able to at some point of time/soon);

Whereas

I've tried to order the book, but it doesn't work out that way. (
expresses a clear statement )

If you really want to use the past simple in your sentence, it's recommended to omit the perfect tense as it isn't necessarily used there. But its usage is clear and correct.
for instance

I [have - additional emphasis on the time/action of "trying"] tried to order the book, but it didn't work out [a terminated period
in the past, no longer taking place, nor does it give any time
consideration at this moment] that way.


text:
Q: Re-launching a VOIP application from background mode using private API's TO start off with - this app doesn't need to get into the App Store.
I'm thinking something along the lines of the following should work:
    mach_port_t *p;
void *uikit = dlopen(UIKITPATH, RTLD_LAZY);
int (*SBSSpringBoardServerPort)() =
dlsym(uikit, "SBSSpringBoardServerPort");
p = (mach_port_t *)SBSSpringBoardServerPort();
dlclose(uikit);

void *sbserv = dlopen(SBSERVPATH, RTLD_LAZY);
int (*setAPMode)(mach_port_t* port, const char* appID, BOOL suspended, void* unknown, void* unknown2) =
dlsym(sbserv, "SBSLaunchApplicationWithIdentifier");
setAPMode(p, "com.apple.weather", NO, nil, nil);
dlclose(sbserv);

However I'm getting exc_bad_access, which is likely due to the fact that it needs an auth token - I could be wrong though.
Alternatively I'm trying using the following:
Class $SBApplicationController=objc_getClass("SBApplicationController");

NSLog(@"[$SBApplicationController sharedInstance], %@", [$SBApplicationController sharedInstance]);

Sadly the output is null - so I guess this can't be done within the application.
Any ideas? This is driving me crazy - thanks!

A: The iOS sandbox will block or kill any process which isn't started by iOS.


text:
Q: How to only output warnings when launching a program under gdb? I have a program which i am trying to debug. When the program is started under gdb, there are several warnings being outout, but then those warnings are hidden under the output of the program.
How can one ensure that only warnings are shown and remain avalable to be read?

A: If you're asking how to suppress output from your program, then the answer is to do it exactly as you'd do it in the shell.  gdb actually uses the shell to start the inferior when you type run, so some kinds of redirection work.
In this case, to suppress all output, you could do something like:
(gdb) run > /dev/null 2>&1

I'm assuming here that the warnings are things gdb is printing that you want to see.  Unfortunately gdb doesn't remember what it has printed, so there's no way to ask it after the fact.


text:
Q: Polymer-AngularJS two-way data binding I have some custom element created with Polymer. Let's call it x-input, and it looks like this:
<polymer-element name="x-input" attributes="name">
    <template>
        <input type="text" value={{name}}> {{name}}

        <input type="range" value={{age}} > {{age}}
    </template>
 </polymer-element>

And I have this html I use Angular:

        <input id="outer_input" type="text" ng-model="kids[0].name" value={{kids[0].name}} />

        name: {{kids[0].name}} age: {{kids[0].age}}

        <x-input ng-repeat="kid in kids" name={{kid.name}} age={{kid.age}}>
        </x-input>

Here is the JS:
var testApp = angular.module('testApp', []);

testApp.controller('AppCtrl', function ($scope, $http)
{
    $scope.kids = [{"name": "Din", "age": 11}, {"name": "Dina", "age": 17}];
}

The problem is with the two-ways data binding. When I change the #outer_input input value the x-input inner values (name and age) are changed.
But when I change the custom element input only inner binded variable are changed.
How can I change value of binded variable within the polymer element and it will change the model and all outer bound UI and data (two-way binding)?
Thanks

A: If you tell it to, Polymer will reflect model changes back out to the published property (its attribute), but issue is that Angular doesn't observer bindings to attributes.
There's a patch that makes this work like you want: https://github.com/eee-c/angular-bind-polymer
More info here: http://blog.sethladd.com/2014/02/angular-and-polymer-data-binding.html

A: I started the ng-polymer-elements project which lets you have two-way binding between web components and Angular in an Angular-like way:
<input ng-model="model"/>
<paper-input ng-model="model"></paper-elements>

It comes with support for Polymer core and paper elements, and can be configured for any web component.

A: I belive this is what youre looking for simple and transparent 2 way data binding and capability to expand to more custom elements and for javascript not dart
NG Polymer Elements

A: This is my working solution, ng-polymer-elements doesn't work for me ($dirty, $pristine, etc. not working). This is very straighforward IMO
angular.module 'tinizen.admin.ui'
.directive 'paperInput', ->
  restrict: 'E'
  require: 'ngModel'
  link: (scope, elem, attrs, ctrl)->

    watcher = ->
      if ctrl.$dirty then ctrl.$invalid else false

    scope.$watch watcher, (invalid)->
      elem[0].invalid = invalid

    updateModel = (inputValue)-> ctrl.$setViewValue inputValue

    ## attrs.$observe 'inputValue', updateModel not working
    ## so I have to use on 'input'
    elem.on 'input', ->
      scope.$apply ->
        updateModel elem.prop('inputValue')

    updateModel()

    ctrl.$render = ->
      elem.prop 'inputValue', ctrl.$viewValue

A: according to their documentation, when binding to native elements, you have to add an extra binding notation
https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#two-way-native
Here {{name}} will update on input events, the {{age}} only on the change event
<polymer-element name="x-input" attributes="name">
    <template>
        <input type="text" value={{name::input}}> {{name}}

        <input type="range" value={{age::change}} > {{age}}
    </template>
 </polymer-element>


text:
Q: Метод equals не работает во всех циклах do, кроме последнего public static void userRegistration() {
    Scanner in = new Scanner(System.in);
    User user = new User();
    System.out.println("Зарегистрируйте пользователя");
    System.out.println("Введите фамилию");
    user.setLastName(in.nextLine());
    System.out.println("Введите имя");
    user.setFirstName(in.nextLine());
    System.out.println("Введите отчество");
    user.setSurName(in.nextLine());
    System.out.println("Введите номер телефона");
    while (!user.setPhoneNumber(in.nextLine())) ;
    boolean notunique;

    do {
        notunique = false;
        System.out.println("Введите e-mail");
        for (User emailCheck : users) {
            while (!user.setEmail(in.nextLine())) ;
            if (emailCheck.equals(user)) {
                System.out.println("Такой e-mail уже существует, введите другой");
                notunique = true;
            }
        }
    }
    while (notunique);

    do {
        notunique = false;
        System.out.println("Введите логин");
        user.setLogin(in.nextLine());
        for (User loginCheck : users) {
            if (loginCheck.equals(user)) {
                System.out.println("Такой логин уже существует, введите другой");
                notunique = true;
            }
        }
    }
    while (notunique);

    System.out.println("Введите пароль");
    user.setPassword(in.nextLine());
    user.setUserType("guest");
    users.add(user);
    System.out.println("Пользователь добавлен");
}

Добавление нового пользователя в ArrayList.
Циклами do проверяется e-mail и логин на уникальность при помощи метода equals.
Если проверка уникальности только одна (один цикл do), все работает (выдает сообщение о существовании такого же логина или e-mail, если он уже есть в списке, просит ввести заново). Если две или больше, то выполняется только последний.
Полазил по другим темам и видеоурокам на ютюбе, поэкспериментировал с переопределением методов equals() и hashCode() - результат пока тот же. Причем, если делаю всё не через сеттеры, а объявляя переменные перед циклом do, то при таком же подходе все работает. Но задание требует делать всё через сеттеры, что бы параллельно еще проверялось соответствие вводимых значений регулярным выражениям в классе User.
Подскажите, почему не выполняются проверки во всех циклах?


text:
Q: How can I optimize this snippet? Being only able to glue pieces together to get some JS working, I came up with the following code.
if (document.getElementById("component_projector_askforproduct")){
  document.getElementById("component_projector_askforproduct").style.display = "none";
}
if (document.getElementById("askforproduct_58676")){
  document.getElementById("askforproduct_58676").className = "";
}
if (document.getElementById("longdescription_58676")){
  document.getElementById("longdescription_58676").className = "";
}

if (document.getElementById("opinions_58676")){
  document.getElementById("opinions_58676").className = "activTab";
}
if (document.getElementById("component_projector_opinions")){
  document.getElementById("component_projector_opinions").style.display = "block";
}
if (document.getElementById("component_projector_opinions_add")){
  document.getElementById("component_projector_opinions_add").style.display = "block";
}

It works, but I know it's a mess. How could I optimize and slim this code down?

A: EDIT I removed my last answer, and got an idea from Mirko Vukušićs answer.
if you create css classes for hiding and showing elements you could do it like this.
css
.hide { display: none!important; }
.show { display: block!important; }

javascript
var arr = [
  ["component_projector_askforproduct", "hide"],
  ["askforproduct_58676", ""],
  ["longdescription_58676", ""],
  ["opinions_58676", "activTab"],
  ["component_projector_opinions", "show"],
  ["component_projector_opinions_add", "show"]
]

for (i = 0; i < arr.length -1; i++) {
  var elm = document.getElementById(arr[i][0]);
  if(elm) {
    elm.className = arr[i][1];
  }
}

A: What I would do is:

*

*use object to store all your changes like:
var objChecks = {
  component_projector_askforproduct: "some_display_none_className",
  askforproduct_58676: "",
  longdescription_58676: ""
}

*then create function to process it (pass objChecks to it):
function processChecks(checks) {
  Object.getOwnPropertyNames(objChecks).map(function(check){
    var el = document.getElementById(check);
    if (el) el.className=objChecks[check];
  })
}

*change your HTML a bit. I noticed sometimes you change className and sometimes style.display. I'd make a new class that hides an element (same as display=none) which makes everything much neater.

A: use ternary conditions for code beautification.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
or use switch conditions.
suggestion : If i am in this scenario i would make specific function to perform this task and use ternary condition for code beautification.

A: To avoid constant checking, and avoid errors, you can do this neat trick, to set default values:
function $(elem) {

return document.getElementById(elem) || document.createElement("div");
}

So, this way, if element doesn't exist, it will be created, but not appended to body!
Test:

function $(elem) {

return document.getElementById(elem) || document.createElement("div");
}

$("component_projector_askforproduct").style.display = "none";
$("askforproduct_58676").className='';
$('longdescription_58676').className="";
$('opinions_58676').className="activeTab";
$("component_projector_opinions").style.display = "block";
//etc, etc....
.activeTab {
  background:red;
  color:white;
}

6666666666666

qqqqqqqqqqqqqq

11111111111111

A: After analyse question code I understand it is some kind of menu or tabs with possibility to activate,deactivate, show, hide elements. I created structure for this purposes with builded in methods. It can be used on many elements, it can be use on one element many times, it has also chain methods so it is possible to run many methods in one code line.
Check code of this structure and examples, if there is some questions or something is not clear then ask. I am not using ES6 or jQuery because this question is not about that.

var ME = function(){
  //structure represent single menu element
  var MenuElement = function(id){

    this.el = document.getElementById(id);

  };

  MenuElement.prototype.hide = function(){

    if (this.el)
    this.el.style.display = "none";

    return this;
  };

  MenuElement.prototype.show = function(){

    if (this.el)
    this.el.style.display = "block";

    return this;
  };

  MenuElement.prototype.active = function(){

    if (this.el)
    this.el.className = "activeTab";

    return this;

  };

  MenuElement.prototype.deActive = function(){

    if (this.el)
    this.el.className = "";

    return this;
  };

  //return only obj with create method to use it without new keyword
  return {
    create: function(id){
      return new MenuElement(id);
    }
  };

}();

//USE EXAMPLE - the same like in question snippet
ME.create("component_projector_askforproduct").hide();
ME.create("askforproduct_58676").deActive();
ME.create("longdescription_58676").deActive();
ME.create("opinions_58676").active();
ME.create("component_projector_opinions").show();
ME.create("component_projector_opinions_add").show();

//USE EXAMPLE MANY TIMES ON ONE ELEMENT - ONLY EXAMPLE PURPOSES
var element = ME.create("component_projector_askforproduct");
var toggle = true;
setInterval(function(){

   if (toggle)
   element.show().active(); //chaining example
   else
     element.deActive().hide();

   toggle = !toggle;

},1000);
div.activeTab {
     font-weight: bold;
     color: red;
 }

component_projector_askforproduct

askforproduct_58676

longdescription_58676

opinions_58676

component_projector_opinions

component_projector_opinions_add

A: Do not call getElementById twice for the same ID. Store return value in a variable, and check that before trying to manipulate it.


text:
Q: code won't compile generates infinite 2222s The purpose of this code is to construct a char Hadamard matrix of the size of my choosing.
This question is related to a previous question I asked. The answer given there was an integer not char matrix, but the code here is pretty much the same format.
The code compiles but when executed it doesn't finish and I don't know why. When executed infinite 2's are printed.
I get the same result when swap the dynamic Hadamard matrix section for one of a fixed size.

A: Note: I've no idea what your program does, but obviously this is wrong. You failed to actually change the control variable in your for-loop (which can be done in the final expression or the loop body itself).
Change this:
for (ind=1;ind<=sizeH;ind*2)

to this:
for (ind=1;ind<=sizeH;ind*=2) // << note *=


text:
Q: Can't Get Selenium WebDriver to Work on Mac I downloaded the chrome webdriver and got the chromedriver executable in the /usr/local/bin. Still, the error shows up that "driver is not found" There might be something else wrong with the code too.
pip install selenium
from selenium import webdriver
driver = webdriver.Chrome
driver.get('https://www.google.com')

A: The line of code:
pip install selenium

is the part of installing Selenium i.e. Configuration. So it shouln't be part of your script. So you need to remove this line.
Finally, if your usecase is to use selenium-chromedriver and google-chrome you need to initialize the session in the following way:
driver = webdriver.Chrome()
# or
driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver') # presuming chromedriver binary stored at /usr/local/bin


text:
Q: Error in File Upload using google Drive API I'm trying to Upload file to the Google Drive using php.
I'm not able to authenticate to google.
I have generated client_secret.json. as per their suggestion.
But I don't know what is drive-php-quickstart.json here.
I have follow this link :- https://developers.google.com/drive/v3/web/quickstart/php.
I have cloned git's google repository from here
Link :- https://github.com/google/google-api-php-client.
And I have make one file quickstart.php in the root folder but nothing happens and in console it shows.
I have Tried below code.
<?php
require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Drive::DRIVE_METADATA_READONLY)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

// Print the names and IDs for up to 10 files.
$optParams = array(
  'pageSize' => 10,
  'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
  print "No files found.\n";
} else {
  print "Files:\n";
  foreach ($results->getFiles() as $file) {
    printf("%s (%s)\n", $file->getName(), $file->getId());
  }
}

Please suggest me what is I'm missing.


text:
Q: How to convert rows to columns with commasepart using huge data in SQL Server I have a question about SQL Server: how to convert rows to columns with comma-separated data using bulk data?
CREATE TABLE [dbo].[Emp]
(
    [eid] [int] NULL,
    [name] [varchar](50) NULL,
    [sal] [money] NULL,
    [doj] [date] NULL,
    [deptno] [int] NULL
)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (1, N'a', 100.0000, CAST(N'2010-10-01' AS Date), 10)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (2, N'bb', 200.0000, CAST(N'2010-02-03' AS Date), 20)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (3, N'c', 300.0000, CAST(N'2017-02-03' AS Date), 30)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (4, N'd', 301.0000, CAST(N'2010-03-04' AS Date), 10)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (5, N'teee', 250.0000, CAST(N'2010-06-04' AS Date), 20)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (7, N'tte', 800.0000, CAST(N'2010-08-09' AS Date), 70)

I want output like below :
userlist
1,2,3,4,5,7

I tried this code:
select distinct
    stuff((select ',' + cast(u.eid as varchar)
           from emp u
           where 1 = 1
           for xml path('')), 1, 1, '') as userlist
from emp

Suppose if data has 100 thousand entries, then this query is not returning 100 thousand comma-separated
Could you please tell me how to write query to achieve this task in SQL Server?

A: I think the query is working as expected.  But the result is too large to be displayed in management studio.


text:
Q: How to hook CSS file according to theme selection in the customizer section I have added a new area in the Customizer section which allows a user to choose whichever theme colors they want:

But I don't know how to activate/add CSS files according to the selection.
i.e. add green.css if green theme color is selected
or add blue.css if blue theme color is selected.

A: You can access Customizer values with get_theme_mod(), so you just need to check the value of your setting before enqueueing stylesheets the normal way:
function wpse_310123_enqueue_scheme_css() {
    $scheme = get_theme_mod( 'theme_scheme' );

    if ( $scheme === 'green' ) {
        wp_enqueue_style( 'theme-green', get_theme_file_uri( 'green.css' ) );
    } elseif ( $scheme === 'blue') {
        wp_enqueue_style( 'theme-blue', get_theme_file_uri( 'blue.css' ) );
    }
}
add_action( 'wp_enqueue_scripts', 'wpse_310123_enqueue_scheme_css' );

Note that the above code assumes:

*

*The name of your Customizer setting is theme_scheme. If it's not, change that to whatever your actual setting is.

*The possible values are green or blue. If they're something else, like green-theme, then make sure to change those.

*Your blue.css and green.css files are in the root folder of your theme. If they're not, add the directories to the file name, eg. get_theme_file_uri( 'assets/css/green.css' ).


text:
Q: Can I select type of authentication using react-native-biometrics? I am using react-native-biometrics library for login authentication for a banking app I am working. The requirement is to provide both Face ID and Touch ID options to the user so that he can login as per his wish. But while using react-native-biometrics, "biometricType" flag gives only single result.
So, is there any way by which I can customise authentication type?
Also, how can we handle the same scenario in Android as only a common "Biometrics" type is used in the same?
Please help!


text:
Q: Web scraping and promise with node I am using cheerio and node to do web scraping. I thought it would be good idea to use promise for making it easier to deal with the asynchronous code. So, tried to chain the promises but could not make it working. I am pasting my code over here such that somebody could help me figure out what exactly I have been doing wrong.
http.createServer(function(req, res){
  res.writeHead(200, {"Content-Type": "application/json"})
  loadPage().then(parseLoadedData);

}).listen(3000, function(error){
  console.log(error);
});

function fetchMainPage(){
  var deferred = q.defer();
  http.get('http://www.google.com?q=node', function(response){
      var responseString = '';
      response.on('data', function(data){
        responseString += data.toString('utf8');
      });
      response.on('error', function(error){
        deferred.reject(error);
      });
      response.on('end', function(){
        deferred.resolve(responseString);
      });
  });
  return deferred.promise;
}

function parseMainContent(responseString){
  var deferred = q.defer();
  var $ = cheerio.load(responseString);
  var rightCol = $('#right-col');
  var children = rightCol.children();
  var keys = Object.keys(children);
  var results = [];
  keys.forEach(function(key){
    var div = children[key];
    div.children.forEach(function(aChild){
      if(aChild.name == 'h3' && aChild.children[0].data == "Some title"){
        lis = aChild.next.children;
        var results = lis.map(function(li){
          var anchor  = $(li).find('a');
          if(anchor != undefined && anchor.attr('href') != undefined)
          return [anchor.text(), anchor.attr('href')]
        });
        results = results.filter(function(result){
            return result != undefined;
        });
        deferred.resolve(results);
      }
    });
  });
  return deferred.promise;
}

var loadPage = function(){
 return fetchMainPage().then(function(data){
    return data;
  })
},
parseLoadedData = function(data){
  return parseMainContent(data).then(function(results){
    console.log(results);
  });
}

The problem here is I can't get my parseLoadedData being called. The response is fetched from the server but the second chaining does not seem to be working. I would like to thank you all in advance for helping me out.
Note: The url I am using is different and so the parsing function deal with that specific url only.

A: You don't really need the loadPage function since fetchMainPage already returns a promise so this should work:
var loadPage = function(){
 return fetchMainPage();
}

To chain promises every then callback should return another promise and you were returning the data.
Eg.:
var loadPage = function(){
  var deferred = q.defer();
  fetchMainPage().then(function(data){
    return someOtherPromise(data);
  }).then(function(someOtherData) {
    return myThirdPromise(someOtherData);
  }).then(function(myThirdData) {
    return deferred.resolve(myThirdData);
  });
}

// IS THE SAME AS

var loadPage2 = function(){
  return fetchMainPage().then(function(data){
    return someOtherPromise(data);
  }).then(function(someOtherData) {
    return myThirdPromise(someOtherData);
  });
}


text:
Q: Consistency in distances between nodes on vertices along stacked, horizontal line segments in a `TikZ` diagram In the following TikZ diagram, I have depicted an expanding graph - a sequence of simple graphs. An inconsistency in this diagram is the distances between consecutive steps in the expansion. For the first four steps, I just decreased the y-coordinate by 3 of each of the vertices. A multi-line node under a vertex of the fourth graph prevented that from happening. I just put the last graph 6 cm under the fourth graph. It is unseemly.
How do I define a length between (label_for_Vertex_b.south) and (label_for_Farey_Fraction_at_Vertex_b.north) and use that distance to position the fraction (2n+1)/2 on the last graph, and from this node, draw the last horizontal line?
\documentclass{amsart}
\usepackage{amssymb}
\usepackage{mathtools,array}

\usepackage{tikz}
\usetikzlibrary{calc,intersections}

\begin{document}

\begin{tikzpicture}[nodes={inner sep=0, font=\scriptsize,
execute at begin node={\setlength\abovedisplayskip{0.75ex}%
\setlength\belowdisplayskip{0.5ex}%
\setlength\abovedisplayshortskip{0.75ex}%
\setlength\belowdisplayshortskip{0.5ex}}},
shorten/.style={shorten >=#1,shorten <=#1}]

%A sequence of graphs is drawn, starting with the vertex with the b-label b.

%Here is the blow-up of the vertex labeled b.
\draw[fill] (-4,0) circle (1.5pt);
\node[anchor=north] (label_for_Vertex_b) at ($(-4,0) +(0,-0.25)$){\textit{b}};
\node[anchor=south] at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
%
%
\draw (-4,-3) -- (-2,-3);
\draw[fill] (-4,-3) circle (1.5pt);
\draw[fill] (-2,-3) circle (1.5pt);
%
\node[anchor=north] at ($(-4,-3) +(0,-0.25)$){\textit{b}};
\node[anchor=south] (label_for_Farey_Fraction_at_Vertex_b) at ($(-4,-3) +(0,0.25)$){$\dfrac{0}{1}$};
%
\node[anchor=north] (label_for_Vertex_b-1) at ($(-2,-3) +(0,-0.25)$){$b - 1$};
\node[anchor=south] at ($(-2,-3) +(0,0.25)$){$\dfrac{1}{1}$};
%
%
%An arrow is drawn to the next diagram.
\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b) to[bend right=30] node[midway, left=1.5mm, align=center]
{Blow-up of\\vertex \textit{b}} (label_for_Farey_Fraction_at_Vertex_b);

%Here is the blow-up of the vertex labeled b-1.
\draw (-4,-6) -- (-2,-6) -- (0,-6);
\draw[fill] (-4,-6) circle (1.5pt);
\draw[fill] (-2,-6) circle (1.5pt);
\draw[fill] (0,-6) circle (1.5pt);
%
\node[anchor=north] at ($(-4,-6) +(0,-0.25)$){\textit{b}};
\node[anchor=south] at ($(-4,-6) +(0,0.25)$){$\dfrac{0}{1}$};
%
\node[anchor=north] at ($(-2,-6) +(0,-0.25)$){$b-1$};
\node[anchor=south] (label_for_Farey_Fraction_at_Vertex_b-1) at ($(-2,-6) +(0,0.25)$){$\dfrac{1}{1}$};
%
\node[anchor=north] (label_for_Vertex_b-2) at ($(0,-6) +(0,-0.25)$){$b-2$};
\node[anchor=south] at ($(0,-6) +(0,0.25)$){$\dfrac{2}{1}$};
%
%
\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b-1) to[bend right=30] node[midway, left=1.5mm, align=center]
{Blow-up of\\vertex $b - 1$} (label_for_Farey_Fraction_at_Vertex_b-1);

%Here is the blow-up of the vertex labeled b-n.
\draw (-4,-9) -- (-2,-9) -- (0,-9) (2,-9) -- (5,-9);
\draw[fill] (-4,-9) circle (1.5pt);
\draw[fill] (-2,-9) circle (1.5pt);
\draw[fill] (0,-9) circle (1.5pt);
\node at (1,-9){$\ldots$};
\draw[fill] (2,-9) circle (1.5pt);
\draw[fill] (5,-9) circle (1.5pt);
%
\node[anchor=north] at ($(-4,-9) +(0,-0.25)$){\textit{b}};
\node[anchor=south] at ($(-4,-9) +(0,0.25)$){$\dfrac{0}{1}$};
%
\node[anchor=north] at ($(-2,-9) +(0,-0.25)$){$b-1$};
\node[anchor=south] at ($(-2,-9) +(0,0.25)$){$\dfrac{1}{1}$};
%
\node[anchor=north] at ($(0,-9) +(0,-0.25)$){$b-2$};
\node[anchor=south] at ($(0,-9) +(0,0.25)$){$\dfrac{2}{1}$};
%
\node[anchor=south, green] (label_for_phantom_Farey_Fraction_at_ellipses) at ($(1,-9) +(0,0.25)$){$\dfrac{1}{1}$};
%
\node[anchor=north] at ($(2,-9) +(0,-0.25)$){\textit{b-n}};
\node[anchor=south] at ($(2,-9) +(0,0.25)$){$\dfrac{n}{1}$};
%
\node[anchor=north] at ($(5,-9) +(0,-0.25)$){$b-(n+1)$};
\node[anchor=south] at ($(5,-9) +(0,0.25)$){$\dfrac{n+1}{1}$};
%
%
%
%
\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b-2) to[bend right=30] node[midway, left=1.5mm, align=center]
{Blow-up of\\more vertices} (label_for_phantom_Farey_Fraction_at_ellipses);
%
%
%A "pin" is drawn between the midpoint of last two vertices and the label of the mediants of these vertices.
\draw[-latex, dashed, line width=0.8pt, shorten <=3mm, shorten >=1mm] ($(3.5,-9) +(60:2)$) -- (3.5,-9);
\path node[anchor=south, align=center, text width={width("future vertex")}]
at ($(3.5,-9) +(60:2)$){future mediant\\for vertex\[\dfrac{2n+1}{2}\]};
%
%A "pin" is drawn between the midpoint of the edge between the last two vertices and its label.
\coordinate (label_for_Edge) at ($(3.5,-9.5) +(0,-0.75)$);
\draw[draw=gray, line width=0.8pt, shorten <=1mm, shorten >=1mm] (3.5,-9) -- (label_for_Edge);
\node[anchor=north, align=center, inner sep=0, font=\scriptsize] (actual_label_for_Edge) at (label_for_Edge)
{$\begin{aligned} &\text{Present edge label of} \\[-1.5ex]
&\quad 2\bigl[(b-n)+(b-(n+1))\bigr] \\[-1.5ex]
&\qquad=2^{2}b-(2n+1)2
\end{aligned}$};

\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b-1) to[bend right=30] node[midway, left=1.5mm, align=center]
{Blow-up of\\vertex $b - 1$} (label_for_Farey_Fraction_at_Vertex_b-1);

\draw[-latex, line width=0.8pt, shorten <=30pt, shorten >=7.5pt] (label_for_Edge.south) -- ($(label_for_Edge.south) +(0,-4)$);

%Here is the vertex placed at the broken edge.
\draw (-4,-15) -- (-2,-15) -- (0,-15) (2,-15) -- (5,-15);
\draw[fill] (-4,-15) circle (1.5pt);
\draw[fill] (-2,-15) circle (1.5pt);
\draw[fill] (0,-15) circle (1.5pt);
\node at (1,-15){$\ldots$};
\draw[fill] (2,-15) circle (1.5pt);
\draw[fill] ({(2+5)/2},-15) circle (1.5pt);
\draw[fill] (5,-15) circle (1.5pt);
%
\node[anchor=north] at ($(-4,-15) +(0,-0.25)$){\textit{b}};
\node[anchor=south] at ($(-4,-15) +(0,0.25)$){$\dfrac{0}{1}$};
%
\node[anchor=north] at ($(-2,-15) +(0,-0.25)$){$b-1$};
\node[anchor=south] at ($(-2,-15) +(0,0.25)$){$\dfrac{1}{1}$};
%
\node[anchor=north] at ($(0,-15) +(0,-0.25)$){$b-2$};
\node[anchor=south] at ($(0,-15) +(0,0.25)$){$\dfrac{2}{1}$};
%
\node[anchor=north] at ($(2,-15) +(0,-0.25)$){\textit{b-n}};
\node[anchor=south] at ($(2,-15) +(0,0.25)$){$\dfrac{n}{1}$};
%
\node[anchor=north] at ($(5,-15) +(0,-0.25)$){$b-(n+1)$};
\node[anchor=south] at ($(5,-15) +(0,0.25)$){$\dfrac{n+1}{1}$};
%
%A "pin" is drawn between the midpoint of the edge between the last two vertices and its label.
\draw[draw=gray, line width=0.8pt, shorten <=1mm, shorten >=1mm] ({(2+5)/2},-15) -- ({(2+5)/2},-16);
\node[anchor=north] at ({(2+5)/2},-16){$2^{2}b-(n+1)2$};
\node[anchor=south] (Last_Farey_Fraction_in_diagram) at ($({(2+5)/2},-15) +(0,0.25)$){$\dfrac{2n+1}{2}$};

%Extra code to display distances I want between graphs.
\draw[|<->|, green] (label_for_Farey_Fraction_at_Vertex_b) -- (label_for_Vertex_b);
\node[green, anchor=west] at ($($(label_for_Farey_Fraction_at_Vertex_b)!0.5!(label_for_Vertex_b)$) +(0.1,0)$){\textit{D}};
%
\draw[|<->|, green] ($(actual_label_for_Edge.south) +(0.5,0)$) -- ($(Last_Farey_Fraction_in_diagram.north) +(0.5,0)$);
\node[green, anchor=west] at ($($(actual_label_for_Edge.south) +(0.6,0)$)!0.5!($(Last_Farey_Fraction_in_diagram.north) +(0.6,0)$)$){\textbf{Want this to be \textit{D}}};

\end{tikzpicture}

\end{document}

A: To shift complete blocks, you can put them in scopes,
\begin{scope}[yshift=-3cm]
 ...
\end{scope}

This allows you to shift the last block 3cm below the south anchor of the edge label.
\documentclass{amsart}
\usepackage{amssymb}
\usepackage{mathtools,array}

\usepackage{tikz}
\usetikzlibrary{calc,intersections}

\begin{document}

\begin{tikzpicture}[nodes={inner sep=0, font=\scriptsize,
execute at begin node={\setlength\abovedisplayskip{0.75ex}%
\setlength\belowdisplayskip{0.5ex}%
\setlength\abovedisplayshortskip{0.75ex}%
\setlength\belowdisplayshortskip{0.5ex}}},
shorten/.style={shorten >=#1,shorten <=#1}]

%A sequence of graphs is drawn, starting with the vertex with the b-label b.

%Here is the blow-up of the vertex labeled b.
\draw[fill] (-4,0) circle (1.5pt);
\node[anchor=north] (label_for_Vertex_b) at ($(-4,0) +(0,-0.25)$){\textit{b}};
\node[anchor=south] at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
%
%
\begin{scope}[yshift=-3cm]
 \draw (-4,0) -- (-2,0);
 \draw[fill] (-4,0) circle (1.5pt);
 \draw[fill] (-2,0) circle (1.5pt);
 %
 \node[anchor=north] at ($(-4,0) +(0,-0.25)$){\textit{b}};
 \node[anchor=south] (label_for_Farey_Fraction_at_Vertex_b) at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
 %
 \node[anchor=north] (label_for_Vertex_b-1) at ($(-2,0) +(0,-0.25)$){$b - 1$};
 \node[anchor=south] at ($(-2,0) +(0,0.25)$){$\dfrac{1}{1}$};
 %
 %
 %An arrow is drawn to the next diagram.
 \draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b) to[bend right=30] node[midway, left=1.5mm, align=center]
 {Blow-up of\\vertex \textit{b}} (label_for_Farey_Fraction_at_Vertex_b);
\end{scope}

\begin{scope}[yshift=-6cm]
 %Here is the blow-up of the vertex labeled b-1.
 \draw (-4,0) -- (-2,0) -- (0,0);
 \draw[fill] (-4,0) circle (1.5pt);
 \draw[fill] (-2,0) circle (1.5pt);
 \draw[fill] (0,0) circle (1.5pt);
 %
 \node[anchor=north] at ($(-4,0) +(0,-0.25)$){\textit{b}};
 \node[anchor=south] at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
 %
 \node[anchor=north] at ($(-2,0) +(0,-0.25)$){$b-1$};
 \node[anchor=south] (label_for_Farey_Fraction_at_Vertex_b-1) at ($(-2,0) +(0,0.25)$){$\dfrac{1}{1}$};
 %
 \node[anchor=north] (label_for_Vertex_b-2) at ($(0,0) +(0,-0.25)$){$b-2$};
 \node[anchor=south] at ($(0,0) +(0,0.25)$){$\dfrac{2}{1}$};
\end{scope}
%
%
\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b-1) to[bend right=30] node[midway, left=1.5mm, align=center]
{Blow-up of\\vertex $b - 1$} (label_for_Farey_Fraction_at_Vertex_b-1);

\begin{scope}[yshift=-9cm]
%Here is the blow-up of the vertex labeled b-n.
 \draw (-4,0) -- (-2,0) -- (0,0) (2,0) -- (5,0);
 \draw[fill] (-4,0) circle (1.5pt);
 \draw[fill] (-2,0) circle (1.5pt);
 \draw[fill] (0,0) circle (1.5pt);
 \node at (1,0){$\ldots$};
 \draw[fill] (2,0) circle (1.5pt);
 \draw[fill] (5,0) circle (1.5pt);
 %
 \node[anchor=north] at ($(-4,0) +(0,-0.25)$){\textit{b}};
 \node[anchor=south] at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
 %
 \node[anchor=north] at ($(-2,0) +(0,-0.25)$){$b-1$};
 \node[anchor=south] at ($(-2,0) +(0,0.25)$){$\dfrac{1}{1}$};
 %
 \node[anchor=north] at ($(0,0) +(0,-0.25)$){$b-2$};
 \node[anchor=south] at ($(0,0) +(0,0.25)$){$\dfrac{2}{1}$};
 %
 \node[anchor=south, green] (label_for_phantom_Farey_Fraction_at_ellipses) at ($(1,0) +(0,0.25)$){$\dfrac{1}{1}$};
 %
 \node[anchor=north] at ($(2,0) +(0,-0.25)$){\textit{b-n}};
 \node[anchor=south] at ($(2,0) +(0,0.25)$){$\dfrac{n}{1}$};
 %
 \node[anchor=north] at ($(5,0) +(0,-0.25)$){$b-(n+1)$};
 \node[anchor=south] at ($(5,0) +(0,0.25)$){$\dfrac{n+1}{1}$};
 %
 %
 %
 %
 \draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b-2) to[bend right=30] node[midway, left=1.5mm, align=center]
 {Blow-up of\\more vertices} (label_for_phantom_Farey_Fraction_at_ellipses);
 %
 %
 %A "pin" is drawn between the midpoint of last two vertices and the label of the mediants of these vertices.
 \draw[-latex, dashed, line width=0.8pt, shorten <=3mm, shorten >=1mm] ($(3.5,0) +(60:2)$) -- (3.5,0);
 \path node[anchor=south, align=center, text width={width("future vertex")}]
 at ($(3.5,0) +(60:2)$){future mediant\\for vertex\[\dfrac{2n+1}{2}\]};
 %
 %A "pin" is drawn between the midpoint of the edge between the last two vertices and its label.
 \coordinate (label_for_Edge) at ($(3.5,-0.5) +(0,-0.75)$);
 \draw[draw=gray, line width=0.8pt, shorten <=1mm, shorten >=1mm] (3.5,0) -- (label_for_Edge);
 \node[anchor=north, align=center, inner sep=0, font=\scriptsize] (edge label) at (label_for_Edge)
 {$\begin{aligned} &\text{Present edge label of} \\[-1.5ex]
 &\quad 2\bigl[(b-n)+(b-(n+1))\bigr] \\[-1.5ex]
 &\qquad=2^{2}b-(2n+1)2
 \end{aligned}$};
\end{scope}

\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b-1) to[bend right=30] node[midway, left=1.5mm, align=center]
{Blow-up of\\vertex $b - 1$} (label_for_Farey_Fraction_at_Vertex_b-1);

\path ($(0,0|-edge label.south)+(0,-3)$) coordinate(auxp);
\begin{scope}[shift={(auxp)}]
 %Here is the vertex placed at the broken edge.
 \draw (-4,0) -- (-2,0) -- (0,0) (2,0) -- (5,0);
 \draw[fill] (-4,0) circle (1.5pt);
 \draw[fill] (-2,0) circle (1.5pt);
 \draw[fill] (0,0) circle (1.5pt);
 \node at (1,0){$\ldots$};
 \draw[fill] (2,0) circle (1.5pt);
 \draw[fill] ({(2+5)/2},0) circle (1.5pt);
 \draw[fill] (5,0) circle (1.5pt);
 %
 \node[anchor=north] at ($(-4,0) +(0,-0.25)$){\textit{b}};
 \node[anchor=south] at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
 %
 \node[anchor=north] at ($(-2,0) +(0,-0.25)$){$b-1$};
 \node[anchor=south] at ($(-2,0) +(0,0.25)$){$\dfrac{1}{1}$};
 %
 \node[anchor=north] at ($(0,0) +(0,-0.25)$){$b-2$};
 \node[anchor=south] at ($(0,0) +(0,0.25)$){$\dfrac{2}{1}$};
 %
 \node[anchor=north] at ($(2,0) +(0,-0.25)$){\textit{b-n}};
 \node[anchor=south] at ($(2,0) +(0,0.25)$){$\dfrac{n}{1}$};
 %
 \node[anchor=north] at ($(5,0) +(0,-0.25)$){$b-(n+1)$};
 \node[anchor=south] at ($(5,0) +(0,0.25)$){$\dfrac{n+1}{1}$};
 %
 %A "pin" is drawn between the midpoint of the edge between the last two vertices and its label.
 \draw[draw=gray, line width=0.8pt, shorten <=1mm, shorten >=1mm] ({(2+5)/2},0)
 -- ({(2+5)/2},-1);
 \node[anchor=north] at ({(2+5)/2},-1){$2^{2}b-(n+1)2$};
 \node[anchor=south] (f2n) at ($({(2+5)/2},0) +(0,0.25)$){$\dfrac{2n+1}{2}$};
\end{scope}
\draw[-latex, line width=0.8pt, shorten <=30pt, shorten >=7.5pt]
(label_for_Edge.south) -- (f2n.north);
\end{tikzpicture}

\end{document}

As mentioned here, you would possibly benefit greatly using positioning to position the blocks relative to each other. This answer is written under the assumption that there are some reasons why you do not want to use positioning.
Here is another attempt to make you happy. The trick is to put of these layers in pics and to put the ("fake") pics in a matrix.

The vertical distance between these layers/pics is entirely fixed by
  column sep.

If you want to add annotations that should not alter the size of these pics, use either overlay or add them outside of the matrix. Examples for both can be found in the MWE
\documentclass{amsart}
\usepackage{amssymb}
\usepackage{mathtools,array}

\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}

\begin{tikzpicture}[nodes={inner sep=0, font=\scriptsize,
execute at begin node={\setlength\abovedisplayskip{0.75ex}%
\setlength\belowdisplayskip{0.5ex}%
\setlength\abovedisplayshortskip{0.75ex}%
\setlength\belowdisplayshortskip{0.5ex}}},
shorten/.style={shorten >=#1,shorten <=#1},
pics/fpic/.style={code={#1}}]

%A sequence of graphs is drawn, starting with the vertex with the b-label b.

\matrix[row sep=4.5em]{%<- this defines the difference between pics
%Here is the blow-up of the vertex labeled b.
\pic{fpic={%
\draw[fill] (-4,0) circle (1.5pt);
\node[anchor=north] (label_for_Vertex_b) at ($(-4,0) +(0,-0.25)$){\textit{b}};
\node[anchor=south] at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
}};\\
%
%
\pic{fpic={%
\draw (-4,0) -- (-2,0) coordinate(lcompare);
 \draw[fill] (-4,0) circle (1.5pt);
 \draw[fill] (-2,0) circle (1.5pt);
 %
 \node[anchor=north] (bcompare) at ($(-4,0) +(0,-0.25)$){\textit{b}};
 \node[anchor=south] (label_for_Farey_Fraction_at_Vertex_b) at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
 %
 \node[anchor=north] (label_for_Vertex_b-1) at ($(-2,0) +(0,-0.25)$){$b - 1$};
 \node[anchor=south] at ($(-2,0) +(0,0.25)$){$\dfrac{1}{1}$};
 }};\\
 %
 %
\pic{fpic={%
 %Here is the blow-up of the vertex labeled b-1.
 \draw (-4,0) -- (-2,0) -- (0,0);
 \draw[fill] (-4,0) circle (1.5pt);
 \draw[fill] (-2,0) circle (1.5pt);
 \draw[fill] (0,0) circle (1.5pt);
 %
 \node[anchor=north] at ($(-4,0) +(0,-0.25)$){\textit{b}};
 \node[anchor=south] at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
 %
 \node[anchor=north] at ($(-2,0) +(0,-0.25)$){$b-1$};
 \node[anchor=south] (label_for_Farey_Fraction_at_Vertex_b-1) at ($(-2,0) +(0,0.25)$){$\dfrac{1}{1}$};
 %
 \node[anchor=north] (label_for_Vertex_b-2) at ($(0,0) +(0,-0.25)$){$b-2$};
 \node[anchor=south] at ($(0,0) +(0,0.25)$){$\dfrac{2}{1}$};
}};\\
\pic{fpic={
%Here is the blow-up of the vertex labeled b-n.
 \draw (-4,0) -- (-2,0) -- (0,0) (2,0) -- (5,0);
 \draw[fill] (-4,0) circle (1.5pt);
 \draw[fill] (-2,0) circle (1.5pt);
 \draw[fill] (0,0) circle (1.5pt);
 \node at (1,0){$\ldots$};
 \draw[fill] (2,0) circle (1.5pt);
 \draw[fill] (5,0) circle (1.5pt);
 %
 \node[anchor=north] at ($(-4,0) +(0,-0.25)$){\textit{b}};
 \node[anchor=south] at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
 %
 \node[anchor=north] at ($(-2,0) +(0,-0.25)$){$b-1$};
 \node[anchor=south] at ($(-2,0) +(0,0.25)$){$\dfrac{1}{1}$};
 %
 \node[anchor=north] at ($(0,0) +(0,-0.25)$){$b-2$};
 \node[anchor=south] at ($(0,0) +(0,0.25)$){$\dfrac{2}{1}$};
 %
 \node[anchor=south, green] (label_for_phantom_Farey_Fraction_at_ellipses) at ($(1,0) +(0,0.25)$){$\dfrac{1}{1}$};
 %
 \node[anchor=north] at ($(2,0) +(0,-0.25)$){\textit{b-n}};
 \node[anchor=south] at ($(2,0) +(0,0.25)$){$\dfrac{n}{1}$};
 %
 \node[anchor=north] at ($(5,0) +(0,-0.25)$){$b-(n+1)$};
 \node[anchor=south] at ($(5,0) +(0,0.25)$){$\dfrac{n+1}{1}$};
 %
 %
 %
 %
 %
 %A "pin" is drawn between the midpoint of last two vertices and the label of the mediants of these vertices.
 \draw[-latex, dashed, line width=0.8pt, shorten <=3mm, shorten >=1mm,overlay] ($(3.5,0) +(60:2)$) -- (3.5,0);
 \path node[anchor=south, align=center, text width={width("future
 vertex")},overlay]
 at ($(3.5,0) +(60:2)$){future mediant\\for vertex\[\dfrac{2n+1}{2}\]};
 %
 %A "pin" is drawn between the midpoint of the edge between the last two vertices and its label.
 \coordinate (label_for_Edge) at ($(3.5,-0.5) +(0,-0.75)$);
 \draw[draw=gray, line width=0.8pt, shorten <=1mm, shorten >=1mm] (3.5,0) -- (label_for_Edge);
 \node[anchor=north, align=center, inner sep=0, font=\scriptsize] (edge label) at (label_for_Edge)
 {$\begin{aligned} &\text{Present edge label of} \\[-1.5ex]
 &\quad 2\bigl[(b-n)+(b-(n+1))\bigr] \\[-1.5ex]
 &\qquad=2^{2}b-(2n+1)2
 \end{aligned}$};
}};\\
\pic{fpic={
 %Here is the vertex placed at the broken edge.
 \draw (-4,0) -- (-2,0) -- (0,0) (2,0) -- (5,0);
 \draw[fill] (-4,0) circle (1.5pt);
 \draw[fill] (-2,0) circle (1.5pt);
 \draw[fill] (0,0) circle (1.5pt);
 \node at (1,0){$\ldots$};
 \draw[fill] (2,0) circle (1.5pt);
 \draw[fill] ({(2+5)/2},0) circle (1.5pt);
 \draw[fill] (5,0) circle (1.5pt);
 %
 \node[anchor=north] at ($(-4,0) +(0,-0.25)$){\textit{b}};
 \node[anchor=south] at ($(-4,0) +(0,0.25)$){$\dfrac{0}{1}$};
 %
 \node[anchor=north] at ($(-2,0) +(0,-0.25)$){$b-1$};
 \node[anchor=south] at ($(-2,0) +(0,0.25)$){$\dfrac{1}{1}$};
 %
 \node[anchor=north] at ($(0,0) +(0,-0.25)$){$b-2$};
 \node[anchor=south] at ($(0,0) +(0,0.25)$){$\dfrac{2}{1}$};
 %
 \node[anchor=north] at ($(2,0) +(0,-0.25)$){\textit{b-n}};
 \node[anchor=south] at ($(2,0) +(0,0.25)$){$\dfrac{n}{1}$};
 %
 \node[anchor=north] at ($(5,0) +(0,-0.25)$){$b-(n+1)$};
 \node[anchor=south] at ($(5,0) +(0,0.25)$){$\dfrac{n+1}{1}$};
 %
 %A "pin" is drawn between the midpoint of the edge between the last two vertices and its label.
 \draw[draw=gray, line width=0.8pt, shorten <=1mm, shorten >=1mm] ({(2+5)/2},0)
 -- ({(2+5)/2},-1);
 \node[anchor=north] at ({(2+5)/2},-1){$2^{2}b-(n+1)2$};
 \node[anchor=south] (f2n) at ($({(2+5)/2},0) +(0,0.25)$){$\dfrac{2n+1}{2}$};
}};\\
};
%An arrow is drawn to the next diagram.
\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b) to[bend right=30] node[midway, left=1.5mm, align=center]
 {Blow-up of\\vertex \textit{b}} (label_for_Farey_Fraction_at_Vertex_b);
%
\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b-1) to[bend right=30] node[midway, left=1.5mm, align=center]
{Blow-up of\\vertex $b - 1$} (label_for_Farey_Fraction_at_Vertex_b-1);
%
\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b-2) to[bend right=30] node[midway, left=1.5mm, align=center]
 {Blow-up of\\more vertices} (label_for_phantom_Farey_Fraction_at_ellipses);
%
\draw[-latex, line width=0.8pt, shorten=7.5pt] (label_for_Vertex_b-1) to[bend right=30] node[midway, left=1.5mm, align=center]
{Blow-up of\\vertex $b - 1$} (label_for_Farey_Fraction_at_Vertex_b-1);
%
\draw[-latex, line width=0.8pt, shorten <=30pt, shorten >=7.5pt]
(label_for_Edge.south) -- (f2n.north);
\end{tikzpicture}
\end{document}


text:
Q: Proper way to backup my Azure VM? I need to backup atleast 4 VM's I have on the Azure platform. Each are for different companies but, I have to provide weekly backups. Should I purchase disk space and attach each VM to this disk space to back them up to? At this point the other companies have access to the other companies backup. Do I have to create disk space for each company, connect the server to this disk and backup to that?
Here are my issues, how can I get this done immediately?

A: Assuming you are following the best practice strategy of: NOT installing anything on the OS or temporary drive (since those get wiped each time the server reprovisioned/redeployed/gets moved in the rack of the datacenter), all you need to worry about is your data disks.
Data disks in Azure use Azure Blob Storage (VHDs), therefore you can use a free tool like CloudXplorer (http://clumsyleaf.com/products/cloudxplorer) and log into your storage account and make a copy of the VHD...as a best practice to another blob storage account in a different region.
You can automate this, by using PowerShell API and copy the VHDs to another storage account/ftp site etc.

A: Azure now how more robust solutions for backing up VMs on Azure, directly within Azure. You can find out more at http://azure.microsoft.com/en-us/services/backup/


text:
Q: Setup Database on Appharbor I started an application with C# and MVC using code first to create my model.
My question is how to do you setup a sql database to run with AppHarbor.  I want to use the ASP.NET SQL profile provider for my users and also a database for the model that I created.
I have heard of SQL Migrations but not too familiar. Should I just use that to create a script and then manually build on AppHarbor using management studio and then just add the connection string as they suggest in AppHarbor to wire everything together?
Any help is greatly appreciated as I am close to getting a live app but I cannot figure out how to setup the databases properly.
Good blog post example that I found after asking this question

A: Creating your own:
var uriString = ConfigurationManager.AppSettings["SQLSERVER_URI"];
var uri = new Uri(uriString);
var connectionString = new SqlConnectionStringBuilder
{
    DataSource = uri.Host,
    InitialCatalog = uri.AbsolutePath.Trim('/'),
    UserID = uri.UserInfo.Split(':').First(),
    Password = uri.UserInfo.Split(':').Last(),
}.ConnectionString;

developing the name:
<connectionStrings>
    <add name="connectionstringname" connectionString="Server=localhost;
        Database=my-app-debug;User ID=test;Password=dfy5fgFdsvV;" />
<connectionStrings>

More info: http://support.appharbor.com/kb/add-ons/using-sequelizer
THIS IS A FAQ: theres info there where it shows when people run into a connection problem with management studio, it will be helpful.
http://support.appharbor.com/kb/getting-started/frequently-asked-questions

A: If you are using Entity Framework, you should probably using Migrations functionality as well. With migrations your app update schema (if required) in each application start, so you need to only worry about right connection string that would point to AppHabor SQL instance.