问:
Accessing Method that is not included in Constructor
I have a class that I created to connect to a database and do various inserts, delete, alter etc...

An array is included to show all. In the database an ID is created automatically so I do not input it, but I would still like the array to output the ID from each column. The code I have is seen below and if I insert cID before cJourneys etc.I get the constructor is undefined. Looking to figure out how to access the ID from the database to call it each time with the array..

```<code>public Car(String cLicenseIn, int cJourneysIn, String cUsernameIn, String cPasswordIn) {
    cLicense = cLicenseIn;
    cJourneys = cJourneysIn;
    cUsername = cUsernameIn;
    cPassword = cPasswordIn;
</code>```

}

```<code>// Display all Vehicles
public ArrayList<Car> getAllCar() {
    ArrayList<Car> AllCar = new ArrayList<Car>();
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url + dbName, userName, password);
        statement = conn.createStatement();
        resultSet = statement.executeQuery("select * from eflow.Registration");

        while (resultSet.next()) {
            Car nextCar = new Car(resultSet.getString("cLicense"), resultSet.getInt("cJourneys"),
                    resultSet.getString("cUsername"), resultSet.getString("cPassword").toString());
            AllCar.add(nextCar);
        }
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return AllCar;
}
</code>```

答:
Like methods, constructors can also be overloaded (accepting different set of arguments) in Java, so you can overload the Car constructor which accepts id as well i.e., you will be having two constructors for your Car class.

Car constructor with id parameter (use this whenever you want to Create Car from database):

```<code>public Car(String id, String cLicenseIn,
 int cJourneysIn, String cUsernameIn, String cPasswordIn) {
  //set fields here
}
</code>```

Car constructor without id parameter (use this whenever you want to create Car from user inputs):

```<code>public Car(String cLicenseIn, int cJourneysIn,
             String cUsernameIn, String cPasswordIn) {
   //set fields here
}
</code>```

getAllCar() method:

```<code>public ArrayList<Car> getAllCar() {
    ArrayList<Car> AllCar = new ArrayList<Car>();
    try {
           //add your existing code here

            Car nextCar = new Car(resultSet.getString("ID"), ,
               resultSet.getString("cLicense"),
               resultSet.getInt("cJourneys"),
               resultSet.getString("cUsername"),
               resultSet.getString("cPassword").toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
       //add null checks and close the resources
       statement.close();
       conn.close();
       resultSet.close();
    }
    return AllCar;
}
</code>```

Also, I strongly suggest you to close the resources in the finally block or use try with resources, otherwise you will end up with resource leaks.

Body:
I have a class that I created to connect to a database and do various inserts, delete, alter etc...

An array is included to show all. In the database an ID is created automatically so I do not input it, but I would still like the array to output the ID from each column. The code I have is seen below and if I insert cID before cJourneys etc.I get the constructor is undefined. Looking to figure out how to access the ID from the database to call it each time with the array..

public Car(String cLicenseIn, int cJourneysIn, String cUsernameIn, String cPasswordIn) {
    cLicense = cLicenseIn;
    cJourneys = cJourneysIn;
    cUsername = cUsernameIn;
    cPassword = cPasswordIn;

}

// Display all Vehicles
public ArrayList<Car> getAllCar() {
    ArrayList<Car> AllCar = new ArrayList<Car>();
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url + dbName, userName, password);
        statement = conn.createStatement();
        resultSet = statement.executeQuery("select * from eflow.Registration");

        while (resultSet.next()) {
            Car nextCar = new Car(resultSet.getString("cLicense"), resultSet.getInt("cJourneys"),
                    resultSet.getString("cUsername"), resultSet.getString("cPassword").toString());
            AllCar.add(nextCar);
        }
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return AllCar;
}

Body:
Like methods, constructors can also be overloaded (accepting different set of arguments) in Java, so you can overload the Car constructor which accepts id as well i.e., you will be having two constructors for your Car class.

Car constructor with id parameter (use this whenever you want to Create Car from database):

public Car(String id, String cLicenseIn,
 int cJourneysIn, String cUsernameIn, String cPasswordIn) {
  //set fields here
}

Car constructor without id parameter (use this whenever you want to create Car from user inputs):

public Car(String cLicenseIn, int cJourneysIn,
             String cUsernameIn, String cPasswordIn) {
   //set fields here
}

getAllCar() method:

public ArrayList<Car> getAllCar() {
    ArrayList<Car> AllCar = new ArrayList<Car>();
    try {
           //add your existing code here

            Car nextCar = new Car(resultSet.getString("ID"), ,
               resultSet.getString("cLicense"),
               resultSet.getInt("cJourneys"),
               resultSet.getString("cUsername"),
               resultSet.getString("cPassword").toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
       //add null checks and close the resources
       statement.close();
       conn.close();
       resultSet.close();
    }
    return AllCar;
}

Also, I strongly suggest you to close the resources in the finally block or use try with resources, otherwise you will end up with resource leaks.


来源: stackexchange

问:
Why is this Python function not working?
Keeps returning "You are older than some hills" even if i input less than 30</p>

```<code>age = raw_input("What age are you?")
def old(n):
  if n >= 30:
    print "You are older than some hills"
  else:
    print "Youth"

old(age)
</code>```

答:
The raw_input() function uses the input as strings, therefore, you should convert the input to int type.

```<code>age = int(raw_input("What age are you?"))
def old(n):
if n >= 30:
  print "You are older than some hills"
else:
  print "Youth"

old(age)
</code>```

This will work.

ContentLicense: CC BY-SA 3.0

Body:
Keeps returning "You are older than some hills" even if i input less than 30

age = raw_input("What age are you?")
def old(n):
  if n >= 30:
    print "You are older than some hills"
  else:
    print "Youth"

old(age)

Body:
The raw_input() function uses the input as strings, therefore, you should convert the input to int type.

age = int(raw_input("What age are you?"))
def old(n):
if n >= 30:
  print "You are older than some hills"
else:
  print "Youth"

old(age)

This will work.


问:
Counting preceding/succeeding cell values in a range in Excel
I am trying to figure out how to write a formula to count preceding and succeeding cell values of a specific value in a range. Here is an example:

For this column, how many times does "black" come before "red", how many times does "green" come before "yellow", etc?

Color List

答:
This is just a stab in the dark as to what you are looking for,  This will count based on the grid, how many are in adjacent cells.

```<code>=SUM(COUNTIFS($A$1:$A$1040001,$C2,$A$2:$A$1040002,D$1),COUNTIFS($A$1:$A$1040001,D$1,$A$2:$A$1040002,$C2))
</code>```

Body:
This is just a stab in the dark as to what you are looking for,  This will count based on the grid, how many are in adjacent cells.

=SUM(COUNTIFS($A$1:$A$1040001,$C2,$A$2:$A$1040002,D$1),COUNTIFS($A$1:$A$1040001,D$1,$A$2:$A$1040002,$C2))


问:
Navbar Button doesn't vertically align
i have been playing around with bootstrap to setup a navbar the way i would like it to be.
I am struggling as you might see in my code to have everything vertically centered properly in this menu. I have made some average fix by playing with the margin but i can't fix the button.
I am sure there is a simple solution with position:relative to have everything center but i can't find it.

http://codepen.io/anon/pen/yMGEZb

Thanks for your help !

答:
updated codepen

Just add the button inside navbar-right li.no need to modify your css.

example snippet

.navbar-default .navbar-header .navbar-brand {
  font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
  font-weight: 200;
  letter-spacing: 1px;
  color: #fdcc52;

}
.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
  color: #fcbd20;
}
.navbar-default .navbar-header .navbar-toggle {
  font-size: 12px;
  color: #222222;
  padding: 8px 10px;
}
.navbar-default .nav > li > a {
  font-family: Montserrat;
  font-weight:300;
  font-style:normal;
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 13px;
  color: #121212;
}
/*@media (min-width: 768px)
    .button-nav {
    display: inline-block;
    z-index: 101;
}*/

.button-nav {
  position: relative;
  bottom: 50%;
  background-color: transparent;
  font-family: Montserrat;
  font-weight: 300;
  font-style:normal;
  letter-spacing:2px;
  font-size: 13px;
  color: #121212;
  text-transform: uppercase;
  border: 1px solid #121212;
  padding: 18px 40px;
  transition: color .4s cubic-bezier(.694,.0482,.335,1),background-color .4s cubic-bezier(.694,.0482,.335,1),border .4s cubic-bezier(.694,.0482,.335,1);
  cursor:pointer;
  text-align:center;
  text-rendering: optimizeLegibility;

}

.button-nav:hover {
background-color: #1c1c1c;
  font-family: Montserrat;
  font-weight: 300;
  font-style:normal;
  letter-spacing:2px;
  font-size: 13px;
  color: white;
  text-transform: uppercase;
  border: 1px solid #1c1c1c;
  padding: 18px 40px;
  transition: color .4s cubic-bezier(.694,.0482,.335,1),background-color .4s cubic-bezier(.694,.0482,.335,1),border .4s cubic-bezier(.694,.0482,.335,1);
  cursor:pointer;
  text-align:center;
  text-rendering: optimizeLegibility;

}

.navbar-default .nav > li > a,
.navbar-default .nav > li > a:focus {
  color: #121212;
}
.navbar-default .nav > li > a:hover,
.navbar-default .nav > li > a:focus:hover {
  color: #fdcc52;
}
.navbar-default .nav > li.active > a,
.navbar-default .nav > li.active > a:focus {
  color: #fdcc52 !important;
  background-color: transparent;
}
.navbar-default .nav > li.active > a:hover,
.navbar-default .nav > li.active > a:focus:hover {
  background-color: transparent;
}
@media (min-width: 768px) {
  .navbar-default {
    background-color: transparent;
    border-color: transparent;
  }
  .navbar-default .navbar-header .navbar-brand {
    color: rgba(34, 34, 34, 0.1);
  }
  .navbar-default .navbar-header .navbar-brand:hover,
  .navbar-default .navbar-header .navbar-brand:focus {
    color: white;
  }
  .navbar-default .nav > li > a,
  .navbar-default .nav > li > a:focus {
    color: #121212;
  }
  .navbar-default .nav > li > a:hover,
  .navbar-default .nav > li > a:focus:hover {
    color: white;
  }
  .navbar-default.affix {
    background-color: white;
    border-color: rgba(34, 34, 34, 0.1);
  }
  .navbar-default.affix .navbar-header .navbar-brand {
    color: #222222;
  }
  .navbar-default.affix .navbar-header .navbar-brand:hover,
  .navbar-default.affix .navbar-header .navbar-brand:focus {
    color: #fdcc52;
  }
  .navbar-default.affix .nav > li > a,
  .navbar-default.affix .nav > li > a:focus {
    color: #222222;
  }
  .navbar-default.affix .nav > li > a:hover,
  .navbar-default.affix .nav > li > a:focus:hover {
    color: #fdcc52;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
        <div class="container" style="height:80px;">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
                </button>

<img src="http://svgshare.com/i/17J.svg" width="220" height="50"  alt="">

            </div>

            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-right" style="margin-top:20px;">
                    <li>
                        Download
                    </li>
                    <li>
                        Features
                    </li>
                    <li>
                        Contact
                    </li>
                                                              <li><button class="button-nav pull-right">Get started</button></li>

                </ul>

            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-fluid -->

    </nav></code>```

Title: Navbar Button doesn't vertically align

Body:
updated codepen

Just add the button inside navbar-right li.no need to modify your css.

example snippet

.navbar-default .navbar-header .navbar-brand {
  font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
  font-weight: 200;
  letter-spacing: 1px;
  color: #fdcc52;

}
.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
  color: #fcbd20;
}
.navbar-default .navbar-header .navbar-toggle {
  font-size: 12px;
  color: #222222;
  padding: 8px 10px;
}
.navbar-default .nav > li > a {
  font-family: Montserrat;
  font-weight:300;
  font-style:normal;
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 13px;
  color: #121212;
}
/*@media (min-width: 768px)
    .button-nav {
    display: inline-block;
    z-index: 101;
}*/

.button-nav {
  position: relative;
  bottom: 50%;
  background-color: transparent;
  font-family: Montserrat;
  font-weight: 300;
  font-style:normal;
  letter-spacing:2px;
  font-size: 13px;
  color: #121212;
  text-transform: uppercase;
  border: 1px solid #121212;
  padding: 18px 40px;
  transition: color .4s cubic-bezier(.694,.0482,.335,1),background-color .4s cubic-bezier(.694,.0482,.335,1),border .4s cubic-bezier(.694,.0482,.335,1);
  cursor:pointer;
  text-align:center;
  text-rendering: optimizeLegibility;

}

.button-nav:hover {
background-color: #1c1c1c;
  font-family: Montserrat;
  font-weight: 300;
  font-style:normal;
  letter-spacing:2px;
  font-size: 13px;
  color: white;
  text-transform: uppercase;
  border: 1px solid #1c1c1c;
  padding: 18px 40px;
  transition: color .4s cubic-bezier(.694,.0482,.335,1),background-color .4s cubic-bezier(.694,.0482,.335,1),border .4s cubic-bezier(.694,.0482,.335,1);
  cursor:pointer;
  text-align:center;
  text-rendering: optimizeLegibility;

}

.navbar-default .nav > li > a,
.navbar-default .nav > li > a:focus {
  color: #121212;
}
.navbar-default .nav > li > a:hover,
.navbar-default .nav > li > a:focus:hover {
  color: #fdcc52;
}
.navbar-default .nav > li.active > a,
.navbar-default .nav > li.active > a:focus {
  color: #fdcc52 !important;
  background-color: transparent;
}
.navbar-default .nav > li.active > a:hover,
.navbar-default .nav > li.active > a:focus:hover {
  background-color: transparent;
}
@media (min-width: 768px) {
  .navbar-default {
    background-color: transparent;
    border-color: transparent;
  }
  .navbar-default .navbar-header .navbar-brand {
    color: rgba(34, 34, 34, 0.1);
  }
  .navbar-default .navbar-header .navbar-brand:hover,
  .navbar-default .navbar-header .navbar-brand:focus {
    color: white;
  }
  .navbar-default .nav > li > a,
  .navbar-default .nav > li > a:focus {
    color: #121212;
  }
  .navbar-default .nav > li > a:hover,
  .navbar-default .nav > li > a:focus:hover {
    color: white;
  }
  .navbar-default.affix {
    background-color: white;
    border-color: rgba(34, 34, 34, 0.1);
  }
  .navbar-default.affix .navbar-header .navbar-brand {
    color: #222222;
  }
  .navbar-default.affix .navbar-header .navbar-brand:hover,
  .navbar-default.affix .navbar-header .navbar-brand:focus {
    color: #fdcc52;
  }
  .navbar-default.affix .nav > li > a,
  .navbar-default.affix .nav > li > a:focus {
    color: #222222;
  }
  .navbar-default.affix .nav > li > a:hover,
  .navbar-default.affix .nav > li > a:focus:hover {
    color: #fdcc52;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
        <div class="container" style="height:80px;">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
                </button>

            <a class="navbar-brand page-scroll" href="#page-top">
<img src="http://svgshare.com/i/17J.svg" width="220" height="50"  alt="">

                    </a>
            </div>

            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-right" style="margin-top:20px;">
                    <li>
                        <a class="page-scroll" href="#download">Download</a>
                    </li>
                    <li>
                        <a class="page-scroll" href="#features">Features</a>
                    </li>
                    <li>
                        <a class="page-scroll" href="#contact">Contact</a>
                    </li>
                                                              <li><button class="button-nav pull-right">Get started</button></li>

                </ul>

            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-fluid -->

    </nav>


问:
How to delete a Single Gmail contact using PHP
I'm using this script try to delete contacts from GMAIL but it couldn't delete.

I am refer: https://developers.google.com/glass/v1/reference/contacts/delete

My Script:

```<code>$id = '******';
$contact_mail = '********';
$contact_id = '************';

$contactXML = '<?xml version="1.0" encoding="utf-8"?>
<entry gd:etag="*">
<id>http://www.google.com/m8/feeds/contacts/'.$contact_mail.'/base/'.$contact_id.'</id>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/m8/feeds/contacts/'.$contact_mail.'/full/'.$contact_id.'"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/m8/feeds/contacts/'.$contact_mail.'/full/'.$contact_id.'"/></entry>';

    $headers = array(
    'Host: www.google.com',
    'Gdata-version: 3.0',
    'Content-length: '.strlen($contactXML),
    'Content-type: application/atom+xml',
    'Authorization: OAuth '.$access_token
    );

    $contactQuery = 'https://www.google.com/m8/feeds/contacts/default/full/'.$contact_id.'';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $contactQuery );
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $contactXML);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    $result = curl_exec($ch);
    print_r($result);
</code>```

Please find where I am wrong or guide me any other solutions.

答:
Your OAuth header is incorrect. Change Authorization: OAuth ... to Authorization: Bearer ...

Delete requests do not take content.

The documentation you link to and the API you are calling are totally different. You linked to a Glass API but you are invoking the Contacts API: https://developers.google.com/google-apps/contacts/v3

There are several other things that could be wrong (particularly with how the OAuth token was fetched) but without the actual error message you are receiving from the server it is impossible to definitively diagnose.

Body:
I'm using this script try to delete contacts from GMAIL but it couldn't delete.

I am refer: https://developers.google.com/glass/v1/reference/contacts/delete

My Script:

$id = '******';
$contact_mail = '********';
$contact_id = '************';

$contactXML = '<?xml version="1.0" encoding="utf-8"?>
<entry gd:etag="*">
<id>http://www.google.com/m8/feeds/contacts/'.$contact_mail.'/base/'.$contact_id.'</id>
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact"/>
<link rel="self" type="application/atom+xml" href="https://www.google.com/m8/feeds/contacts/'.$contact_mail.'/full/'.$contact_id.'"/>
<link rel="edit" type="application/atom+xml" href="https://www.google.com/m8/feeds/contacts/'.$contact_mail.'/full/'.$contact_id.'"/></entry>';

    $headers = array(
    'Host: www.google.com',
    'Gdata-version: 3.0',
    'Content-length: '.strlen($contactXML),
    'Content-type: application/atom+xml',
    'Authorization: OAuth '.$access_token
    );

    $contactQuery = 'https://www.google.com/m8/feeds/contacts/default/full/'.$contact_id.'';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $contactQuery );
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $contactXML);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    $result = curl_exec($ch);
    print_r($result);

Please find where I am wrong or guide me any other solutions.


问:
trouble using distinct() and filter() in django with an Oracle backend
I'm trying to get a list of all the distinct values field B can take given a value for field A.  I'm using django 1.10 and Oracle 12g.

I tried MyModel.objects.filter(fieldA='foo').values_list('fieldB').distinct() but this gives me a list with many duplicates, as if distinct() simply isn't working. I can get rid of the duplicates by converting the list to a set in python, but I'd like to rely on the database.

thanks for any help you can give

答:
You should use order_by in conjunction with distinct to get distinct values

```<code>MyModel.objects.filter(fieldA='foo').order_by('fieldB').values_list('fieldB', flat=True).distinct()
</code>```

Body:
You should use order_by in conjunction with distinct to get distinct values

MyModel.objects.filter(fieldA='foo').order_by('fieldB').values_list('fieldB', flat=True).distinct()


问:
Generate HTML from PostgreSQL function with sql sentence for input
can anybody tell me, how to write function in plpgsql, which generates html table and is called like this:

SELECT funktionName( 'Select name,
  salary*1.2  from employees  where
  salary IN (
        SELECT MIN(SALARY) from employees where salary>'||salary||') '
  ) from employees where ssn=111;

Thanks for help.

答:
You can generate XML using Postgres' XML features and transform that into HTML using XSLT. There is an example for that in the manual

But this is definitely not a recommended approach.

ContentLicense: CC BY-SA 2.5


问:
C# uwp change "Splitview.Content" in MVVM
To be honest I somehow have a hard time with MVVM.
To be more exact I have a hard time with creating/changing pages in MVVM.

This is my MainPage containing my SplitView:

```<code><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <!--#region Splitview-->
    <Grid.RowDefinitions >
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <RelativePanel >
        <Button
                FontFamily="Segoe MDL2 Assets"
                Content=""
                FontSize="30"/>
    </RelativePanel>
    <SplitView Grid.Row="1"
               x:Name="SplitView"
               DisplayMode="CompactOverlay"
               IsPaneOpen="False"
               CompactPaneLength="49"
               OpenPaneLength="160"
               PaneBackground="DarkGray"
               >
        <SplitView.Pane>
            <StackPanel>
                <ListBox SelectionMode="Single"
                         x:Name="lbHamburgerMenue"
                         Background="Gray"
                         HorizontalAlignment="Left">
                    <ListBoxItem Margin="0,5,0,2.5"
                                 Background="DarkGray">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontFamily="Segoe MDL2 Assets"
                                       Text=""
                                       FontSize="30"
                                       VerticalAlignment="Center"/>
                            <TextBlock Margin="15,0,0,0"
                                       Text="Home"
                                       FontSize="20"
                                       VerticalAlignment="Center"/>
                        </StackPanel>
                    </ListBoxItem>
                    <ListBoxItem Margin="0,2.5,0,2.5"
                                 Background="DarkGray">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontFamily="Segoe MDL2 Assets"
                                       Text=""
                                       FontSize="30"
                                       VerticalAlignment="Center"/>
                            <TextBlock Margin="15,0,0,0"
                                       Text="New Movie"
                                       FontSize="20"
                                       VerticalAlignment="Center"/>
                        </StackPanel>
                    </ListBoxItem>
                </ListBox>
            </StackPanel>
        </SplitView.Pane>
        <SplitView.Content>

            <!--#endregion-->
            <!--#region  content area-->
            <Grid Grid.Row="1" Grid.Column="1" >
            </Grid>
        </SplitView.Content>
    </SplitView>
</Grid>
</code>```

For the Content I am kinda lost.
How do I get a View displayed when another ListBox.Item gets selected?
I know I need a Frame and inside that Frame the View has to be, but I would like some help in that regard because I am stuck here. (or with views in MVVM in general).

答:
Yes, you are correct on your first assumption. You need to replace your GridView in the SplitView.Content section with a Frame. Then when you want to navigate to a particular view, you call Frame.Navigate.

For MVVM to keep your main page ViewModel from having intimate knowledge of your views, you can define a NavigationService that encapsulates page and view structure and the view types.

Here is a good article about the basics of MVVM and building a NavigationService: https://msdn.microsoft.com/en-us/magazine/jj651572.aspx (go to 'Setting up Navigation' section).

Another great description from StackOverflow: Navigating to a new page from the View Model in Windows Phone 8.1 universal app.

Body:
To be honest I somehow have a hard time with MVVM.
To be more exact I have a hard time with creating/changing pages in MVVM.

This is my MainPage containing my SplitView:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid.RowDefinitions >
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <RelativePanel >
        <Button
                FontFamily="Segoe MDL2 Assets"
                Content=""
                FontSize="30"/>
    </RelativePanel>
    <SplitView Grid.Row="1"
               x:Name="SplitView"
               DisplayMode="CompactOverlay"
               IsPaneOpen="False"
               CompactPaneLength="49"
               OpenPaneLength="160"
               PaneBackground="DarkGray"
               >
        <SplitView.Pane>
            <StackPanel>
                <ListBox SelectionMode="Single"
                         x:Name="lbHamburgerMenue"
                         Background="Gray"
                         HorizontalAlignment="Left">
                    <ListBoxItem Margin="0,5,0,2.5"
                                 Background="DarkGray">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontFamily="Segoe MDL2 Assets"
                                       Text=""
                                       FontSize="30"
                                       VerticalAlignment="Center"/>
                            <TextBlock Margin="15,0,0,0"
                                       Text="Home"
                                       FontSize="20"
                                       VerticalAlignment="Center"/>
                        </StackPanel>
                    </ListBoxItem>
                    <ListBoxItem Margin="0,2.5,0,2.5"
                                 Background="DarkGray">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontFamily="Segoe MDL2 Assets"
                                       Text=""
                                       FontSize="30"
                                       VerticalAlignment="Center"/>
                            <TextBlock Margin="15,0,0,0"
                                       Text="New Movie"
                                       FontSize="20"
                                       VerticalAlignment="Center"/>
                        </StackPanel>
                    </ListBoxItem>
                </ListBox>
            </StackPanel>
        </SplitView.Pane>
        <SplitView.Content>

            <Grid Grid.Row="1" Grid.Column="1" >
            </Grid>
        </SplitView.Content>
    </SplitView>
</Grid>

For the Content I am kinda lost.
How do I get a View displayed when another ListBox.Item gets selected?
I know I need a Frame and inside that Frame the View has to be, but I would like some help in that regard because I am stuck here. (or with views in MVVM in general).


问:
classloading in WildFly
Consider following structure of jboss-deployment-structure.xml inside META-INF of ear

```<code><!-- Make sub deployments not isolated so they can see each others classes without a Class-Path entry (default is true) -->
<ear-subdeployments-isolated>false</ear-subdeployments-isolated>

<deployment>
    <!-- Exclusions allow you to prevent the server from automatically adding some dependencies -->
    <exclusions>
        <module name="org.apache.xerces" />
    </exclusions>
</deployment>

<sub-deployment name="mySubDeployment.war">
    <exclusions>
        <module name="org.apache.log4j" />
    </exclusions>
    <dependencies>
        <system>
            <paths>
                <path name="com/sun/org/apache/xerces/internal/dom"/>
                <path name="com/sun/org/apache/xerces/internal/xni"/>
                <path name="com/sun/org/apache/xerces/internal/jaxp"/>
            </paths>
        </system>
    </dependencies>
</sub-deployment>
</code>```

Given that, I have excluded default org.apache.xerces module from deployment (line#11) and deployed custom xercesImpl.jar in APP-INF/lib folder or ear. Also I have added path dependencies for mySubDeployment.war sub-deployment.

From where classes of xerces will be loaded for mySubDeployment.war? From the default com.apache.xerces module of WildFly or custom jar deployed in APP-INF/lib?

What is the exact meaning of adding path dependencies in sub-deployment? Will that ignore the exclusions (i.e. org.apache.xerces here) under main deployment?

答:
You shouldn't really need those paths. You'll also have to exclude xerces for each sub-deployment.

Also the APP-INF directory is not a standard Java EE directory. You'll need to put libraries in the /lib directory of your EAR.

Title: classloading in WildFly

Body:
Consider following structure of jboss-deployment-structure.xml inside META-INF of ear

<ear-subdeployments-isolated>false</ear-subdeployments-isolated>

<deployment>

    <exclusions>
        <module name="org.apache.xerces" />
    </exclusions>
</deployment>

    <exclusions>
        <module name="org.apache.log4j" />
    </exclusions>
    <dependencies>
        <system>
            <paths>
                <path name="com/sun/org/apache/xerces/internal/dom"/>
                <path name="com/sun/org/apache/xerces/internal/xni"/>
                <path name="com/sun/org/apache/xerces/internal/jaxp"/>
            </paths>
        </system>
    </dependencies>

Given that, I have excluded default org.apache.xerces module from deployment (line#11) and deployed custom xercesImpl.jar in APP-INF/lib folder or ear. Also I have added path dependencies for mySubDeployment.war sub-deployment.

From where classes of xerces will be loaded for mySubDeployment.war? From the default com.apache.xerces module of WildFly or custom jar deployed in APP-INF/lib?

What is the exact meaning of adding path dependencies in sub-deployment? Will that ignore the exclusions (i.e. org.apache.xerces here) under main deployment?


问:
how to setup Karma with Ui5
I have a question related to karma and ui5.
Current situation is as follows:

I use karma-openui5 and load ui5 via bower. Karma-openui5 simply adds some bootstrap information and the core-file itself:

```<code>files.unshift({pattern: ui5path, included: true, watched: false, served: true});
</code>```

which leads to this head entry:

```<code><script type="text/javascript" src="/base/bower_components/openui5-sap.ui.core/resources/sap-ui-core.js" crossorigin="anonymous"></script>
</code>```

Ui5 is designed to load everything else related to the core-file but is served by sap in different bower packages this means, request is:

http://localhost:9876/base/bower_components/openui5-sap.ui.core/resources/sap/m/library-preload.js

but it's actually located under

http://localhost:9876/base/bower_components/openui5-sap.m/resources/sap/m/library-preload.js

I could overcome this problem with proxy entries. But i can`t include the .css files which one are in a separate bower package. I can't see a way to proxy only */**/.css requests to another directory. Therefore this way just doesn't work well.

Openui5 has already some middleware (connect-openui5) to resolve this problems and server everything as expected  under localhost:XXXX/resources/.

How and can i add custom script tags in karma? like:

```<code><script type="text/javascript" src="resources/sap-ui-core.js"></script>
</code>```

How can i add a middleware (connect-openui5) to handle all requests to /resources/**/*?

答:
The solution was to use the connect middleware from sap, started with grunt and proxy to this.

I packed everything in a yeoman generator, if anyone is interested in the setup.

https://www.npmjs.com/package/generator-ui5

Title: how to setup Karma with Ui5

Body:
I have a question related to karma and ui5.
Current situation is as follows:

I use karma-openui5 and load ui5 via bower. Karma-openui5 simply adds some bootstrap information and the core-file itself:

files.unshift({pattern: ui5path, included: true, watched: false, served: true});

which leads to this head entry:

Ui5 is designed to load everything else related to the core-file but is served by sap in different bower packages this means, request is:

http://localhost:9876/base/bower_components/openui5-sap.ui.core/resources/sap/m/library-preload.js

but it's actually located under

http://localhost:9876/base/bower_components/openui5-sap.m/resources/sap/m/library-preload.js

I could overcome this problem with proxy entries. But i can`t include the .css files which one are in a separate bower package. I can't see a way to proxy only */**/.css requests to another directory. Therefore this way just doesn't work well.

Openui5 has already some middleware (connect-openui5) to resolve this problems and server everything as expected  under localhost:XXXX/resources/.

How and can i add custom script tags in karma? like:

How can i add a middleware (connect-openui5) to handle all requests to /resources/**/*?


问:
Strech image to fill the transparent background using Magick.NET
I have an image (attached).

I want the image to be stretched out to cover the yellow area.

I am using c#, magick.net

What will be the best approach?

答:
I propose the following approach:

read input image saving original size

remove the transparent* area using trim

stretch the (now smaller) image to the original size

*If the yellow area in your sample image is actually transparent you can leave fuzz = 0 in the following code, otherwise you'll have to adjust the value to be sure to remove all the unwanted area.

```<code>string srcImageFullPath = "c:\input.png";
int fuzz = 0;
string destImageFullPath = "c:\output.png";

// Read image from file
using (MagickImage image = new MagickImage(srcImageFullPath))
{
    //save height/width of the original image
    int height = image.Page.Height;
    int width = image.Page.Width;

    //set fuzz percentage
    image.ColorFuzz = new ImageMagick.Percentage(fuzz);

    //trim borders
    image.Trim();

    //resize image to original size
    MagickGeometry size = new MagickGeometry(width, height);
    size.IgnoreAspectRatio = true;
    image.Resize(size);

    // Save the result
    image.Write(destImageFullPath);
}
</code>```

In the following picture you can see the original image on the left, and the image after resizing on the right:

Notes

Trim removes any border that has the same color of the pixels in the corner of you image (see here for the details)

Since the yellow border in your sample image is not made of a single color you can use Fuzz to remove "similar" colors (more info here). As said before if your border is transparent just leave fuzz = 0

Body:
I propose the following approach:

read input image saving original size

remove the transparent* area using trim

stretch the (now smaller) image to the original size

*If the yellow area in your sample image is actually transparent you can leave fuzz = 0 in the following code, otherwise you'll have to adjust the value to be sure to remove all the unwanted area.

string srcImageFullPath = "c:\input.png";
int fuzz = 0;
string destImageFullPath = "c:\output.png";

// Read image from file
using (MagickImage image = new MagickImage(srcImageFullPath))
{
    //save height/width of the original image
    int height = image.Page.Height;
    int width = image.Page.Width;

    //set fuzz percentage
    image.ColorFuzz = new ImageMagick.Percentage(fuzz);

    //trim borders
    image.Trim();

    //resize image to original size
    MagickGeometry size = new MagickGeometry(width, height);
    size.IgnoreAspectRatio = true;
    image.Resize(size);

    // Save the result
    image.Write(destImageFullPath);
}

In the following picture you can see the original image on the left, and the image after resizing on the right:

Notes

Trim removes any border that has the same color of the pixels in the corner of you image (see here for the details)

Since the yellow border in your sample image is not made of a single color you can use Fuzz to remove "similar" colors (more info here). As said before if your border is transparent just leave fuzz = 0


问:
I can't kill MyApp.vshost.exe
I've managed to get myself in a state where I've no instances of devenv running, but still a MyApp.vshost.exe in the background (no visible windows or consoles).

I've tried TaskManager, ProcessExplorer and command line (taskkill /F /IM MyApp.vshost.exe), none of them complain, the command line even says 'PID 5824 stopped', but it's still there.

I know I can reboot, but I'd rather get to the bottom of this.

It doesn't look like it's this issue (http://support.microsoft.com/kb/982551), because I can reboot no problem (just have in fact, so won't be able to provide any further diagnostics, sorry).

EDIT

This is how I got into this pickle:

答:
It seems to be the normal behaviour for this task. When you kill it the task is restarted.
So i advice you to close Visual Studio, that closes the *.vshost.exe task.</p>

Title: I can't kill MyApp.vshost.exe


问:
errors with Elif expected indented block
I'm trying to create a menu for my application, the menu has 4 options and each of these options should return with the correct information when the user has entered the chosen value. i keep getting an error with the Elif statements.
I am a newbie so please understand where am coming from.
much appreciation.

when i indent the while ans: i will receive an error says invalid syntax after indenting the elif ans==2.

elif ans==2 <--- this error keeps saying indention block error or syntex invalid when i indent it.

def print_menu(self,car):

            print    ("1.Search by platenumber")
            print    ("2.Search by price ")
            print    ("3.Delete 3")
            print    ("4.Exit 4")

loop=True

    while loop:
        print_menu()
        ans==input("Please choose from the list")

```<code>    if ans==1:
        print("These are the cars within this platenumber")
    return platenumber_

    while ans:
        if ans==2:
        elif ans==2:
            print("These are the prices of the cars")
    return price_

    elif ans==3:
        print("Delete the cars ")
    return delete_

    elif  ans==4:
    return Exit_

            loop=False

    else:
        raw_input("please choose a correct option")
</code>```

答:
You have a while loop without a body. Generally speaking, if there is an indentation error message and the error is not on the line mentioned, it's something closely above it.

```<code>loop=True
while loop:
    print_menu()
    ans = int(input("Please choose from the list"))

    if ans==1:
        print("These are the cars within this platenumber")
        # return some valid information about plate numbers

    elif ans==2:
         print("These are the prices of the cars")
         # return some valid information about pricing

    elif ans==3:
        print("Delete the cars ")
        # Perform car deletion action and return

    elif  ans==4:
        # I am assuming this is the exit option? in which case
        # return without doing anything

    else:
        # In this case they have not chosen a valid option. Send
        # A message to the user, and do nothing. The while loop will run again.
        print("please choose a correct option")
</code>```

Also, your code is a bit confusing to me. It looks like you're going to return car_ no matter what, which means your loop will only execute once. Also, = is assignment and == is equality. Be careful.

Body:
I'm trying to create a menu for my application, the menu has 4 options and each of these options should return with the correct information when the user has entered the chosen value. i keep getting an error with the Elif statements.
I am a newbie so please understand where am coming from.
much appreciation.

when i indent the while ans: i will receive an error says invalid syntax after indenting the elif ans==2.

elif ans==2 <--- this error keeps saying indention block error or syntex invalid when i indent it.

def print_menu(self,car):

            print    ("1.Search by platenumber")
            print    ("2.Search by price ")
            print    ("3.Delete 3")
            print    ("4.Exit 4")

loop=True

    while loop:
        print_menu()
        ans==input("Please choose from the list")

    if ans==1:
        print("These are the cars within this platenumber")
    return platenumber_

    while ans:
        if ans==2:
        elif ans==2:
            print("These are the prices of the cars")
    return price_

    elif ans==3:
        print("Delete the cars ")
    return delete_

    elif  ans==4:
    return Exit_

            loop=False

    else:
        raw_input("please choose a correct option")

Body:
You have a while loop without a body. Generally speaking, if there is an indentation error message and the error is not on the line mentioned, it's something closely above it.

loop=True
while loop:
    print_menu()
    ans = int(input("Please choose from the list"))

    if ans==1:
        print("These are the cars within this platenumber")
        # return some valid information about plate numbers

    elif ans==2:
         print("These are the prices of the cars")
         # return some valid information about pricing

    elif ans==3:
        print("Delete the cars ")
        # Perform car deletion action and return

    elif  ans==4:
        # I am assuming this is the exit option? in which case
        # return without doing anything

    else:
        # In this case they have not chosen a valid option. Send
        # A message to the user, and do nothing. The while loop will run again.
        print("please choose a correct option")

Also, your code is a bit confusing to me. It looks like you're going to return car_ no matter what, which means your loop will only execute once. Also, = is assignment and == is equality. Be careful.


问:
Can vim monitor realtime changes to a file
My question is similar to this how to monitor a text file in realtime
but I want to do it in vim. I know I can read an opened file use tail -f sample.xml file, and when new content is written to the file, it'll also write the new content to my screen. Can I have vim automatically fill the new data when a file is updated?

答:
There is a plugin also:

https://github.com/djoshea/vim-autoread

This was the only way I could make this work on OSX.

LastEditorDisplayName: anon


问:
SqlException: Deadlock
I have these two exceptions generated when I try to get data from SQL database in C#:

System.Data.SqlClient.SqlException:  Transaction (Process ID 97) was deadlocked on lock resources with another process and has been chosen as the deadlock victim.

OR

System.Data.SqlClient.SqlException: Transaction (Process ID 62) was deadlocked on lock resources with another process and has been chosen as the deadlock victim.

OR

System.Data.SqlClient.SqlException: Transaction (Process ID 54) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

this is the code:

```<code> using (SqlConnection con = new SqlConnection(datasource))
 {
    SqlCommand cmd = new SqlCommand("Select * from MyTable Where ID='1' ", con);
    cmd.CommandTimeout = 300;
    con.Open();
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adapter.Fill(ds);
    con.Close();
    return ds.Tables[0];
 }
</code>```

These happened every time.

Any ideas on how these can be resolved?

答: Basically, the SQL server concurrency model makes it so you can never avoid this exception (eg. completely unrelated transaction might block eachother if they happen to lock the same index page or something). The best you can do is keep your transactions short to reduce the likelyhood, and if you get the exception, do what it says and retry the transaction.</p>

ContentLicense: CC BY-SA 4.0

Title: SqlException: Deadlock

Body:
I have these two exceptions generated when I try to get data from SQL database in C#:

System.Data.SqlClient.SqlException:  Transaction (Process ID 97) was deadlocked on lock resources with another process and has been chosen as the deadlock victim.

OR

System.Data.SqlClient.SqlException: Transaction (Process ID 62) was deadlocked on lock resources with another process and has been chosen as the deadlock victim.

OR

System.Data.SqlClient.SqlException: Transaction (Process ID 54) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

this is the code:

 using (SqlConnection con = new SqlConnection(datasource))
 {
    SqlCommand cmd = new SqlCommand("Select * from MyTable Where ID='1' ", con);
    cmd.CommandTimeout = 300;
    con.Open();
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adapter.Fill(ds);
    con.Close();
    return ds.Tables[0];
 }

These happened every time.

Any ideas on how these can be resolved?


问:
Composer update without versioning
I'm developing a composer package used in another application. The package resides in a separate repository. Every now and then when I fix something in the package during the development, I have to increment its version by assigning a git tag so that the application where the package is used can download the latest version of it. I end up having lots of tags.

Is there a more appropriate way allowing to update (the composer update cmd) the package under development in the app where it's used without using thousands of tags?

Say I change the package, commit and push the changes to the repo. When I do composer update in the app's scope, it updates the package, although it's version is not incremented with the last change, there are only new commits in the package's repo.

答:
What is bad with having a lot of tags?

You can depend on branches. Composer would clone the repository and checkout the latest commit of that branch every time you run update. I highly recommend to depend on a branch using a version alias: "your/lib": "dev-feature as 2.2.0" - this will fulfill dependencies of other libs that require this one in a certain version, and it makes it clearer which version this branch is based on.

Title: Composer update without versioning


问:
How to verify JWT id_token produced by MS Azure AD?
I have an angularjs SPA web app which uses ADAL-JS (and adal-angular).
It's set up to authenticate vs our corporate AD in MS Azure. The log-in flow seems to work correctly, and the SPA receives an id_token.

Next, when the user clicks a button, the SPA makes a request to a REST API I am hosting on AWS API Gateway. I am passing the id_token on the Authorization: Bearer <id_token> header.
The API Gateway receives the header as intended, and now has to determine if the given token is good or not to either allow or deny access.

I have a sample token, and it parses correctly on https://jwt.io/ but I have so far failed to find the Public Key or Certificate I should use to verify the signature. I have looked in:

https://login.microsoftonline.com/{tenantid}/federationmetadata/2007-06/federationmetadata.xml

https://login.microsoftonline.com/{tenantId}/discovery/keys

https://login.microsoftonline.com/common/.well-known/openid-configuration (to get the jwks_uri)

https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration

https://login.microsoftonline.com/common/discovery/keys

https://login.microsoftonline.com/common/discovery/v2.0/keys

I think I should use the value of the x5c property of the key in https://login.microsoftonline.com/common/discovery/keys matching the kid and x5t properties from the JWT id_token (currently a3QN0BZS7s4nN-BdrjbF0Y_LdMM, which leads to an x5c value starting with "MIIDBTCCAe2gAwIBAgIQY..." ). However, the https://jwt.io/ page reports "Invalid Signature" (I also tried wrapping the key value with "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----").

Also, is there a (possibly python) library that can facilitate the verification of a given id_token as in the case above (so that I won't have to go grab the signing key on the fly myself?)... The best I could find (ADAL for python) doesn't seem to provide this feature?

答:
The best solution I could put together so far:

Grab the certificate (the first value in the x5c property array) from either https://login.microsoftonline.com/common/discovery/keys or https://login.microsoftonline.com/common/discovery/v2.0/keys, matching kid and x5t from the id_token.

Wrap the certificate in -----BEGIN CERTIFICATE-----\n and \n-----END CERTIFICATE----- (the newlines seem to matter), and use the result as Public Key (in conjunction with the id_token, on https://jwt.io/ ).

Of course, your actual use case will likely be to have some program validate the incoming JWT id_tokens, so your goal won't be to simply get the token to validate through the web UI on https://jwt.io/.

For instance, in python, I need something like this:

```<code>#!/usr/bin/env python

import jwt
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend

PEMSTART = "-----BEGIN CERTIFICATE-----\n"
PEMEND = "\n-----END CERTIFICATE-----\n"

mspubkey = "The value from the x5c property"
IDTOKEN = "the id_token to be validated"
tenant_id = "your tenant id"

cert_str = PEMSTART + mspubkey + PEMEND
cert_obj = load_pem_x509_certificate(cert_str, default_backend())
public_key = cert_obj.public_key()

decoded = jwt.decode(IDTOKEN, public_key, algorithms=['RS256'], audience=tenant_id)
if decoded:
    print "Decoded!"
else:
    print "Could not decode token."
</code>```

For a list of JWT libraries in various languages, see the JWT Site.
I'm using pyjwt, and its cryptography dependency (which has binary dependencies, so needs to be built and packaged for the target OS).

And then, of course, you can verify additional details such as the claims as recommended here.

Body:
The best solution I could put together so far:

Grab the certificate (the first value in the x5c property array) from either https://login.microsoftonline.com/common/discovery/keys or https://login.microsoftonline.com/common/discovery/v2.0/keys, matching kid and x5t from the id_token.

Wrap the certificate in -----BEGIN CERTIFICATE-----\n and \n-----END CERTIFICATE----- (the newlines seem to matter), and use the result as Public Key (in conjunction with the id_token, on https://jwt.io/ ).

Of course, your actual use case will likely be to have some program validate the incoming JWT id_tokens, so your goal won't be to simply get the token to validate through the web UI on https://jwt.io/.

For instance, in python, I need something like this:

#!/usr/bin/env python

import jwt
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend

PEMSTART = "-----BEGIN CERTIFICATE-----\n"
PEMEND = "\n-----END CERTIFICATE-----\n"

mspubkey = "The value from the x5c property"
IDTOKEN = "the id_token to be validated"
tenant_id = "your tenant id"

cert_str = PEMSTART + mspubkey + PEMEND
cert_obj = load_pem_x509_certificate(cert_str, default_backend())
public_key = cert_obj.public_key()

decoded = jwt.decode(IDTOKEN, public_key, algorithms=['RS256'], audience=tenant_id)
if decoded:
    print "Decoded!"
else:
    print "Could not decode token."

For a list of JWT libraries in various languages, see the JWT Site.
I'm using pyjwt, and its cryptography dependency (which has binary dependencies, so needs to be built and packaged for the target OS).

And then, of course, you can verify additional details such as the claims as recommended here.


问:
Replace white space with a single space
I am starting from this example in JavaScript, and trying to do the same performance test.

I have

```<code>$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$RegEx1 = '/ +/g'
$RegEx2 = '/  +/g'
$RegEx3 = '/ {2,}/g'
$RegEx4 = '/\s\s+/g'
$RegEx5 = '/ +(?= )/g'

Measure-Command {
    $newString = $string -replace $RegEx1, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx2, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx3, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx4, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx5, $null
}
Write-Host "$newString"
</code>```

and I am getting very different times, but all return nothing, which isn't exactly useful. Where am I going wrong translating Javascript RegEx to PowerShell Regex?
FWIW, I want to keep things simple, so spaces only, no need to also replace CR and the like. The data is pretty simple, the formatting is just junk.

答:
In PowerShell (by extension I think .Net in general) your modifiers/options are supposed to be at the beginning of the string in a construct like (?smi)/ + for example.

Replace white space with a single space

```<code>$newString = $string -replace "\s+", " "
</code>```

That should do it just fine if you want simplicity.

Consider this example using your regex string to show what you would be trying to match against.

```<code>"this is only a /    /g" -replace '/ +/g', "test"
this is only a test
</code>```

A pair of literal forward slashes with at least one space separating them followed by the literal g.

Title: Replace white space with a single space

Body:
I am starting from this example in JavaScript, and trying to do the same performance test.

I have

$string = 'RAM Statistics:     5954 /     8174       743=InUse      746=Peak'
$RegEx1 = '/ +/g'
$RegEx2 = '/  +/g'
$RegEx3 = '/ {2,}/g'
$RegEx4 = '/\s\s+/g'
$RegEx5 = '/ +(?= )/g'

Measure-Command {
    $newString = $string -replace $RegEx1, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx2, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx3, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx4, $null
}
Write-Host "$newString"
Measure-Command {
    $newString = $string -replace $RegEx5, $null
}
Write-Host "$newString"

and I am getting very different times, but all return nothing, which isn't exactly useful. Where am I going wrong translating Javascript RegEx to PowerShell Regex?
FWIW, I want to keep things simple, so spaces only, no need to also replace CR and the like. The data is pretty simple, the formatting is just junk.

Body:
In PowerShell (by extension I think .Net in general) your modifiers/options are supposed to be at the beginning of the string in a construct like (?smi)/ + for example.

Replace white space with a single space

$newString = $string -replace "\s+", " "

That should do it just fine if you want simplicity.

Consider this example using your regex string to show what you would be trying to match against.

"this is only a /    /g" -replace '/ +/g', "test"
this is only a test

A pair of literal forward slashes with at least one space separating them followed by the literal g.


问:
How to obfuscate Python code effectively?
I am looking for how to hide my Python source code.

```<code>print "Hello World!"
</code>```

How can I encode this example so that it isn't human-readable?  I've been told to use base64 but I'm not sure how.

答:
Try pasting your hello world python code to the following site:

http://enscryption.com/encrypt-and-obfuscate-scripts.html

It will produce a complex encrypted and obfuscated, but fully functional  script for you.  See if you can crack the script and reveal the actual code.  Or see if the level of complexity it provides satisfies your need for peace of mind.

The encrypted script that is produced for you through this site should work on any Unix system that has python installed.

If you would like to encrypt another way, I strongly suggest you write your own encryption/obfuscation algorithm (if security is that important to you). That way, no one can figure out how it works but you.  But, for this to really work, you have to spend a tremendous amount of time on it to ensure there aren't any loopholes that someone who has a lot of time on their hands can exploit.  And make sure you use tools that are already natural to the Unix system... i.e. openssl or base64. That way, your encrypted script is more portable.

Body:
I am looking for how to hide my Python source code.

print "Hello World!"

How can I encode this example so that it isn't human-readable?  I've been told to use base64 but I'm not sure how.


问:
C - pointer to pointer array
I am learning C and as I got stuck at the pointer chapter. Particullary at the pointer to pointer ( **p ) part, used with processing 2 dimensional arrays.

The following function generates a 2 dimmensional array with all its elements equal to 0 .

```<code>double** example(int rows, int cols){
    static double tr[rows][cols];
    for(int i = 0; i < rows; i++)
       for(int j = 0; j < cols; j++)
            tr[j][i] = 0;
    return tr;
    }
int main(void){

    double **tr;
    int m = 2 ;
    int n = 2 ;

    tr = transpose(m, n);
    return 0;}
</code>```

Is the tr returned by the function a "double pointer" to the first element of the tr array ? Or to its value ? Also, now (after the the function was called) how do I  access the elements of the array at the part of memory where **tr points to ?

Can someone explain me how this all works ? Or suggest me an article or a chapter in a book that does ?

答:
The presented program is totally incorrect. A variable length array may not have static storage duration/ According to the C Standard (6.7.6.2 Array declarators)

2 If an identiﬁer is declared as having a variably modiﬁed type, it
  shall be an ordinary identiﬁer (as deﬁned in 6.2.3), have no linkage,
  and have either block scope or function prototype scope. If an
  identiﬁer is declared to be an object with static or thread storage
  duration, it shall not have a variable length array type.

Moreover the pointer types double ** and double ( * )[cols] (to which the array provided that it was declared correctly is converted in expressions) are not compatible. So the function is wrong.

```<code>double** example(int rows, int cols){
    static double tr[rows][cols];
    for(int i = 0; i < rows; i++)
       for(int j = 0; j < cols; j++)
            tr[j][i] = 0;
    return tr;
    }
</code>```

Here is a demonstrative program that shows how to deal with variable length arrays.

```<code>#include <stdio.h>

void init( size_t rows, size_t cols, double a[rows][cols] )
//  or
//  void init( size_t rows, size_t cols, double a[][cols] )
//  or
//  void init( size_t rows, size_t cols, double ( *a )[cols] )
{
    for ( size_t i = 0; i < rows; i++ )
    {
        for ( size_t j = 0; j < cols; j++ ) a[i][j] = 0.0;
    }
}

void display( size_t rows, size_t cols, double a[rows][cols] )
//  or
//  void display( size_t rows, size_t cols, double a[][cols] )
//  or
//  void display( size_t rows, size_t cols, double ( *a )[cols] )
{
    for ( size_t i = 0; i < rows; i++ )
    {
        for ( size_t j = 0; j < cols; j++ ) printf( "%lf", a[i][j] );
        putchar( '\n' );
    }
}

int main(void)
{
    while ( 1 )
    {
        size_t m, n;

        printf( "Enter numbers of rows and columns (0 - exit): " );

        if ( scanf( "%zu%zu", &m, &n ) != 2 || m == 0 || n == 0 ) break;

        double a[m][n];

        putchar( '\n' );

        init( m, n, a );
        display( m, n, a );

        putchar( '\n' );
    }

    return 0;
}
</code>```

Its output might look like

```<code>Enter numbers of rows and columns (0 - exit): 2 3

0.0000000.0000000.000000
0.0000000.0000000.000000

Enter numbers of rows and columns (0 - exit): 3 4

0.0000000.0000000.0000000.000000
0.0000000.0000000.0000000.000000
0.0000000.0000000.0000000.000000

Enter numbers of rows and columns (0 - exit): 0 0
</code>```

Within the both functions the third parameter is adjusted to the pointer type double ( *a )[cols]. It is not the same as double **a.

If you will write for example the following program

```<code>#include <stdio.h>

#define M   2
#define N   3

int main(void)
{
    int a[M][N] =
    {
        { 1, 2, 3 },
        { 4, 5, 6 }
    };

    int **p = ( int ** )a;

    p[0][0] = 10;

    return 0;
}
</code>```

then it will have undefined behavior because p[0] considers the value stored in the element a[0][0] (or the combined value stored in elements a[0][0] and a[0][1] depending on the size of the pointer) that is the value 1 as a pointer value and try to access the memory at address 1 in the expression p[0][0].

Title: C - pointer to pointer array

Body:
I am learning C and as I got stuck at the pointer chapter. Particullary at the pointer to pointer ( **p ) part, used with processing 2 dimensional arrays.

The following function generates a 2 dimmensional array with all its elements equal to 0 .

double** example(int rows, int cols){
    static double tr[rows][cols];
    for(int i = 0; i < rows; i++)
       for(int j = 0; j < cols; j++)
            tr[j][i] = 0;
    return tr;
    }
int main(void){

    double **tr;
    int m = 2 ;
    int n = 2 ;

    tr = transpose(m, n);
    return 0;}

Is the tr returned by the function a "double pointer" to the first element of the tr array ? Or to its value ? Also, now (after the the function was called) how do I  access the elements of the array at the part of memory where **tr points to ?

Can someone explain me how this all works ? Or suggest me an article or a chapter in a book that does ?

Body:
The presented program is totally incorrect. A variable length array may not have static storage duration/ According to the C Standard (6.7.6.2 Array declarators)

2 If an identiﬁer is declared as having a variably modiﬁed type, it
  shall be an ordinary identiﬁer (as deﬁned in 6.2.3), have no linkage,
  and have either block scope or function prototype scope. If an
  identiﬁer is declared to be an object with static or thread storage
  duration, it shall not have a variable length array type.

Moreover the pointer types double ** and double ( * )[cols] (to which the array provided that it was declared correctly is converted in expressions) are not compatible. So the function is wrong.

double** example(int rows, int cols){
    static double tr[rows][cols];
    for(int i = 0; i < rows; i++)
       for(int j = 0; j < cols; j++)
            tr[j][i] = 0;
    return tr;
    }

Here is a demonstrative program that shows how to deal with variable length arrays.

#include <stdio.h>

void init( size_t rows, size_t cols, double a[rows][cols] )
//  or
//  void init( size_t rows, size_t cols, double a[][cols] )
//  or
//  void init( size_t rows, size_t cols, double ( *a )[cols] )
{
    for ( size_t i = 0; i < rows; i++ )
    {
        for ( size_t j = 0; j < cols; j++ ) a[i][j] = 0.0;
    }
}

void display( size_t rows, size_t cols, double a[rows][cols] )
//  or
//  void display( size_t rows, size_t cols, double a[][cols] )
//  or
//  void display( size_t rows, size_t cols, double ( *a )[cols] )
{
    for ( size_t i = 0; i < rows; i++ )
    {
        for ( size_t j = 0; j < cols; j++ ) printf( "%lf", a[i][j] );
        putchar( '\n' );
    }
}

int main(void)
{
    while ( 1 )
    {
        size_t m, n;

        printf( "Enter numbers of rows and columns (0 - exit): " );

        if ( scanf( "%zu%zu", &m, &n ) != 2 || m == 0 || n == 0 ) break;

        double a[m][n];

        putchar( '\n' );

        init( m, n, a );
        display( m, n, a );

        putchar( '\n' );
    }

    return 0;
}

Its output might look like

Enter numbers of rows and columns (0 - exit): 2 3

0.0000000.0000000.000000
0.0000000.0000000.000000

Enter numbers of rows and columns (0 - exit): 3 4

0.0000000.0000000.0000000.000000
0.0000000.0000000.0000000.000000
0.0000000.0000000.0000000.000000

Enter numbers of rows and columns (0 - exit): 0 0

Within the both functions the third parameter is adjusted to the pointer type double ( *a )[cols]. It is not the same as double **a.

If you will write for example the following program

#include <stdio.h>

#define M   2
#define N   3

int main(void)
{
    int a[M][N] =
    {
        { 1, 2, 3 },
        { 4, 5, 6 }
    };

    int **p = ( int ** )a;

    p[0][0] = 10;

    return 0;
}

then it will have undefined behavior because p[0] considers the value stored in the element a[0][0] (or the combined value stored in elements a[0][0] and a[0][1] depending on the size of the pointer) that is the value 1 as a pointer value and try to access the memory at address 1 in the expression p[0][0].


问:
How to mimic a "callback with promise" function parameter in rxjs?
I'm an absolute rxjs beginner. For me to start learning to think in observables, I need to translate concepts through code examples. I feel like if I can see the code for this, I can start to do this on my own with other concepts.

I do NOT want to CONVERT a promise to an observable, I want to make a new implementation using Observable that can behave like a promise. How would I re-write the following using Observables?

```<code> constructor(){
    let makeMessage2 = function(){
        return new Promise(resolve, reject){
           setTimeout(()=>{
                  var r = Math.random();
                  resolve("message two plus random value: " + r );
           }, 1000);
        }
    }
    this.logMessageAndResultOfCallback("message one!", makeMessage2);
}
private sideEffect1:string = "";
private sideEffect2:string = "";

logMessageAndResultOfCallback( message1:string, callback:Function ){
    console.log(message1);
    this.sideEffect1 = message1;

    callback().then((message2)=>{
          console.log(message2);
          this.sideEffect2 = message2;
    }
}
</code>```

I guess the part I don't understand is how to define the "callback" function, how to invoke it. I understand I would wait for the complete or emit handlers, like makeMessage2().subscribe(message2 => console.log(message2)); but I don't have any clue how to define makeMessage2.

This may be totally clueless question, but I've read about 10 different intros to rxjs and this hasn't quite clicked. I just need to map this scenario to observable pattern and I think I can understand it.

Basically, I want to define an observable function myObs() that does not "execute immediately" but "executes" whenever the someMethod(message:string,obs:Observable) is executed. When myObs is executed, it should do something ansynchronously within it (like get the result of a HTTP request) then set the next value, then fire a complete() so my observer defined in someMethod can handle the complete and do something with the result.

Edit: I'm not concerned with the timer or native equivalents in rxjs, this is just to simulate any async action, like getting data from the server.

答:
I solved it with help from this guide.</p>

```<code>import {Observable} from 'rxjs';
var makeMessage2 = Observable.create(observer => {
  // Yield a single value and complete
  setTimeout(function(){
     let r = Math.random();
     observer.next("message two plus random value: " + r );
     observer.complete();
  }, 1000);
  return () => console.log('disposed')
});
logMessageAndResultOfCallback( "some message one", makeMessage2);

logMessageAndResultOfCallback( message1:string, callback:Observeable ){
    console.log(message1);
    this.sideEffect1 = message1;

    var subscription = callback.subscribe(
       (value)=>{this.sideEffect2 = value;},
       (e) =>{ console.log('onError: %s', e)},
       () => {console.log(this.sideEffect2);});
      subscription.dispose();
}
</code>```

Body:
I'm an absolute rxjs beginner. For me to start learning to think in observables, I need to translate concepts through code examples. I feel like if I can see the code for this, I can start to do this on my own with other concepts.

I do NOT want to CONVERT a promise to an observable, I want to make a new implementation using Observable that can behave like a promise. How would I re-write the following using Observables?

 constructor(){
    let makeMessage2 = function(){
        return new Promise(resolve, reject){
           setTimeout(()=>{
                  var r = Math.random();
                  resolve("message two plus random value: " + r );
           }, 1000);
        }
    }
    this.logMessageAndResultOfCallback("message one!", makeMessage2);
}
private sideEffect1:string = "";
private sideEffect2:string = "";

logMessageAndResultOfCallback( message1:string, callback:Function ){
    console.log(message1);
    this.sideEffect1 = message1;

    callback().then((message2)=>{
          console.log(message2);
          this.sideEffect2 = message2;
    }
}

I guess the part I don't understand is how to define the "callback" function, how to invoke it. I understand I would wait for the complete or emit handlers, like makeMessage2().subscribe(message2 => console.log(message2)); but I don't have any clue how to define makeMessage2.

This may be totally clueless question, but I've read about 10 different intros to rxjs and this hasn't quite clicked. I just need to map this scenario to observable pattern and I think I can understand it.

Basically, I want to define an observable function myObs() that does not "execute immediately" but "executes" whenever the someMethod(message:string,obs:Observable) is executed. When myObs is executed, it should do something ansynchronously within it (like get the result of a HTTP request) then set the next value, then fire a complete() so my observer defined in someMethod can handle the complete and do something with the result.

Edit: I'm not concerned with the timer or native equivalents in rxjs, this is just to simulate any async action, like getting data from the server.

Body:
I solved it with help from this guide.

import {Observable} from 'rxjs';
var makeMessage2 = Observable.create(observer => {
  // Yield a single value and complete
  setTimeout(function(){
     let r = Math.random();
     observer.next("message two plus random value: " + r );
     observer.complete();
  }, 1000);
  return () => console.log('disposed')
});
logMessageAndResultOfCallback( "some message one", makeMessage2);

logMessageAndResultOfCallback( message1:string, callback:Observeable ){
    console.log(message1);
    this.sideEffect1 = message1;

    var subscription = callback.subscribe(
       (value)=>{this.sideEffect2 = value;},
       (e) =>{ console.log('onError: %s', e)},
       () => {console.log(this.sideEffect2);});
      subscription.dispose();
}


问:
How to avoid computation every time a python module is reloaded
I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.

To give more information about my problem,

```<code>FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min
</code>```

答:
There's another pretty obvious solution for this problem. When code is reloaded the original scope is still available.

So... doing something like this will make sure this code is executed only once.

```<code>try:
    FD
except NameError:
    FD = FreqDist(word for word in brown.words())
</code>```

Body:
I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation.

To give more information about my problem,

FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min

LastEditorDisplayName: Triptych

Body:
There's another pretty obvious solution for this problem. When code is reloaded the original scope is still available.

So... doing something like this will make sure this code is executed only once.

try:
    FD
except NameError:
    FD = FreqDist(word for word in brown.words())

OwnerDisplayName: Rick van Hattem


问:
price of developer license for Windows Phone 7?
Does Microsoft offer developer license for professionals and students? Is there a special student program?</p>

答:
If you're simply interested in developing using the emulator, there is no license fee to pay. Just download the tools and go to town.

Scott Guthrie actually has a good write-up of all the tools you'll need to download (for free) and how to get started:

Windows Phone 7 Developer Tools Released - ScottGu's Blog

Registering for the Marketplace to sell your apps is another story. You will have to pay a $99 fee to create your account there unless you are a student participating in Microsoft's DreamSpark program (in which case the registration is free there as well).


问:
Python equivalent to C#'s ListView?
I am creating a simple GUI program to manage priorities. The thing is, I am coming from C# to Python, and my question is what exactly is Python's equivalent for a ListView in C#?  </p>

答:
It depends on which GUI package you go for.  For WX, it is wx.ListCtrl and for tk it is listbox.  Probably a good idea to have a look through some docs:

https://wxpython.org/ for WX

https://wiki.python.org/moin/TkInter for tk

Title: Python equivalent to C#'s ListView?


问:
How to divide different divs on the same line along the width of a device in different resolutions?
I have a list of projects consists of multiples lines.Each line consists of 3 divs:

The first contain a logo.

The second contains the title, state and the date of the project.

The third contains some more infos.

I want to put the 3 divs on the same line and take in consideration the width of different resolutions of device into the display of the page.
index.html:

As a result I got the logo in a line and the two other divs in another line.How can I fix that?

#list_project {
  position: relative;
  top: 120px;
  z-index: 1;
}

.project_logo {
  display: block;
  height: 60px;
}

.project_title {
  font-size: 18px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_status {
  font-size: 18px;
  font-family: "Arial Round MT Bold";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_date {
  font-size: 18px;
  font-family: "Arial";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_info_1 {
  border-radius: 10px;
  background-color: #e6e1e1;
  height: 63px;
}

.project_cost {
  font-size: 16px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_cost_1 {
  font-size: 16px;
  font-family: "Arial";
  color: #8e8e8e;
  font-weight: bold;
  line-height: 1.2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="list_project">
  <div class="container-fluid">
    <div class="row">
      <div class="col col-sm-4 col-md-4 col-lg-4 col-xl-4">
        <img class="project_logo" src="./logos/logo.png" />
      </div>
      <div class="col col-sm-4 col-md-4 col-lg-4 col-xl-4">
        <table>
          <tbody>
            <tr>
              <td class="project_title"> Project 1 </td>
            </tr>
            <tr>
              <td class="project_status">Active</td>
            </tr>
            <tr>
              <td class="project_date">03/2017-05/2018</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="col col-sm-4 col-md-4 col-lg-4 col-xl-4">
        <table class="project_info_1">
          <tbody>
            <tr>
              <td class="project_cost" name="project_cost">Cost:</td>
              <td class="project_cost_1" name="project_cost_1">140.000k$.</td>
            </tr>
            <tr>
              <td class="project_cost" name="project_delay">Delay:</td>
              <td class="project_cost_1" name="project_delay_1">350 days.</td>
            </tr>
            <tr>
              <td class="project_cost" name="project_load">Load:</td>
              <td class="project_cost_1" name="project_load_1">125 days.</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div></code>```

答:
Ok First of all it won't work because you have clas="..." and not class="..". So that alone won't make it work

Lastly, as a guide "col col-sm-4 col-md-4 col-lg-4 col-xl-4" is not needed.
You can use only "col col-sm-4 col-md-4" because any resolution bigger will use the last 'highest span' found, if you know what I mean which in your case is col-md-4 if you make the change, therefore col-md-4 will be 4 for lg, xl, xxl as well.

You only add the col-lg and so on if there are to be of different span size

Body:
I have a list of projects consists of multiples lines.Each line consists of 3 divs:

The first contain a logo.

The second contains the title, state and the date of the project.

The third contains some more infos.

I want to put the 3 divs on the same line and take in consideration the width of different resolutions of device into the display of the page.
index.html:

As a result I got the logo in a line and the two other divs in another line.How can I fix that?

#list_project {
  position: relative;
  top: 120px;
  z-index: 1;
}

.project_logo {
  display: block;
  height: 60px;
}

.project_title {
  font-size: 18px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_status {
  font-size: 18px;
  font-family: "Arial Round MT Bold";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_date {
  font-size: 18px;
  font-family: "Arial";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_info_1 {
  border-radius: 10px;
  background-color: #e6e1e1;
  height: 63px;
}

.project_cost {
  font-size: 16px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_cost_1 {
  font-size: 16px;
  font-family: "Arial";
  color: #8e8e8e;
  font-weight: bold;
  line-height: 1.2;
}

               Project 1

              Active

              03/2017-05/2018

              Cost:
              140.000k$.

              Delay:
              350 days.

              Load:
              125 days.


问:
Android 6.0 not checked Switch preference from layout resource. Android 7.0 work fine
Java

```<code>DeviceSwitch.setLayoutResource(R.layout.settings);
DeviceSwitch.setKey(CategoryKey);
DeviceSwitch.setDefaultValue(true);
DeviceSwitch.setEnabled(true);
DeviceSwitch.setSelectable(true);
DevicesShowScreen.addPreference(DeviceSwitch);
</code>```

if this code run --> DeviceSwitch.setLayoutResource(R.layout.settings);
Switch not checked in Android 6.0

This string --> DeviceSwitch.setCheked(true);
Not work in Android 6.0

in Android 7.0 switch preference from layout checked normal

Layout

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/listPreferredItemHeightSmall"
    android:gravity="center_vertical"
    android:clipToPadding="false">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingTop="16dp"
        android:paddingBottom="16dp"
        android:layout_marginStart="15dp">

        <TextView android:id="@android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?attr/textAppearanceListItem"
            android:ellipsize="marquee" />

        <TextView android:id="@android:id/summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@android:id/title"
            android:layout_alignStart="@android:id/title"
            android:maxLines="10"
            android:ellipsize="end" />

    </RelativeLayout>

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:focusable="false"
        android:clickable="false"
        android:gravity="center"
        android:layout_marginEnd="15dp"
        android:id="@android:id/switch_widget"
        android:checked="false" />

</LinearLayout>
</code>```

答:
It's because sdk 23 uses com.android.internal.R.id.switchWidget identifier instead of com.android.internal.R.id.switch_widget

Workaround is quite simple. Just inherit SwitchPreference class and duplicate some code:

```<code>public class MySwitchPreference extends SwitchPreference {
    private final Listener mListener = new Listener();

    private class Listener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (!callChangeListener(isChecked)) {
                // Listener didn't like it, change it back.
                // CompoundButton will make sure we don't recurse.
                buttonView.setChecked(!isChecked);
                return;
            }

            MySwitchPreference.this.setChecked(isChecked);
        }
    }

    public MySwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
       super(context, attrs, defStyleAttr, defStyleRes);
    }

    public MySwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public MySwitchPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MySwitchPreference(Context context) {
        super(context);
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);

        View checkableView = view.findViewById(R.id.switch_widget);
        if (checkableView != null && checkableView instanceof Checkable) {
            if (checkableView instanceof Switch) {
                final Switch switchView = (Switch) checkableView;
                switchView.setOnCheckedChangeListener(null);
            }

            ((Checkable) checkableView).setChecked(isChecked());

            if (checkableView instanceof Switch) {
                final Switch switchView = (Switch) checkableView;
                switchView.setTextOn(getSwitchTextOn());
                switchView.setTextOff(getSwitchTextOff());
                switchView.setOnCheckedChangeListener(mListener);
            }
        }
    }
}
</code>```

And of course don't forget to replace android:id="@android:id/switch_widget" to android:id="@+id/switch_widget" in your widget switcher layout.

Body:
Java

DeviceSwitch.setLayoutResource(R.layout.settings);
DeviceSwitch.setKey(CategoryKey);
DeviceSwitch.setDefaultValue(true);
DeviceSwitch.setEnabled(true);
DeviceSwitch.setSelectable(true);
DevicesShowScreen.addPreference(DeviceSwitch);

if this code run --> DeviceSwitch.setLayoutResource(R.layout.settings);
Switch not checked in Android 6.0

This string --> DeviceSwitch.setCheked(true);
Not work in Android 6.0

in Android 7.0 switch preference from layout checked normal

Layout

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/listPreferredItemHeightSmall"
    android:gravity="center_vertical"
    android:clipToPadding="false">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingTop="16dp"
        android:paddingBottom="16dp"
        android:layout_marginStart="15dp">

        <TextView android:id="@android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?attr/textAppearanceListItem"
            android:ellipsize="marquee" />

        <TextView android:id="@android:id/summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@android:id/title"
            android:layout_alignStart="@android:id/title"
            android:maxLines="10"
            android:ellipsize="end" />

    </RelativeLayout>

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:focusable="false"
        android:clickable="false"
        android:gravity="center"
        android:layout_marginEnd="15dp"
        android:id="@android:id/switch_widget"
        android:checked="false" />

</LinearLayout>

Body:
It's because sdk 23 uses com.android.internal.R.id.switchWidget identifier instead of com.android.internal.R.id.switch_widget

Workaround is quite simple. Just inherit SwitchPreference class and duplicate some code:

public class MySwitchPreference extends SwitchPreference {
    private final Listener mListener = new Listener();

    private class Listener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (!callChangeListener(isChecked)) {
                // Listener didn't like it, change it back.
                // CompoundButton will make sure we don't recurse.
                buttonView.setChecked(!isChecked);
                return;
            }

            MySwitchPreference.this.setChecked(isChecked);
        }
    }

    public MySwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
       super(context, attrs, defStyleAttr, defStyleRes);
    }

    public MySwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public MySwitchPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MySwitchPreference(Context context) {
        super(context);
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);

        View checkableView = view.findViewById(R.id.switch_widget);
        if (checkableView != null && checkableView instanceof Checkable) {
            if (checkableView instanceof Switch) {
                final Switch switchView = (Switch) checkableView;
                switchView.setOnCheckedChangeListener(null);
            }

            ((Checkable) checkableView).setChecked(isChecked());

            if (checkableView instanceof Switch) {
                final Switch switchView = (Switch) checkableView;
                switchView.setTextOn(getSwitchTextOn());
                switchView.setTextOff(getSwitchTextOff());
                switchView.setOnCheckedChangeListener(mListener);
            }
        }
    }
}

And of course don't forget to replace android:id="@android:id/switch_widget" to android:id="@+id/switch_widget" in your widget switcher layout.


问:
Regex to match group less than or equal to n times
I'm basically looking for the reverse of

```<code>\d{n,} // matches \d n or more times
</code>```

such that

```<code>\d{,3} // hypothetical syntax
</code>```

would match

```<code>1
12
123
</code>```

and not

```<code>1234
12345
etc.
</code>```

The above examples aren't representative of anything I'm actually trying to match against. This is just a general question. Does something like this exist?

答:
Engines that support the range quantifier {min,max}  syntax

specify that

min is required

( minimum matches of the preceding construct )

, is optional

If , is not present, max = min

max is optional and , must precede it if max is present

( maximum matches of the preceding construct )

If max is not present, and is preceded by a ,  the max defaults to unlimited.

You can't tell the range quantifier to be un-greedy.

It is always greedy, but may match less if backtracking occurs,

or it can't match the maximum, because it's not there.

Or some surrounding assert construct(s) prohibit a full max range match.

Body:
I'm basically looking for the reverse of

\d{n,} // matches \d n or more times

such that

\d{,3} // hypothetical syntax

would match

1
12
123

and not

1234
12345
etc.

The above examples aren't representative of anything I'm actually trying to match against. This is just a general question. Does something like this exist?


问:
Grails.pass parameters from the controller to external .js file?
I have controller:

```<code>package plugin

class TestController {

def simply = {[name:new Date()]}
}
</code>```

as you see i pass param name

my view page:

```<code><html>
<head>
<!-- <script type="text/javascript" src="${resource(dir:'resource/js',file:'simply.js')}?color=FA8DFF">-->

<g:javascript>
    alert("${name}")
</g:javascript>
</head>
<body>
</body>
</html>
</code>```

this page run correct - afrer load i see alert window with current date :)

but, when

view page:

```<code><html>
<head>
<script type="text/javascript" src="${resource(dir:'resource/js',file:'simply.js')}?color=FA8DF">
</script>
</head>
<body>
</body>
</html>
</code>```

and external simply.js file:

```<code>alert("${name}")
</code>```

i see empty alert window. So, my question: how i can pass params to external.js file?

答:
There are two stages in parsing the view when it is displayed to the user. State one is the server executing any code contained in the view page. In your case

```<code>${name}
</code>```

Is turned into the current date since that’s the value from the controller. This means that the text sent to the users browser contains 3/2/2010 instead of ${name}

The second stage that takes place when the user accesses a view is the browser parsing the HTML. The HTML that is sent to the browser depends on what took place on the server. Since in your example the JavaScript is contained in the view ${name} is replaced with the current date on the server. Then JavaScript containing 3/3/2010 is sent to the browser since ${name} was replaced by 3/3/2010 on the server. This means the popup box will contain 3/3/2010. If you include external JavaScript files they never get run through the first step since the browser directly downloads them and does not make a request to the server. This means that the first step never takes place so $[name} does not get replaced with the value from your controller. This behavior is the same weather you use the

```<code><script>
</code>```

or

```<code><g:javascript>
</code>```

tag.
In order to pass values from a view into JavaScript located in an external file you should define your JavaScript as functions in external files if you wish to pass parameters. For example in external.js

```<code>Function dispDate(theParam)
{
Alert(theParam);
}
</code>```

Then from your view

```<code><g:javascript src="external.js" />
<script type="text/JavaScript">
dispDate(“${name}”);
 </script>
</code>```

Where external.js is stored in the web-app/js directory.

Body:
I have controller:

package plugin

class TestController {

def simply = {[name:new Date()]}
}

as you see i pass param name

my view page:

Body:
There are two stages in parsing the view when it is displayed to the user. State one is the server executing any code contained in the view page. In your case

${name}

Is turned into the current date since that’s the value from the controller. This means that the text sent to the users browser contains 3/2/2010 instead of ${name}

The second stage that takes place when the user accesses a view is the browser parsing the HTML. The HTML that is sent to the browser depends on what took place on the server. Since in your example the JavaScript is contained in the view ${name} is replaced with the current date on the server. Then JavaScript containing 3/3/2010 is sent to the browser since ${name} was replaced by 3/3/2010 on the server. This means the popup box will contain 3/3/2010. If you include external JavaScript files they never get run through the first step since the browser directly downloads them and does not make a request to the server. This means that the first step never takes place so $[name} does not get replaced with the value from your controller. This behavior is the same weather you use the

<script>

or

<g:javascript>

tag.
In order to pass values from a view into JavaScript located in an external file you should define your JavaScript as functions in external files if you wish to pass parameters. For example in external.js

Function dispDate(theParam)
{
Alert(theParam);
}

Then from your view

<g:javascript src="external.js" />
<script type="text/JavaScript">
dispDate(“${name}”);
 </script>

Where external.js is stored in the web-app/js directory.