问:
Date Range Based on Today
I am trying to write a stored procedure that will be called by an automated report on the 1st, 8th, 15th, and 22nd of each month.

Below I have the code I am currently trying to use however I keep getting the error Explicit conversion from data type int to date is not allowed. on the line for @StartDate if ran on the 1st. However I have tried commenting out that section and I just get the same error but then for the next @StartDate.

I need @StartDate and @EndDate to be able to change based on which day of the month the report is currently being ran.

On the 1st it would need to be ran from the 21st of the
previous month to the end of the previous month.

On the  8th it would need to be  1st of the current month to the  7th.

On the 15th it would need to be  8th of the current month to the 14th.

On the 22nd it would need to be 15th of the current month to the 21st.

```<code>Declare @RunDate    date
Declare @StartDate Date
Declare @EndDate    Date

Set  @RunDate = '3/1/2017'

If (Day(@RunDate) = 1)
Begin

Set @StartDate  = Convert(Date,(Month(DATEADD(d,-1,@Rundate)) + '/21/' + Case When Month(@Rundate) = '1' Then Year(@RunDate) Else Year(DATEADD(yy,-1,@Rundate)) End),101)
Set @EndDate    = Convert(date,DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,@Rundate),0))),101)

End
Else
IF (Day(@RunDate) = 8)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/1/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/7/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 15)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/8/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/14/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 22)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/15/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/21/' + Year(@RunDate)),101)

End
</code>```

I am using SQL Server 2012 back end with SSMS 2016 front end. If that helps.

答:
The error is because you are trying to add integer and varchar values together. Using this line as an example:

```<code>Set @StartDate  = Convert(Date,(Month(DATEADD(d,-1,@Rundate)) + '/21/' + Case When Month(@Rundate) = '1' Then Year(@RunDate) Else Year(DATEADD(yy,-1,@Rundate)) End),101)
</code>```

If you break down the parts of your calculation you have the month integer value, a day varchar value and a year integer value. If you try to concatenate these you get the error message:

Msg 245, Level 16, State 1, Line 9 Conversion failed when converting
  the varchar value '/21/' to data type int.

You could cast the integer values to varchar and it would work.

It is recommended to use the built-in date functions than using concatenation so you could achieve the same result like so:

```<code>DECLARE
    @RunDate DATE = '20170101'
,   @StartDate DATE
,   @EndDate DATE

IF DATEPART(DAY, @RunDate) = 1
    SELECT
        @StartDate = DATEADD(DAY, -(DATEPART(DAY, DATEADD(DAY, -1, @RunDate)) - 20), @RunDate)
    ,   @EndDate = DATEADD(DAY, -1, @RunDate)

SELECT
    @StartDate
,   @EndDate
</code>```

Title: Date Range Based on Today

Body:
I am trying to write a stored procedure that will be called by an automated report on the 1st, 8th, 15th, and 22nd of each month.

Below I have the code I am currently trying to use however I keep getting the error Explicit conversion from data type int to date is not allowed. on the line for @StartDate if ran on the 1st. However I have tried commenting out that section and I just get the same error but then for the next @StartDate.

I need @StartDate and @EndDate to be able to change based on which day of the month the report is currently being ran.

On the 1st it would need to be ran from the 21st of the
previous month to the end of the previous month.

On the  8th it would need to be  1st of the current month to the  7th.

On the 15th it would need to be  8th of the current month to the 14th.

On the 22nd it would need to be 15th of the current month to the 21st.

Declare @RunDate    date
Declare @StartDate Date
Declare @EndDate    Date

Set  @RunDate = '3/1/2017'

If (Day(@RunDate) = 1)
Begin

Set @StartDate  = Convert(Date,(Month(DATEADD(d,-1,@Rundate)) + '/21/' + Case When Month(@Rundate) = '1' Then Year(@RunDate) Else Year(DATEADD(yy,-1,@Rundate)) End),101)
Set @EndDate    = Convert(date,DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,@Rundate),0))),101)

End
Else
IF (Day(@RunDate) = 8)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/1/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/7/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 15)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/8/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/14/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 22)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/15/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/21/' + Year(@RunDate)),101)

End

I am using SQL Server 2012 back end with SSMS 2016 front end. If that helps.

Body:
The error is because you are trying to add integer and varchar values together. Using this line as an example:

Set @StartDate  = Convert(Date,(Month(DATEADD(d,-1,@Rundate)) + '/21/' + Case When Month(@Rundate) = '1' Then Year(@RunDate) Else Year(DATEADD(yy,-1,@Rundate)) End),101)

If you break down the parts of your calculation you have the month integer value, a day varchar value and a year integer value. If you try to concatenate these you get the error message:

Msg 245, Level 16, State 1, Line 9 Conversion failed when converting
  the varchar value '/21/' to data type int.

You could cast the integer values to varchar and it would work.

It is recommended to use the built-in date functions than using concatenation so you could achieve the same result like so:

DECLARE
    @RunDate DATE = '20170101'
,   @StartDate DATE
,   @EndDate DATE

IF DATEPART(DAY, @RunDate) = 1
    SELECT
        @StartDate = DATEADD(DAY, -(DATEPART(DAY, DATEADD(DAY, -1, @RunDate)) - 20), @RunDate)
    ,   @EndDate = DATEADD(DAY, -1, @RunDate)

SELECT
    @StartDate
,   @EndDate


来源: stackexchange

问:
Developing new TEditButton types requires dclfmxstd package which does not exist as dcp
I am using Delphi Berlin Enterprise and I need to extend some functionalities of the TClearEditButton and TDropDownEditButton. So I developed my own TMEClearEditButton and TMEDropDownListEditButton. They are subclasses of the standard FireMonkey ones, so I used the FMX.Edit unit. I did some test by creating the buttons by code and had no problems up to here.

Problems started when I decided to build a designtime only package to have the possibility to add the buttons to edits directly in the IDE. Copying some code from FMX.Editors, I came up with the following:

```<code>Unit ME.Editors;

Interface

Uses
  System.Classes,
  DesignIntf,
  FMX.Editor.Items,
  FMX.Design.Items;

Type
  TMEEditEditor = Class(TItemsEditor)
  Public
    Constructor Create(AComponent: TComponent; ADesigner: IDesigner); Override;
  End;

Implementation

Uses
  FMX.Edit,
  ME.Edit;

Constructor TMEEditEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
Begin
  Inherited Create(AComponent, ADesigner);
  FAllowChild := False;
  SetLength(FItemsClasses, 10);
  FItemsClasses[0] := TItemClassDesc.Create(TEditButton);
  FItemsClasses[1] := TItemClassDesc.Create(TMEClearEditButton);
  FItemsClasses[2] := TItemClassDesc.Create(TPasswordEditButton);
  FItemsClasses[3] := TItemClassDesc.Create(TSearchEditButton);
  FItemsClasses[4] := TItemClassDesc.Create(TEllipsesEditButton);
  FItemsClasses[5] := TItemClassDesc.Create(TDropDownEditButton);
  FItemsClasses[6] := TItemClassDesc.Create(TMEDropDownListEditButton);
  FItemsClasses[7] := TItemClassDesc.Create(TMEDropDownDateEditButton);
  FItemsClasses[8] := TItemClassDesc.Create(TMEDropDownTimeEditButton);
  FItemsClasses[9] := TItemClassDesc.Create(TSpinEditButton);
End;

End.
</code>```

Now compiling this requires some standard delphi designtime packages:

DesignIDE

fmxdesigner

dclcommon

... but that does not seem to be enough. It now compiles, but with warning that the following units were implicitly imported into my package:

FMX.Design.Lang

FmxDsnConst

FMX.Editor.Items

FMX.Design.Items

... and suggesting I should add the dclfmxstd package to the requires list.

If I do so, it won't work because no dclfmxstd.dcp actually exists anywhere on my computer. There is a dclfmxstd240.bpl package library in my 18.0\bin directory, but no dcp compiled package anywhere.

I also tried to copy those 4 units in my development directory and include them explicitly in my package... but that won't work as it states that those units are already included in the dclfmxstd240 package.

Any hints as to how to get out of this empasse and move forward?

PS - As an aside... it would be nice to have a mapping of delphi units to packages so as to know which packages have to be referenced... without using a binary search tool on all the many dcps in Lib ;)

I have reported this issue on the Embarcadero QP (RSP-17686)

答:
I thought I'd post this as an answer because although it doesn't solve your problem in a very satisfactory way, I've at least got as far as deriving an FMX component which I can install in the IDE and which has a custom designer.  What I've done might give you some ideas for where next.

Here's what I've done:

I created a unit containing a minimal descendant of FMX's TEdit, TMyEdit.  This uses the following FMX units:    FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation and FMX.Edit.
I also created a separate unit (like you are supposed to) containing a minimal component edit.  This unit only uses System.Classes, DesignIntf, FMX.Editor.Items and FMX.Design.Items.

I added both of these units to a new .Dpk project and set its Requires clause to list RTL.DCP, FMX.DCP and FMXDesigner.DCP.

I compiled the .Dpk and attempted to install it.  I got the same dialog as you suggesting to add DclFMXStd.DCP to my Requires list.  And then, of course, it complained that it couldn't find it.

I searched my entire h/disk for DclFMXStd.* and of course it found nothing apart from DclFMXStd230.BPL, but no counterpart .DCP file.

So then I wondered "Where is it getting the name 'DclFMXStd' from?  A Grep search of my Seattle  install (which is what I'm using, though I have Tokyo installed to) found that the only file that contains the name is the package file, DclFMXStd230.Bpl, which contains 3 occurrences of it.  I confirmed this by running Delphi's TDump utility on the .Bpl.

So then I thought 'What if I uninstall DclFMXStd230.Bpl from the IDE?'.  I tried, and Presto, my package now compiles and installs without complaint,  Although, of course, the IDE is now devoid of the supplied FMX components.

So, I think that would be enough to file a legitimate QP report, if I were in your position.

If you want to reinstate the other FMX components, I suppose you could think about adding them to your package, though you might want to check whether that is allowed under the terms of your Delphi licence.

The other thing I've been wondering is 'Surely, other FMX authors must have run into this problem, despite google only finding your SO posts?  So it might be worth tracking down a preferably-freeware FMX library with source and looking at how the authors solve or avoid the problem.

Good luck!

ContentLicense: CC BY-SA 3.0

Body:
I am using Delphi Berlin Enterprise and I need to extend some functionalities of the TClearEditButton and TDropDownEditButton. So I developed my own TMEClearEditButton and TMEDropDownListEditButton. They are subclasses of the standard FireMonkey ones, so I used the FMX.Edit unit. I did some test by creating the buttons by code and had no problems up to here.

Problems started when I decided to build a designtime only package to have the possibility to add the buttons to edits directly in the IDE. Copying some code from FMX.Editors, I came up with the following:

Unit ME.Editors;

Interface

Uses
  System.Classes,
  DesignIntf,
  FMX.Editor.Items,
  FMX.Design.Items;

Type
  TMEEditEditor = Class(TItemsEditor)
  Public
    Constructor Create(AComponent: TComponent; ADesigner: IDesigner); Override;
  End;

Implementation

Uses
  FMX.Edit,
  ME.Edit;

Constructor TMEEditEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
Begin
  Inherited Create(AComponent, ADesigner);
  FAllowChild := False;
  SetLength(FItemsClasses, 10);
  FItemsClasses[0] := TItemClassDesc.Create(TEditButton);
  FItemsClasses[1] := TItemClassDesc.Create(TMEClearEditButton);
  FItemsClasses[2] := TItemClassDesc.Create(TPasswordEditButton);
  FItemsClasses[3] := TItemClassDesc.Create(TSearchEditButton);
  FItemsClasses[4] := TItemClassDesc.Create(TEllipsesEditButton);
  FItemsClasses[5] := TItemClassDesc.Create(TDropDownEditButton);
  FItemsClasses[6] := TItemClassDesc.Create(TMEDropDownListEditButton);
  FItemsClasses[7] := TItemClassDesc.Create(TMEDropDownDateEditButton);
  FItemsClasses[8] := TItemClassDesc.Create(TMEDropDownTimeEditButton);
  FItemsClasses[9] := TItemClassDesc.Create(TSpinEditButton);
End;

End.

Now compiling this requires some standard delphi designtime packages:

DesignIDE

fmxdesigner

dclcommon

... but that does not seem to be enough. It now compiles, but with warning that the following units were implicitly imported into my package:

FMX.Design.Lang

FmxDsnConst

FMX.Editor.Items

FMX.Design.Items

... and suggesting I should add the dclfmxstd package to the requires list.

If I do so, it won't work because no dclfmxstd.dcp actually exists anywhere on my computer. There is a dclfmxstd240.bpl package library in my 18.0\bin directory, but no dcp compiled package anywhere.

I also tried to copy those 4 units in my development directory and include them explicitly in my package... but that won't work as it states that those units are already included in the dclfmxstd240 package.

Any hints as to how to get out of this empasse and move forward?

PS - As an aside... it would be nice to have a mapping of delphi units to packages so as to know which packages have to be referenced... without using a binary search tool on all the many dcps in Lib ;)

I have reported this issue on the Embarcadero QP (RSP-17686)


问:
Help with my funky PHP loop
Ok so i have this page and when viewed in firefox the proper results show up but when i look at it in chrome or safari it is way off. Could it be the funky php loop that i am using that makes it off in the browsers..Here is my code

I am generating a left and right array..seems like a hack to me

```<code>    $left = array();
    $right = array();
$finaltot=0.00;
 for($i=0;$i<count($steps);$i++)
{
$sql="SELECT *  FROM configure_system WHERE EstimateID='".$_SESSION['ESTQUOTE']."' AND StepID=".($i+1) ;
$expstep=ExecuteGetRows($sql);

if ($i % 2 == 0) {
      $sql="SELECT SUM(TotalPrice) AS TOT FROM configure_system WHERE EstimateID='".$_SESSION['ESTQUOTE']."' AND StepID=".($i+1);
      $tots=ExecuteGetRows($sql);
    $left["Step"][$i][]  = $steps[$i];
    $left["expstep"][$i][]  = $expstep;
    $left["final_total"][$i][] = $tots[0]['TOT'];
    $finaltot+=$tots[0]['TOT'];
  } else {
   $sql="SELECT SUM(TotalPrice) AS TOT FROM configure_system WHERE EstimateID='".$_SESSION['ESTQUOTE']."' AND StepID=".($i+1);
   $tots=ExecuteGetRows($sql);
    $right["Step"][$i][]  = $steps[$i];
    $right["expstep"][$i][]  = $expstep;
    $left["final_total"][$i][] = $tots[0]['TOT'];
    $finaltot+=$tots[0]['TOT'];

 }
</code>```

then since the left array only has 0,2,4,6,8,10
and right has 1,3,5,7,9,11

so my loops are like this

```<code><?php for($i=0;$i<count($left['Step']) * 2;$i++) { ?>
      <?php $i++; ?>
<?php } ?>

<?php for($i=1;$i<count($right['Step'])* 2;$i++) { ?>
      <?php $i++; ?>
<?php } ?>
</code>```

So as you can see the code is a bit off and i think that maybe the problem with why safari and chrome are off...any suggestions

答:
Why do not use foreach instead?

```<code>foreach ($right['Step'] as $i => $val) {
     // ...
}
</code>```

Also you could get the same results with only one query:

```<code>  SELECT SUM(TotalPrice) AS TOT
    FROM configure_system
   WHERE EstimateID='".$_SESSION['ESTQUOTE']."'
GROUP BY StepID
</code>```

ContentLicense: CC BY-SA 2.5

Title: Help with my funky PHP loop

Body:
Ok so i have this page and when viewed in firefox the proper results show up but when i look at it in chrome or safari it is way off. Could it be the funky php loop that i am using that makes it off in the browsers..Here is my code

I am generating a left and right array..seems like a hack to me

    $left = array();
    $right = array();
$finaltot=0.00;
 for($i=0;$i<count($steps);$i++)
{
$sql="SELECT *  FROM configure_system WHERE EstimateID='".$_SESSION['ESTQUOTE']."' AND StepID=".($i+1) ;
$expstep=ExecuteGetRows($sql);

if ($i % 2 == 0) {
      $sql="SELECT SUM(TotalPrice) AS TOT FROM configure_system WHERE EstimateID='".$_SESSION['ESTQUOTE']."' AND StepID=".($i+1);
      $tots=ExecuteGetRows($sql);
    $left["Step"][$i][]  = $steps[$i];
    $left["expstep"][$i][]  = $expstep;
    $left["final_total"][$i][] = $tots[0]['TOT'];
    $finaltot+=$tots[0]['TOT'];
  } else {
   $sql="SELECT SUM(TotalPrice) AS TOT FROM configure_system WHERE EstimateID='".$_SESSION['ESTQUOTE']."' AND StepID=".($i+1);
   $tots=ExecuteGetRows($sql);
    $right["Step"][$i][]  = $steps[$i];
    $right["expstep"][$i][]  = $expstep;
    $left["final_total"][$i][] = $tots[0]['TOT'];
    $finaltot+=$tots[0]['TOT'];

 }

then since the left array only has 0,2,4,6,8,10
and right has 1,3,5,7,9,11

so my loops are like this

<?php for($i=0;$i<count($left['Step']) * 2;$i++) { ?>
      <?php $i++; ?>
<?php } ?>

<?php for($i=1;$i<count($right['Step'])* 2;$i++) { ?>
      <?php $i++; ?>
<?php } ?>

So as you can see the code is a bit off and i think that maybe the problem with why safari and chrome are off...any suggestions

Body:
Why do not use foreach instead?

foreach ($right['Step'] as $i => $val) {
     // ...
}

Also you could get the same results with only one query:

  SELECT SUM(TotalPrice) AS TOT
    FROM configure_system
   WHERE EstimateID='".$_SESSION['ESTQUOTE']."'
GROUP BY StepID


问:
How can i store object in MySql Database?
can i store some object in MySql Database? Because I am making a online or offline support system by MySql. So it is important to store all data as Object. Do you have better Idea except Object?

This is Damo example about object

```<code>$data = array(
                'user_id' => 1, //$userId,
                'payment_id' => $payment_id,
                'hash' => $hash,
                'conversation' => $object,
                'amount' => $paypal->getTransactions()[0]->getAmount()->getTotal(),
                'description' => $paypal->getTransactions()[0]->getDescription()
            );
$this->db->insert($this->table, $data);
</code>```

答:
MySql has added many features in MySql 5.7. Now you can do it in many ways.

Oracle, like Big Data is now Integrating in MySQL.

MySql has Unlocked New Big Data Insights with MySQL & Hadoop.

Solution 1: You can use MySQL as a Document Store. It is possible to store many many object as JSON. It is highly recommended and Extendable.

MySQL Document Store = (MySql + NoSql).

X Dev API will help to produce JSON with SQL and CRUD operation over X
  Protocol. Also there is the possibility of maintaining X Session.

It will be best for transparent data sending and sharing for chat application or group Application.

Solution 2: MySql Sysbench: Read Only is another great solution. It will be very very fast and scalable to make group chat Applications.

Solution 3: Use MySql 5.7 : InnoDB, NoSql with Memcached API which will interact directly with storage engine InnoDB. It is 6X faster than MySql 5.6.

Currently, FaceBook is using this technology. Because it is very fast.

For more details:

https://www.mysql.com/news-and-events/web-seminars/introducing-mysql-document-store/

https://dev.mysql.com/doc/refman/5.7/en/document-store-setting-up.html

https://www.oracle.com/big-data/index.html

https://www.youtube.com/watch?v=1Dk517M-_7o

Body:
can i store some object in MySql Database? Because I am making a online or offline support system by MySql. So it is important to store all data as Object. Do you have better Idea except Object?

This is Damo example about object

$data = array(
                'user_id' => 1, //$userId,
                'payment_id' => $payment_id,
                'hash' => $hash,
                'conversation' => $object,
                'amount' => $paypal->getTransactions()[0]->getAmount()->getTotal(),
                'description' => $paypal->getTransactions()[0]->getDescription()
            );
$this->db->insert($this->table, $data);

ContentLicense: CC BY-SA 4.0


问:
Regex - Find Name With No Middle Initial
I'm doing a query on an SQL database and need to write a regular expression to find names with no middle initial.

For example.

Michael J. Fox - Should fail

Michael J Fox - Should fail

Michael Fox - Should pass

Full names in the database are stored in a single string for reference.

答:
the ^ operator looks for characters at the begining of the line and the \$ operator looks at the end of the line. this regex will look for exactly two words in a line that are at least two characters long.

^[a-zA-Z]{2,} [a-zA-Z]{2,}\$


问:
trellis layered plots in altair/Vega-Lite
I would like to compare multiple conditions of an altair (ultimately vega-lite) layered plot. The perfect solution would be to facet/trellis the plot so I can see the different conditions side by side. Unfortunately I cannot figure out how to give the command to plot the different conditions.

Here is my attempt to implement my idea based on the example for layered plots:
(https://github.com/ellisonbg/altair/blob/master/altair/notebooks/07-LayeredCharts.ipynb)

```<code>import pandas as pd
import numpy as np

data = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10), 'z':['a', 'b']*5})

chart = LayeredChart(data)
chart += Chart().mark_line().encode(x='x:Q', y='y:Q', column='z:Q')
chart += Chart().mark_point().encode(x='x:Q', y='y:Q', column='z:Q')
chart
</code>```

When compared with the example I added the column 'z' with the two conditions, and the two column statements in the Chart definitions.
This solution generates seemingly good Vega-lite code,  but no plot.  Alternatively I tried "chart = LayeredChart(data).encode(column='z:Q')" but I then got the error 'LayeredChart' object has no attribute 'encode'

I am wondering whether it is possible to facet (trellis) layered plots at all and whether it will be possible in future Vega-Lite releases.

I am using jupyter with Anaconda

答: Layering is only experimentally supported in the current release of Vega-Lite and Altair, and I believe you've hit one of the unsupported aspects. This should be addressed in the Vega-Lite 2.0  release (and associated Altair release) later this spring.</p>

Body:
I would like to compare multiple conditions of an altair (ultimately vega-lite) layered plot. The perfect solution would be to facet/trellis the plot so I can see the different conditions side by side. Unfortunately I cannot figure out how to give the command to plot the different conditions.

Here is my attempt to implement my idea based on the example for layered plots:
(https://github.com/ellisonbg/altair/blob/master/altair/notebooks/07-LayeredCharts.ipynb)

import pandas as pd
import numpy as np

data = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10), 'z':['a', 'b']*5})

chart = LayeredChart(data)
chart += Chart().mark_line().encode(x='x:Q', y='y:Q', column='z:Q')
chart += Chart().mark_point().encode(x='x:Q', y='y:Q', column='z:Q')
chart

When compared with the example I added the column 'z' with the two conditions, and the two column statements in the Chart definitions.
This solution generates seemingly good Vega-lite code,  but no plot.  Alternatively I tried "chart = LayeredChart(data).encode(column='z:Q')" but I then got the error 'LayeredChart' object has no attribute 'encode'

I am wondering whether it is possible to facet (trellis) layered plots at all and whether it will be possible in future Vega-Lite releases.

I am using jupyter with Anaconda


问:
F# exists where function?
I have a function processing a DataTable looking for any row that has a column with a certain value. It looks like this:

```<code>let exists =
    let mutable e = false
    for row in dt.Rows do
        if row.["Status"] :?> bool = false
            then e <- true
    e
</code>```

I'm wondering if there is a way to do this in a single expression.  For example, Python has the "any" function which would do it something like this:

```<code>exists = any(row for row in dt.Rows if not row["Status"])
</code>```

Can I write a similar one-liner in F# for my exists function?

答:
Something like this (untested):

dt.Rows |> Seq.exists (fun row -> not (row.["Status"] :?> bool))

https://msdn.microsoft.com/visualfsharpdocs/conceptual/seq.exists%5b%27t%5d-function-%5bfsharp%5d

Title: F# exists where function?

Body:
I have a function processing a DataTable looking for any row that has a column with a certain value. It looks like this:

let exists =
    let mutable e = false
    for row in dt.Rows do
        if row.["Status"] :?> bool = false
            then e <- true
    e

I'm wondering if there is a way to do this in a single expression.  For example, Python has the "any" function which would do it something like this:

exists = any(row for row in dt.Rows if not row["Status"])

Can I write a similar one-liner in F# for my exists function?


问:
Using Dynamic Table name in ADO.NET Source Editor
I have an SSIS data flow task where I am trying to load data from a source table using ADO.NET Source Editor into a SQL Server table.

The problem:

The source table name is dynamic and depends on the current date.

Example: If I want to load today's data then the table name would be Sample_03292017_data and if loading tomorrow's data then it would be Sample_03302017_Data.

I did some research and found how to pass parameters to an ADO.NET Source Editor to use in where conditions but I couldn't find anything on how to use this parameter in a table name.

Does anyone know how I can achieve this? My query is really simple:

```<code>select * from Sample_[DateParameter]_Data.
</code>```

I am using Visual Studio Data Tools 2010.

答:
Expression must be set on the Data Flow Task not in the Ado.net Source

Follow this steps to set an expression for an Ado.net Source:

in the control flow tab click on the Data Flow Task and press F4 to show the properties tab

Click on the expression button, it show up a form like shown below

choose [Ado.net Source].sqlcommand property  and click on the expression builder button

write the following expression "select * from Sample_ " + @[User::DateParameter] + "_Data" (assuming that your data parameter is stored in a variable named DateParameter)

Body:
I have an SSIS data flow task where I am trying to load data from a source table using ADO.NET Source Editor into a SQL Server table.

The problem:

The source table name is dynamic and depends on the current date.

Example: If I want to load today's data then the table name would be Sample_03292017_data and if loading tomorrow's data then it would be Sample_03302017_Data.

I did some research and found how to pass parameters to an ADO.NET Source Editor to use in where conditions but I couldn't find anything on how to use this parameter in a table name.

Does anyone know how I can achieve this? My query is really simple:

select * from Sample_[DateParameter]_Data.

I am using Visual Studio Data Tools 2010.


问:
How to simplify terms with usage of square root in maxima
Let's say we have a term like 1/4 * x/sqrt(2) * x^2 / 2; in Maxima.
As an output (without further modification) it gives x^3/2^(7/2).
How can I force the output format to be like x^3/(8*sqrt(2)) with usage of square roots whenever possible?

答:
```<code>(%i1) sq2: " "(sqrt(2))$
(%i2) matchdeclare(n, lambda([n], oddp(n) and n#1))$
(%i3) defrule(r_sq2, 2^(n/2), sq2*2^((n-1)/2))     $
(%i4) e: 1/4 * x/sqrt(2) * x^2 / 2;
                                       3
                                      x
(%o4)                                ----
                                      7/2
                                     2
(%i5) apply1(e, r_sq2);
                                             3
                                  (sqrt(2)) x
(%o5)                            -------------
                                      16
</code>```

A rule can help to insert sqrt(2). In the example I use a "null" function to prevent simplification. You can also consider box and rembox functions or leave sq2 undefined.

Body:
(%i1) sq2: " "(sqrt(2))$
(%i2) matchdeclare(n, lambda([n], oddp(n) and n#1))$
(%i3) defrule(r_sq2, 2^(n/2), sq2*2^((n-1)/2))     $
(%i4) e: 1/4 * x/sqrt(2) * x^2 / 2;
                                       3
                                      x
(%o4)                                ----
                                      7/2
                                     2
(%i5) apply1(e, r_sq2);
                                             3
                                  (sqrt(2)) x
(%o5)                            -------------
                                      16

A rule can help to insert sqrt(2). In the example I use a "null" function to prevent simplification. You can also consider box and rembox functions or leave sq2 undefined.


问:
How to set margin programmatically in android for a textview inside linearlayout?
I am trying to add margins for each textbox added to a linear layout, which is inside a scrollview. However big margins i set, it doesn't reflect on the UI. Why? I have referred quite a few things on this stack overflow itself.</p>

```<code>import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ScrollView mainScrollView;
    LinearLayout scrollViewContainer;
    ArrayList<String> stringArr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainScrollView = (ScrollView) findViewById(R.id.mainScrollView);
        scrollViewContainer = (LinearLayout)findViewById(R.id.scrollViewContainer);

        stringArr = new ArrayList<String>();
        String str1 = "In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. " +
                "The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).";
        String str2 = "Initializes a newly created String object so that it represents the same sequence of characters as the argument; " +
                "in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed," +
                " use of this constructor is unnecessary since Strings are immutable.";

        for(int ii = 0; ii < 10; ii++){
            if(ii%2 ==  0) {
                stringArr.add(str1);
            }else{
                stringArr.add(str2);
            }
        }
        Resources r = getResources();
        float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
        float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());

        LinearLayoutCompat.LayoutParams textViewLayoutParams =  new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for(int ii = 0; ii < stringArr.size(); ii++){
            TextView textView = new TextView(this);
            textView.setTextSize(12f);
            textView.setText(stringArr.get(ii));
            textView.setLayoutParams(textViewLayoutParams);
            textViewLayoutParams.setMargins(10,30,10,30);
            textView.requestLayout();
            scrollViewContainer.addView(textView);
        }

    }
}
</code>```

答:
```<code>textViewLayoutParams.setMargins(10,30,10,30);
textView.setLayoutParams(textViewLayoutParams);
</code>```

this could be the problem ... you were editing textViewLayoutParams  AFTER  you were setting it to a textView.setLayoutParams(textViewLayoutParams) ...

Body:
I am trying to add margins for each textbox added to a linear layout, which is inside a scrollview. However big margins i set, it doesn't reflect on the UI. Why? I have referred quite a few things on this stack overflow itself.

import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ScrollView mainScrollView;
    LinearLayout scrollViewContainer;
    ArrayList<String> stringArr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainScrollView = (ScrollView) findViewById(R.id.mainScrollView);
        scrollViewContainer = (LinearLayout)findViewById(R.id.scrollViewContainer);

        stringArr = new ArrayList<String>();
        String str1 = "In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. " +
                "The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).";
        String str2 = "Initializes a newly created String object so that it represents the same sequence of characters as the argument; " +
                "in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed," +
                " use of this constructor is unnecessary since Strings are immutable.";

        for(int ii = 0; ii < 10; ii++){
            if(ii%2 ==  0) {
                stringArr.add(str1);
            }else{
                stringArr.add(str2);
            }
        }
        Resources r = getResources();
        float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
        float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());

        LinearLayoutCompat.LayoutParams textViewLayoutParams =  new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for(int ii = 0; ii < stringArr.size(); ii++){
            TextView textView = new TextView(this);
            textView.setTextSize(12f);
            textView.setText(stringArr.get(ii));
            textView.setLayoutParams(textViewLayoutParams);
            textViewLayoutParams.setMargins(10,30,10,30);
            textView.requestLayout();
            scrollViewContainer.addView(textView);
        }

    }
}

Body:
textViewLayoutParams.setMargins(10,30,10,30);
textView.setLayoutParams(textViewLayoutParams);

this could be the problem ... you were editing textViewLayoutParams  AFTER  you were setting it to a textView.setLayoutParams(textViewLayoutParams) ...


答:
Use the following approach(for MySql query):

```<code>SELECT
    fullname
FROM
    table
WHERE
    fullname REGEXP '^[[:alpha:]]+[[:space:]]+[[:alpha:]]+$';
</code>```

[:alpha:] - represents a character class that matches all alphanumeric characters

[:space:] - represents a character class that matches Space, tab, newline, and carriage return

Title: Regex - Find Name With No Middle Initial

Body:
I'm doing a query on an SQL database and need to write a regular expression to find names with no middle initial.

For example.

Michael J. Fox - Should fail

Michael J Fox - Should fail

Michael Fox - Should pass

Full names in the database are stored in a single string for reference.

Body:
Use the following approach(for MySql query):

SELECT
    fullname
FROM
    table
WHERE
    fullname REGEXP '^[[:alpha:]]+[[:space:]]+[[:alpha:]]+$';

[:alpha:] - represents a character class that matches all alphanumeric characters

[:space:] - represents a character class that matches Space, tab, newline, and carriage return


问:
Hundreds of aliases/synonyms vs database tables' fully qualified names
Given hundreds of database tables in multiple schemas, when creating stored procedures and views, would you recommend using aliases/synonyms or fully qualified name? Given a few schema.table like so,

```<code>Orders.OrderHeader, Production.LineThroughput, Sales.Opportunities
</code>```

I expect a slight gain in performance with using qualified names but if a table such as Orders.Customers would have to be moved to Sales.Customers, I would either have to alter existing views/procedures referring to Orders.Customers or use a synonym ahead of time where such a move is anticipated. I see value in moving code into testing using synonyms but at the same time I could as well create a replica of my production environment to test/dev and not require synonyms.

SQL Server Books Online recommends to always use a fully qualified name. Some friends propose creating one synonym for each of the hundreds of tables and using only synonyms. While I prefer to use fully qualified name (more readable and self-explanatory code, knowing what referred object belongs to what schema, and habit of typing schema.table), what significant performance, operational or readability (dis)advantage have you observed with using synonyms vs fully qualified table names?

答:
There is always more than answer to any question. That is why "it depends" is always the right answer. I find that when you stay true to the intentions and design you in the end you come out ahead.

Schemas are designed for namespace isolation. For example, when designing a SaaS system, schemas can be used very effectively to separate concerns for multiple tenants. Schemas can also be used to separate test from production or one application data from another. And it is not just for tables but for stored procedures and all other database objects.

DB2 provides a special register called CURRENT SCHEMA that allows you to code unqualified object names but switch to the right schema by simply setting CURRENT SCHEMA special register like so:

```<code>SET CURRENT SCHEMA =  'Production'
</code>```

This, in my opinion, is a much better approach than using synonyms.

Body:
Given hundreds of database tables in multiple schemas, when creating stored procedures and views, would you recommend using aliases/synonyms or fully qualified name? Given a few schema.table like so,

Orders.OrderHeader, Production.LineThroughput, Sales.Opportunities

I expect a slight gain in performance with using qualified names but if a table such as Orders.Customers would have to be moved to Sales.Customers, I would either have to alter existing views/procedures referring to Orders.Customers or use a synonym ahead of time where such a move is anticipated. I see value in moving code into testing using synonyms but at the same time I could as well create a replica of my production environment to test/dev and not require synonyms.

SQL Server Books Online recommends to always use a fully qualified name. Some friends propose creating one synonym for each of the hundreds of tables and using only synonyms. While I prefer to use fully qualified name (more readable and self-explanatory code, knowing what referred object belongs to what schema, and habit of typing schema.table), what significant performance, operational or readability (dis)advantage have you observed with using synonyms vs fully qualified table names?

Body:
There is always more than answer to any question. That is why "it depends" is always the right answer. I find that when you stay true to the intentions and design you in the end you come out ahead.

Schemas are designed for namespace isolation. For example, when designing a SaaS system, schemas can be used very effectively to separate concerns for multiple tenants. Schemas can also be used to separate test from production or one application data from another. And it is not just for tables but for stored procedures and all other database objects.

DB2 provides a special register called CURRENT SCHEMA that allows you to code unqualified object names but switch to the right schema by simply setting CURRENT SCHEMA special register like so:

SET CURRENT SCHEMA =  'Production'

This, in my opinion, is a much better approach than using synonyms.


问:
remote access is not supported for transaction isolation level snapshot - is this conditional?
Folks - apologies for rehashing this topic as I see even here on Stack, there are so many questions on the topic already.

But I find myself in an interesting place and I'm hoping you can help.

High level Question: can SQL SERVER have the leeway to decide that a view should be wrapped in a ISOLATION LEVEL SNAPSHOT?

I know that sounds like a crazy question but I'm trying to exhaust all avenues per an issue I'm encountering.

I'm working with an application that runs 35 queries to retrieve data from another database via Link Server. The queries are simple selects against one table respectively. All DB operations are carried out against SQL SERVER, and retrieval code is ADO.NET/c#, etc.

34 of the queries work flawlessly - but there's this one bad apple, and for it, I get the transaction isolation level snapshot issue.

I've also tested data retrieval outside of the application and when I implement the below snippet on the "problem" query, I also get the issue:

```<code>using (var trans = conn.BeginTransaction(IsolationLevel.Snapshot))
</code>```

However, when I do NOT implement it on said query, all is well.
I've also tested this against the other queries - with and without "Shapshot" - and my results are predictable... With "Shapshot" in place, no queries process... When not implemented, all queries process...

My results suggest that the application is responsible for changing up the data retrieval strategy.

Per their knowledge base, I found this: Locking is handled by the database level (MS SQL Server/Oracle) and not by "us". Generally, locking is row level but the optimizer may choose something different

Unfortunately I don't have native access to the boiler-plate application code responsible for data retrieval.  I suspect that this particular query/table has one or more key words - either in the column or query/table naming - that trigger the application to use an alternate retrieval strategy.  Per the developer forums, I've asked of this is the case and I'm awaiting a reply...

Anyway back to their mention of the optimizer may choose something different- their optimizer, or perhaps the database optimizer? Can SQL SERVER be set up to make a "judgement call" ? Is the statement unclear or do I just not enough of SQL SERVER and its capabilities?

I know it seems like a crazy question but I really want to knock out all possible avenues here.
Thank you kindly for suspending your disbelieve and humoring that crazy post :)

答:
Apparently objects with the word "valuation" (perhaps because of the sensitive nature implied) cause the application to build the transaction. Once I changed the view name, the data returned to the client successfully.

So yes the application was/is the issue.

Body:
Folks - apologies for rehashing this topic as I see even here on Stack, there are so many questions on the topic already.

But I find myself in an interesting place and I'm hoping you can help.

High level Question: can SQL SERVER have the leeway to decide that a view should be wrapped in a ISOLATION LEVEL SNAPSHOT?

I know that sounds like a crazy question but I'm trying to exhaust all avenues per an issue I'm encountering.

I'm working with an application that runs 35 queries to retrieve data from another database via Link Server. The queries are simple selects against one table respectively. All DB operations are carried out against SQL SERVER, and retrieval code is ADO.NET/c#, etc.

34 of the queries work flawlessly - but there's this one bad apple, and for it, I get the transaction isolation level snapshot issue.

I've also tested data retrieval outside of the application and when I implement the below snippet on the "problem" query, I also get the issue:

using (var trans = conn.BeginTransaction(IsolationLevel.Snapshot))

However, when I do NOT implement it on said query, all is well.
I've also tested this against the other queries - with and without "Shapshot" - and my results are predictable... With "Shapshot" in place, no queries process... When not implemented, all queries process...

My results suggest that the application is responsible for changing up the data retrieval strategy.

Per their knowledge base, I found this: Locking is handled by the database level (MS SQL Server/Oracle) and not by "us". Generally, locking is row level but the optimizer may choose something different

Unfortunately I don't have native access to the boiler-plate application code responsible for data retrieval.  I suspect that this particular query/table has one or more key words - either in the column or query/table naming - that trigger the application to use an alternate retrieval strategy.  Per the developer forums, I've asked of this is the case and I'm awaiting a reply...

Anyway back to their mention of the optimizer may choose something different- their optimizer, or perhaps the database optimizer? Can SQL SERVER be set up to make a "judgement call" ? Is the statement unclear or do I just not enough of SQL SERVER and its capabilities?

I know it seems like a crazy question but I really want to knock out all possible avenues here.
Thank you kindly for suspending your disbelieve and humoring that crazy post :)


问:
php get ID from another page
I've got 2 pages...

```<code>   Page1 (transaction table page)
</code>```

The first page is a Transaction Table with  by $_GET to show all data from the user.
then, i  create a  $_POST, when clicked go to the "Refund page".

```<code>   Page1 (Refund page)
</code>```

In this page i've got a functions to give back the money to the user, but is not complete, because i dont have the Transaction ID that is required to ask a refund...

My question is... How can i get an ID from another page?...

答:
Send the data via POST, in hidden input.</p>

```<code><input type="hidden" name="transaction_id" value="TRXXX" />
</code>```

Title: php get ID from another page

Body:
I've got 2 pages...

   Page1 (transaction table page)

The first page is a Transaction Table with  by $_GET to show all data from the user.
then, i  create a  $_POST, when clicked go to the "Refund page".

   Page1 (Refund page)

In this page i've got a functions to give back the money to the user, but is not complete, because i dont have the Transaction ID that is required to ask a refund...

My question is... How can i get an ID from another page?...

Body:
Send the data via POST, in hidden input.

<input type="hidden" name="transaction_id" value="TRXXX" />


问:
Update Column of a Hive Table without using Sub query
This is a question regarding updating a new column in a Hive table.  Since I think Hive does not allow to update a column of an existing table using subqueries, I wanted to ask what will be the best way to achieve the following update operation.

I have the following two example tables:

Table A:

KeyId ValId Val

   W1    V1    10

   W2    V2    20

Table B:

KeyId ValId Val

   W1    V1    10

   W1    V1    30

   W1    V3    40

   W1    V4    50

   W2    V2    0

   W2    V2    50

   W2    V2    70

   W2    V4    80

I want to create another column in Table A, lets say avgVal that takes the KeyId and ValId in each row in Table A and takes the average of Val for those corresponding KeyId and ValId in Table B.  Thus, my final output table should look like:

Updated Table A:

KeyId ValId Val   avgVal

   W1    V1    10     20

   W2    V2    20     40

Please let me know if the question is not clear.

答:
It seems you are trying to get aggregate values in table A from table B. In that case you cannot have "val" column in table A because after aggregation which val from table B do you expect in table A?

Assuming that  was genuine mistake, and you remove "val" column from table a, your insert statement for table a should look like this:

```<code>insert into table table_a select keyid,valid,avg(val) from table_b group by keyid,valid
</code>```

Body:
It seems you are trying to get aggregate values in table A from table B. In that case you cannot have "val" column in table A because after aggregation which val from table B do you expect in table A?

Assuming that  was genuine mistake, and you remove "val" column from table a, your insert statement for table a should look like this:

insert into table table_a select keyid,valid,avg(val) from table_b group by keyid,valid


问:
Append Element Into Element
It might sound stupid , but i didn't find the correct way to achieve this . I want to create an element(in our example a div element) and add to it the textarea value . In my example it seems that the element is created but i cant embed it into the #notesPosition . I achieve this with JQuery but i`am not sure whats the best way to do it with pure Javascript.

var notesPositionToAdd = document.getElementById('notesPosition');
var notesTextareaBtn = document.getElementById('btnAddNotes');

notesTextareaBtn.addEventListener('click', function(e) {
  e.preventDefault();
  var notesTextarea = document.getElementById('addNotesTextarea').value;
  console.log(notesTextarea);
  var newEl = document.createElement('div');

  newEl.append(notesTextarea);
  newEl.className += " col-lg-2";
  console.log(newEl);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row ">
  <div class="col-lg-4 col-md-4 col-sm-4 col-12 offset-md-8 ">
    <form id="newNoteForm">
      <div class="form-group offset-lg-6">
        <i class="fa fa-times text-md-right " aria-hidden="true"></i>
        <label for="addNotesTextarea">Add notes !</label>
        <textarea class="form-control" id="addNotesTextarea" rows="3"></textarea>
        <input class="btn btn-danger btn-sm" type="submit" value="Add" id="btnAddNotes">
      </div>
    </form>
  </div>
</div>
<div class="row" id="notesPosition">

</div></code>```

答:
Hello

Check if this helps:

```<code>newEl.append(notesTextarea);
newEl.className += " col-lg-2";
console.log(newEl);
</code>```

to:

```<code>newEl.append(notesTextarea);
newEl.className += " col-lg-2";
notesPositionToAdd.append(newEl);
console.log(newEl);
</code>```

I hope it helped you!

Title: Append Element Into Element

Body:
It might sound stupid , but i didn't find the correct way to achieve this . I want to create an element(in our example a div element) and add to it the textarea value . In my example it seems that the element is created but i cant embed it into the #notesPosition . I achieve this with JQuery but i`am not sure whats the best way to do it with pure Javascript.

var notesPositionToAdd = document.getElementById('notesPosition');
var notesTextareaBtn = document.getElementById('btnAddNotes');

notesTextareaBtn.addEventListener('click', function(e) {
  e.preventDefault();
  var notesTextarea = document.getElementById('addNotesTextarea').value;
  console.log(notesTextarea);
  var newEl = document.createElement('div');

  newEl.append(notesTextarea);
  newEl.className += " col-lg-2";
  console.log(newEl);

});

    <form id="newNoteForm">

        Add notes !
        <textarea class="form-control" id="addNotesTextarea" rows="3"></textarea>
        <input class="btn btn-danger btn-sm" type="submit" value="Add" id="btnAddNotes">

    </form>

Body:
Hello

Check if this helps:

newEl.append(notesTextarea);
newEl.className += " col-lg-2";
console.log(newEl);

to:

newEl.append(notesTextarea);
newEl.className += " col-lg-2";
notesPositionToAdd.append(newEl);
console.log(newEl);

I hope it helped you!


Title: A numpy.where error?

Body:
I am using numpy.where to find the indices of some values. However, numpy.where yields the wrong indices as you can see below. Can somebody else explain me why I am getting such wrong indices please?

Thanks.

In [1]: d = np.random.rand(3,4)

In [2]: d
Out[2]:
array([[ 0.11694612,  0.95137658,  0.70099781,  0.06730629],
       [ 0.59989836,  0.52586768,  0.45387929,  0.76093495],
       [ 0.036541  ,  0.91714289,  0.2246452 ,  0.40785078]])

In [3]: np.where(d>0.9)
Out[3]: (array([0, 2]), array([1, 1]))

However,

In [4]: d[0,2]
Out[4]: 0.70099781000000005
In[5]: d[1,1]
Out[5]: 0.52586767999999995

Body:
The issue is that np.where returns a tuple of arrays with the indices in a given axis of where your condition holds. So, perhaps this makes it clearer:

>>> import numpy as np
>>> d = np.array([[ 0.11694612,  0.95137658,  0.70099781,  0.06730629],
...        [ 0.59989836,  0.52586768,  0.45387929,  0.76093495],
...        [ 0.036541  ,  0.91714289,  0.2246452 ,  0.40785078]])
>>> x, y = np.where(d > 0.9)
>>> d[x[0],y[0]]
0.95137658000000003
>>> d[x[1],y[1]]
0.91714289000000004

Note, this works well with the way numpy indexing works:

>>> d[x,y]
array([ 0.95137658,  0.91714289])

Note, this works with any dimensions:

>>> d.reshape(3,2,2)
array([[[ 0.11694612,  0.95137658],
        [ 0.70099781,  0.06730629]],

       [[ 0.59989836,  0.52586768],
        [ 0.45387929,  0.76093495]],

       [[ 0.036541  ,  0.91714289],
        [ 0.2246452 ,  0.40785078]]])
>>> d = d.reshape(3,2,2)
>>> x, y, z = np.where(d > 0.9)
>>> x
array([0, 2])
>>> y
array([0, 0])
>>> z
array([1, 1])
>>> d[x,y,z]
array([ 0.95137658,  0.91714289])


问:
Removing black borders on a vimeo iframe embed using CSS?
I am trying to find a way to hide the black strips across the top and bottom of a vimeo video. I thought there might be a way to cover them up with CSS.

I basically wanted to achieve what this person wanted to achieve with an image in the link below except I want to do it with an embedded video whilst keeping it repsonsive.

Removing black borders 4:3 on youtube thumbnails

Many thanks.

HTML

```<code><section class="d5-d13 c5-c13 b5-b13 a5-a13 video">

   <div class='embed-container'>
      <iframe src='http://player.vimeo.com/video/69252713' frameborder='0'
      webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
   </div>

</section>
</code>```

CSS

```<code>.embed-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0;
overflow: hidden;
max-width: 100%;
height: auto;
}

.embed-container iframe, .embed-container object, .embed-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</code>```

答:
I created a solution for this exact problem using a portion of this github post. Removing Black Bars. It doesn't change vimeo's background color but merely hides it from the viewport.

https://github.com/davatron5000/FitVids.js/issues/130

```<code>#myid {
  height: 112.6%;
}
</code>```

However, If you add a width using CSS "vw"(viewport width) it will size consistently on any monitor/device without showing the black background.   I added a margin so that the iframe will stay centered in the div once the width is shorter.

```<code>#myvimeoiframeID {
  height: 112%;
  width: 80vw;
  margin: 0 15% auto;
</code>```

}

In my parent container that holds the video, I added:

```<code>.embed-container {
   padding-bottom: 40.25%;
}
</code>```

This seems to make sure the video shows in the div. When I removed this section the video disappears but you can still here it play. So there is something that is pretty awesome with the padding-bottom: 40.25%;

I changed the vimeo embedded iframe code to have a height="100%".

So you can add a height to the iframe or you can do it in css. In order to control the height by css, I kept the base height in the iframe at 100% and any adjustments to that base height is through the css.

Body:
I am trying to find a way to hide the black strips across the top and bottom of a vimeo video. I thought there might be a way to cover them up with CSS.

I basically wanted to achieve what this person wanted to achieve with an image in the link below except I want to do it with an embedded video whilst keeping it repsonsive.

Removing black borders 4:3 on youtube thumbnails

Many thanks.

HTML

CSS

.embed-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0;
overflow: hidden;
max-width: 100%;
height: auto;
}

.embed-container iframe, .embed-container object, .embed-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

Body:
I created a solution for this exact problem using a portion of this github post. Removing Black Bars. It doesn't change vimeo's background color but merely hides it from the viewport.

https://github.com/davatron5000/FitVids.js/issues/130

#myid {
  height: 112.6%;
}

However, If you add a width using CSS "vw"(viewport width) it will size consistently on any monitor/device without showing the black background.   I added a margin so that the iframe will stay centered in the div once the width is shorter.

#myvimeoiframeID {
  height: 112%;
  width: 80vw;
  margin: 0 15% auto;

}

In my parent container that holds the video, I added:

.embed-container {
   padding-bottom: 40.25%;
}

This seems to make sure the video shows in the div. When I removed this section the video disappears but you can still here it play. So there is something that is pretty awesome with the padding-bottom: 40.25%;

I changed the vimeo embedded iframe code to have a height="100%".

So you can add a height to the iframe or you can do it in css. In order to control the height by css, I kept the base height in the iframe at 100% and any adjustments to that base height is through the css.


问:
ERR_ADDRESS_UNREACHABLE to opening my localhost in Chrome Android
I´m using the task BrowserSync of Grunt, this task launch my local project to the url "localhost:3000".

This works fine. But when I use the External url (http://192.168.1.129:3000) in my smartphone, I get the following error of my browser Chrome in Android:

```<code>ERR_ADDRESS_UNREACHABLE
</code>```

I don't understand this problem. You can see here my Gruntfile.js:

```<code>//Gruntfile.js
module.exports = function (grunt) {
  grunt.initConfig({

    //Watch task config
    watch: {

    },
    //BrowserSync
    browserSync: {
      default_options: {
        bsFiles: {
          src: [
            "css/*.css",
            "js/*.js",
            "*.html"
          ]
        },
        options: {
          watchTask: true,
          proxy: "tutorialmaterialize.dev"
          }
        }
      }

    });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-browser-sync');

 //Default task
 grunt.registerTask('default', ['browserSync', 'watch']);
};
</code>```

how can i fix this?, thanks you very much.

答:
your IP starts with 192.168 which means this is a private network.

Only devices on the private network can access it.

Your phone will need to be on the same network.

You can check this by checking the first 3 digits of your phone's IP - the first 3 digits must be the same - if they begin 192.168.1.NUMBER then its on the same network. If not then its on a different network and you need to get them on the same network.

If they are already on the same network then ensure that port 3000 is open on the firewall, both the router firewall AND the firewall running on the machine you are accessing.

Body:
I´m using the task BrowserSync of Grunt, this task launch my local project to the url "localhost:3000".

This works fine. But when I use the External url (http://192.168.1.129:3000) in my smartphone, I get the following error of my browser Chrome in Android:

ERR_ADDRESS_UNREACHABLE

I don't understand this problem. You can see here my Gruntfile.js:

//Gruntfile.js
module.exports = function (grunt) {
  grunt.initConfig({

    //Watch task config
    watch: {

    },
    //BrowserSync
    browserSync: {
      default_options: {
        bsFiles: {
          src: [
            "css/*.css",
            "js/*.js",
            "*.html"
          ]
        },
        options: {
          watchTask: true,
          proxy: "tutorialmaterialize.dev"
          }
        }
      }

    });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-browser-sync');

 //Default task
 grunt.registerTask('default', ['browserSync', 'watch']);
};

how can i fix this?, thanks you very much.


问:
PHP MySQL Group BY Having issue
Suppose I have a table like:

```<code>ID|Word |Reference
1 |Dog  |1
1 |Fish |2
1 |Sheep|3
2 |Dog  |4
2 |Fish |5
3 |Sheep|6
4 |Dog  |7
</code>```

I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:

```<code>SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'
</code>```

However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)

Basically the problem is the AND statement over multiple rows with the same ID.

UPDATE:

I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:

```<code>SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;
</code>```

Thanks

答:
Here's one way to do it by joining your table to itself.</p>

```<code>SELECT t1.id FROM `Table` t1
INNER JOIN `Table` t2 ON t1.id = t2.id
WHERE t1.word='Dog' AND t2.word='Sheep';
</code>```

Title: PHP MySQL Group BY Having issue

Body:
Suppose I have a table like:

ID|Word |Reference
1 |Dog  |1
1 |Fish |2
1 |Sheep|3
2 |Dog  |4
2 |Fish |5
3 |Sheep|6
4 |Dog  |7

I want to select all ID's that have the word Dog AND Sheep. So the result should be ID's: 1 and 2. I tried using this query:

SELECT ID FROM `Table` WHERE Word='Dog' OR Word='Fish' GROUP BY ID Having Word='Dog AND Word='Fish'

However, this AND in the Having clause makes me get 0 results. So, am I doing something wrong or is there another way to achieve wat I want based on MySQL query only (to optimize speed, since it has to search through many rows with the same setup as in the example above)

Basically the problem is the AND statement over multiple rows with the same ID.

UPDATE:

I need to get the reference for the ID's that where found. E.g. when the ID 1 and 2 are returned I need to know that ID 1 has reference 1 and 2. ID 2 has reference 3 and 4. Currently, I'm using this query:

SELECT ID FROM `Test` WHERE Word in ('Dog', 'Fish') GROUP BY ID HAVING  count(DISTINCT Word) = 2;

Thanks

Body:
Here's one way to do it by joining your table to itself.

SELECT t1.id FROM `Table` t1
INNER JOIN `Table` t2 ON t1.id = t2.id
WHERE t1.word='Dog' AND t2.word='Sheep';


问:
Umbraco 7.5.1 umbracoNaviHide
To be able to filter out items that should not be rendered with .Where("Visible") I need a property called umbracoNaviHide that returns true or false.

In earlier versions this was added to the Generic tab. However now you cant append to that tab anymore.

How would I accomplish hiding pages now?

Here's my foreach:

```<code> @foreach (var Area in Model.Content.Children.Where("Visible"))
 {
</code>```

Here's a statement about it. But I cant find any workaround.

Related Changes Summary - 7.4 beta - Option toCannot add properties to the "Generic properties" tab

Description - In the 7.4 beta it's not possible anymore to add
  properties to the "Generic properties" tab. I know this has been done
  because properties can be a bit hidden on that tab and usually are
  better on a separate tab. But there are situations where the
  properties are better on that tab.

答:
You can add that property as a true/false datatype to any tab. However, it's important to note that umbracoNaviHide does not do anything special it is just a magic string, that, when implemented as a true/false datatype, it works with

```<code>.Where("Visible").
</code>```

Personally I don't use it anymore.  If I need to cause items to be visible or not then I would name the property more specifically.  For example, it is often useful when implementing menus where you want some nodes to be visible but not others.  I generally have a Menu tab where one of the properties is a true/false type called Show in menu with an alias of showInMenu.

In code it could be something like below (I have used TypedContentAtXPath to get the parent node of a specific doc type. Of course there are various ways of doing this)

```<code>var homeNode = Umbraco.TypedContentAtXPath("//MyHomePageDocType").First();
var menuItems = homeNode.Children.Where(item=>item.GetPropertyValue<bool>("showInMenu"));

foreach(var item in menuItems)
{
    // Do your menu stuff here
}
</code>```

Hope that helps

J

Title: Umbraco 7.5.1 umbracoNaviHide

Body:
To be able to filter out items that should not be rendered with .Where("Visible") I need a property called umbracoNaviHide that returns true or false.

In earlier versions this was added to the Generic tab. However now you cant append to that tab anymore.

How would I accomplish hiding pages now?

Here's my foreach:

 @foreach (var Area in Model.Content.Children.Where("Visible"))
 {

Here's a statement about it. But I cant find any workaround.

Related Changes Summary - 7.4 beta - Option toCannot add properties to the "Generic properties" tab

Description - In the 7.4 beta it's not possible anymore to add
  properties to the "Generic properties" tab. I know this has been done
  because properties can be a bit hidden on that tab and usually are
  better on a separate tab. But there are situations where the
  properties are better on that tab.

Body:
You can add that property as a true/false datatype to any tab. However, it's important to note that umbracoNaviHide does not do anything special it is just a magic string, that, when implemented as a true/false datatype, it works with

.Where("Visible").

Personally I don't use it anymore.  If I need to cause items to be visible or not then I would name the property more specifically.  For example, it is often useful when implementing menus where you want some nodes to be visible but not others.  I generally have a Menu tab where one of the properties is a true/false type called Show in menu with an alias of showInMenu.

In code it could be something like below (I have used TypedContentAtXPath to get the parent node of a specific doc type. Of course there are various ways of doing this)

var homeNode = Umbraco.TypedContentAtXPath("//MyHomePageDocType").First();
var menuItems = homeNode.Children.Where(item=>item.GetPropertyValue<bool>("showInMenu"));

foreach(var item in menuItems)
{
    // Do your menu stuff here
}

Hope that helps

J


问:
How do I sort a table in Excel if it has cell references in it?
I have a table of data in excel in sheet 1 which references various different cells in many other sheets. When I try to sort or filter the sheet, the references change when the cell moves. However, I don't want to manually go into each cell and insert $ signs everywhere, because some of the references are continuous, and I may want to auto-fill later.

For example, one of my data columns uses sheet 2, column B 23:28, sheet 2, column C 1:15, and some others. The section of the column which uses sheet 2's column B is all in the same place before sorting, as are each of the other sections. If I insert $ signs, I would no longer be able to insert empty rows and use auto-fill for new data.

In summary, I would like a way to keep my cell references static without using $ signs, but only for sorting/filtering purposes. My current workaround involves copying the values of the table, pasting in an empty sheet, and then sorting. I hope there's a better way to do this.

答: Easy solution - copy from excel and paste into google sheets.  It copies all of your reference cells as absolute cells so you can begin from scratch.  Then sort and download back as an excel grid and reformat to your needs.  </p>


问:
Oracle query for selecting sampling of number values from a table
I have a data field in my Oracle DB Table whose datatype is NUMBER. I have tried a query below using order by.

```<code>SELECT Value
  FROM Table
 ORDER BY value;
</code>```

I am getting the result as

```<code>Value |
------|
1     |
1     |
2     |
2     |
3     |
3     |
4     |
4     |
5     |
5     |
6     |
6     |
</code>```

Instead I want a result as

```<code>Value |
------|
1     |
2     |
3     |
4     |
5     |
6     |
1     |
2     |
3     |
4     |
5     |
6     |
</code>```

答:
Please try this. I'm using ROW_NUMBER() to arrange the values based on their occurrences,</p>

```<code>SELECT VALUE
FROM (
  SELECT VALUE
    , ROW_NUMBER() OVER (PARTITION BY VALUE ORDER BY VALUE ASC) RNK
  FROM MY_TABLE
)
ORDER BY RNK
  , VALUE;
</code>```

Body:
I have a data field in my Oracle DB Table whose datatype is NUMBER. I have tried a query below using order by.

SELECT Value
  FROM Table
 ORDER BY value;

I am getting the result as

Value |
------|
1     |
1     |
2     |
2     |
3     |
3     |
4     |
4     |
5     |
5     |
6     |
6     |

Instead I want a result as

Value |
------|
1     |
2     |
3     |
4     |
5     |
6     |
1     |
2     |
3     |
4     |
5     |
6     |

Body:
Please try this. I'm using ROW_NUMBER() to arrange the values based on their occurrences,

SELECT VALUE
FROM (
  SELECT VALUE
    , ROW_NUMBER() OVER (PARTITION BY VALUE ORDER BY VALUE ASC) RNK
  FROM MY_TABLE
)
ORDER BY RNK
  , VALUE;


问:
What exactly is JSON?
I'm new to the web application domain. I have been watching some hot and eye-catching discussions regarding JSON everywhere.

Can someone briefly explain what JSON is? Do you have links to websites or forums that can help enlighten me about JSON?

答:
JSON (JavaScript Object Notation) is a data storage language, a bit like XML, but uses a more familiar "dictionary" style syntax and semantics. For example, I can store an address book in JSON:

```<code>[{"Name": "Jane", "Address": "28 Seventh St", "Age": 27},
 {"Name": "Steve", "Address": "14 Ninth St", "Age": 25}
]
</code>```

Notice that it looks a lot like a Python or JavaScript dictionary and list syntax. That's basically all it is: a serialisation of these six basic data types:

Object (or a "dictionary")

Array (or a "list")

String

Number (integer and float)

Boolean (true and false)

null

More information at json.org.

Note that although it has "JavaScript" in the name, it is really easy to read and write JSON data from any language, though the data structure is best represented in dynamic languages like JavaScript and Python. The website has a huge list of implementations in various languages.

Title: What exactly is JSON?

Body:
JSON (JavaScript Object Notation) is a data storage language, a bit like XML, but uses a more familiar "dictionary" style syntax and semantics. For example, I can store an address book in JSON:

[{"Name": "Jane", "Address": "28 Seventh St", "Age": 27},
 {"Name": "Steve", "Address": "14 Ninth St", "Age": 25}
]

Notice that it looks a lot like a Python or JavaScript dictionary and list syntax. That's basically all it is: a serialisation of these six basic data types:

Object (or a "dictionary")

Array (or a "list")

String

Number (integer and float)

Boolean (true and false)

null

More information at json.org.

Note that although it has "JavaScript" in the name, it is really easy to read and write JSON data from any language, though the data structure is best represented in dynamic languages like JavaScript and Python. The website has a huge list of implementations in various languages.


问:
Change part of a name of a file in CMD
I'm trying to change name files, but not all the name, but only the middle part.

For example, I have these files:

```<code>ABC_2018_100,
ABC_2018_101,
ABC_2018_102.
</code>```

And I want to change their names to:

```<code>ABC_2017_100,
ABC_2017_101,
ABC_2017_102.
</code>```

This is to say, I want to change just the '2017' of each one to '2018'.
I want to make in the most simple way, in the command prompt.

(In the real case, I have hundreds of files).

Remember, I just want to change the '2017'.

答:
In the command prompt you can do:</p>

```<code>for /f "delims=_ tokens=1-3" %i in ('dir /B') do rename %i_%j_%k %i_2017_%k
</code>```

Title: Change part of a name of a file in CMD

Body:
I'm trying to change name files, but not all the name, but only the middle part.

For example, I have these files:

ABC_2018_100,
ABC_2018_101,
ABC_2018_102.

And I want to change their names to:

ABC_2017_100,
ABC_2017_101,
ABC_2017_102.

This is to say, I want to change just the '2017' of each one to '2018'.
I want to make in the most simple way, in the command prompt.

(In the real case, I have hundreds of files).

Remember, I just want to change the '2017'.

Body:
In the command prompt you can do:

for /f "delims=_ tokens=1-3" %i in ('dir /B') do rename %i_%j_%k %i_2017_%k


答:
You can use the row_number to evaluate if an occurrence of a value is the first one, the second, and so on; an order by based on this value and then for the value in the table will do the work.

For example:

```<code>/* a test case */
with someTable(value) as (
    select 1 from dual union all
    select 2 from dual union all
    select 3 from dual union all
    select 4 from dual union all
    select 5 from dual union all
    select 6 from dual union all
    select 1 from dual union all
    select 2 from dual union all
    select 3 from dual union all
    select 4 from dual union all
    select 5 from dual union all
    select 6 from dual
)
/* the query */
select value
from someTable
order by row_number() over ( partition by value order by null), value
</code>```

How it works:

```<code>select value, row_number() over ( partition by value order by null) rowNumber
from someTable
order by row_number() over ( partition by value order by null), value
</code>```

gives:

```<code>     VALUE  ROWNUMBER
---------- ----------
         1          1
         2          1
         3          1
         4          1
         5          1
         6          1
         1          2
         2          2
         3          2
         4          2
         5          2
         6          2
</code>```

Title: Oracle query for selecting sampling of number values from a table

Body:
You can use the row_number to evaluate if an occurrence of a value is the first one, the second, and so on; an order by based on this value and then for the value in the table will do the work.

For example:

/* a test case */
with someTable(value) as (
    select 1 from dual union all
    select 2 from dual union all
    select 3 from dual union all
    select 4 from dual union all
    select 5 from dual union all
    select 6 from dual union all
    select 1 from dual union all
    select 2 from dual union all
    select 3 from dual union all
    select 4 from dual union all
    select 5 from dual union all
    select 6 from dual
)
/* the query */
select value
from someTable
order by row_number() over ( partition by value order by null), value

How it works:

select value, row_number() over ( partition by value order by null) rowNumber
from someTable
order by row_number() over ( partition by value order by null), value

gives:

     VALUE  ROWNUMBER
---------- ----------
         1          1
         2          1
         3          1
         4          1
         5          1
         6          1
         1          2
         2          2
         3          2
         4          2
         5          2
         6          2


问:
why argument random_state in cross_validation.train_test_split is integer not boolean
i need to know why argument random_state in cross_validation.train_test_split is integer not Boolean, since it's role is to flag random allocation or not?</p>

答:
random_state is not only a flag of randomness or not, but which random seed to use. If you choose random_state = 3 you will "randomly" split the dataset, but you are able to reproduce the same split each time. I.e. each call with the same dataset will yield the same split, which is not the case if you don't specify the random_state parameter.

The reason why I use the quotation marks, is that it is actually pseudo random.
Wikipedia explains pseudorandomness like this:

A pseudorandom process is a process that appears to be random but is
  not. Pseudorandom sequences typically exhibit statistical randomness
  while being generated by an entirely deterministic causal process.
  Such a process is easier to produce than a genuinely random one, and
  has the benefit that it can be used again and again to produce exactly
  the same numbers - useful for testing and fixing software.


问:
Retrofit2 and certificate pinning
In my android app I want to use certificate pinning when communicating with the server.
I saw this code that uses the keystore that is stored in the raw folder.

```<code>OkClient client = new RetrofitClientBuilder()
.pinCertificates(getResources(), R.raw.keystore, STORE_PASS)
.build()
</code>```

I'm using retrofit2 and OkHTTP3 and just saw this example:

```<code> OkHttpClient client = new OkHttpClient.Builder()
    .certificatePinner(new CertificatePinner.Builder()
            .add("publicobject.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
            .add("publicobject.com", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
            .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
            .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")
            .build())
    .build();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://api.nuuneoi.com/base/")
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();
</code>```

Does this later approach achieves the same result has the first one?

答:
I can say that this approach worked wonderfully for me.
Just make sure you add your endpoint correctly without the "https://" to the certificate pinner and it should work just fine. </p>

Title: Retrofit2 and certificate pinning

Body:
In my android app I want to use certificate pinning when communicating with the server.
I saw this code that uses the keystore that is stored in the raw folder.

OkClient client = new RetrofitClientBuilder()
.pinCertificates(getResources(), R.raw.keystore, STORE_PASS)
.build()

I'm using retrofit2 and OkHTTP3 and just saw this example:

 OkHttpClient client = new OkHttpClient.Builder()
    .certificatePinner(new CertificatePinner.Builder()
            .add("publicobject.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
            .add("publicobject.com", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
            .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
            .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")
            .build())
    .build();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://api.nuuneoi.com/base/")
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

Does this later approach achieves the same result has the first one?


问:
Markup Extension not working when WPF window is loaded through interop
I am opening WPF windows from a VB6 application as a part of a migration process to .NET. The windows are in a C# class library. I am getting a XamlParseException (stack trace below) that only occurs when the XAML window is loaded through a COM-exposed class. The .NET files for that are below.

I am not getting any issues loading the window from a .NET Console application using the classes below. But the code to load it from the console application is nearly identical minus a call to dispatcher.run() in the console app. So I'm not sure why interop is changing the behavior here.

The XamlParseException says "The method or operation is not implemented". The Stack trace is at the bottom of this post. It occurs in WindowA.xaml. I've commented above the line it occurs on. It's happening at <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=MainBrush}"/>

The Project Files

WindowWrapper.cs - Exposes the window to a VB6 application through COM

```<code>[ComVisible(true),
 ClassInterface(ClassInterfaceType.AutoDual)]
public class WindowWrapper
{
    //Note: This function is exposed to COM so that VB6 apps can call it.
    public void OpenWindow()
    {
        Dispatcher.CurrentDispatcher.Invoke(() =>
        {
            var window = new WindowA();
            window.ShowDialog();
        });

        //WPF will use the running Win32 dispatcher from VB6, so no need to call .Run() here
    }
}
</code>```

WindowA.xaml.cs

```<code>public partial class WindowA : Window
{
    public WindowA()
    {
        // This is sort of a hacky way of getting a xaml dependency to load and
        // getting Visual Studio to track the dependencies across projects
        // So we don't have to manually copy or include them in some way.
        // This reference to Localization manager will cause the proper assembly to load.
        var twc = typeof(LocalizationManager); // Telerik.Windows.Controls.dll

        InitializeComponent();
    }
}
</code>```

WindowA.xaml - Xaml file that fails to load when using COM Interop

```<code><Window x:Class="TelerikProject.WindowA"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
            mc:Ignorable="d"
            d:DesignHeight="300" d:DesignWidth="300">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!-- Telerik Windows8 Theme files -->
                <ResourceDictionary Source="pack://application:,,,/TelerikProject;component/Themes/System.Windows.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/TelerikProject;component/Themes/Telerik.Windows.Controls.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <telerik:RadButton Content="Test" Grid.Row="2" Width="75" Height="Auto" VerticalAlignment="Top" Margin="5"/>
        <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Bottom" Grid.Row="0" Margin="5">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">

                <!-- ERROR HAPPENS HERE. Probably isn't loading the MarkupExtension properly -->

                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=MainBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=BasicBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=AccentBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=StrongBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=ValidationBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=MarkerBrush}"/>
            </StackPanel>
        </Border>
    </Grid>
</Window>
</code>```

XamlParseException

```<code>at System.Windows.Baml2006.Baml2006SchemaContext.ResolveBamlType(BamlType bamlType, Int16 typeId)
at System.Windows.Baml2006.Baml2006SchemaContext.GetXamlType(Int16 typeId)
at System.Windows.Baml2006.Baml2006SchemaContext.GetProperty(Int16 propertyId, XamlType parentType)
at System.Windows.Baml2006.Baml2006Reader.Process_PropertyWithConverter()
at System.Windows.Baml2006.Baml2006Reader.Process_OneBamlRecord()
at System.Windows.Baml2006.Baml2006Reader.Process_BamlRecords()
at System.Windows.Baml2006.Baml2006Reader.Read()
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack\`1 stack, IStyleConnector styleConnector)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)

at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at TelerikProject.WindowA.InitializeComponent() in <pathToProject>\TelerikProject\WindowA.xaml:line 1
</code>```

Update

According to Rob Relyea's suggestion, I also tried calling this in code. The following works in both scenarios without error. I hope I'm recreating it right.

```<code>var rect = new Rectangle();
rect.Width = 20;
rect.Height = 20;

var ext = new Windows8ResourceExtension();
ext.ResourceKey = (Windows8ResourceKey)(new Windows8ResourceKeyTypeConverter().ConvertFrom("AccentBrush"));
var resourceReferenceExpression = ext.ProvideValue(new MockServiceProvider(rect));
var type = resourceReferenceExpression.GetType();
var mi = type.GetMethod("GetValue", BindingFlags.NonPublic | BindingFlags.Instance);
rect.Fill = (Brush)mi.Invoke(resourceReferenceExpression, new object[] { rect, Shape.FillProperty });
</code>```

And ProvideValue wanted an IServiceProvider as a parameter. I'm guessing this would feed it the element and property it's applying to, so I mocked the provider to give the rectangle I created. (Is this right?)

```<code>public class MockServiceProvider : IServiceProvider
{
    private Rectangle _rect;

    public MockServiceProvider(Rectangle rect)
    {
        _rect = rect;
    }

    public object GetService(Type serviceType)
    {
        if(serviceType.Name == "IProvideValueTarget")
        {
            return new MockProviderTarget(_rect, Rectangle.FillProperty);
        }
        else
        {
            throw new NotImplementedException();
        }
    }
}

public class MockProviderTarget : IProvideValueTarget
{
    private object _targetObject;
    private object _targetProperty;

    public MockProviderTarget(object targetObject, object targetProperty)
    {
        _targetObject = targetObject;
        _targetProperty = targetProperty;
    }

    public object TargetObject {
        get
        {
            return _targetObject;
        }
    }

    public object TargetProperty {
        get
        {
            return _targetProperty;
        }
    }
}
</code>```

答: Try to take the xaml out of this. Build code to create that markup extension instance and then call providevalue(). My guess is that will fail when you launch the app the same way?  Likely telerik's code relies on something that changes with your two launch techniques. </p>

Body:
I am opening WPF windows from a VB6 application as a part of a migration process to .NET. The windows are in a C# class library. I am getting a XamlParseException (stack trace below) that only occurs when the XAML window is loaded through a COM-exposed class. The .NET files for that are below.

I am not getting any issues loading the window from a .NET Console application using the classes below. But the code to load it from the console application is nearly identical minus a call to dispatcher.run() in the console app. So I'm not sure why interop is changing the behavior here.

The XamlParseException says "The method or operation is not implemented". The Stack trace is at the bottom of this post. It occurs in WindowA.xaml. I've commented above the line it occurs on. It's happening at <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=MainBrush}"/>

The Project Files

WindowWrapper.cs - Exposes the window to a VB6 application through COM

[ComVisible(true),
 ClassInterface(ClassInterfaceType.AutoDual)]
public class WindowWrapper
{
    //Note: This function is exposed to COM so that VB6 apps can call it.
    public void OpenWindow()
    {
        Dispatcher.CurrentDispatcher.Invoke(() =>
        {
            var window = new WindowA();
            window.ShowDialog();
        });

        //WPF will use the running Win32 dispatcher from VB6, so no need to call .Run() here
    }
}

WindowA.xaml.cs

public partial class WindowA : Window
{
    public WindowA()
    {
        // This is sort of a hacky way of getting a xaml dependency to load and
        // getting Visual Studio to track the dependencies across projects
        // So we don't have to manually copy or include them in some way.
        // This reference to Localization manager will cause the proper assembly to load.
        var twc = typeof(LocalizationManager); // Telerik.Windows.Controls.dll

        InitializeComponent();
    }
}

WindowA.xaml - Xaml file that fails to load when using COM Interop

<Window x:Class="TelerikProject.WindowA"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
            mc:Ignorable="d"
            d:DesignHeight="300" d:DesignWidth="300">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>

                <ResourceDictionary Source="pack://application:,,,/TelerikProject;component/Themes/System.Windows.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/TelerikProject;component/Themes/Telerik.Windows.Controls.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <telerik:RadButton Content="Test" Grid.Row="2" Width="75" Height="Auto" VerticalAlignment="Top" Margin="5"/>
        <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Bottom" Grid.Row="0" Margin="5">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">

                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=MainBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=BasicBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=AccentBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=StrongBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=ValidationBrush}"/>
                <Rectangle Width="20" Height="20" Fill="{telerik:Windows8Resource ResourceKey=MarkerBrush}"/>
            </StackPanel>
        </Border>
    </Grid>
</Window>

XamlParseException

at System.Windows.Baml2006.Baml2006SchemaContext.ResolveBamlType(BamlType bamlType, Int16 typeId)
at System.Windows.Baml2006.Baml2006SchemaContext.GetXamlType(Int16 typeId)
at System.Windows.Baml2006.Baml2006SchemaContext.GetProperty(Int16 propertyId, XamlType parentType)
at System.Windows.Baml2006.Baml2006Reader.Process_PropertyWithConverter()
at System.Windows.Baml2006.Baml2006Reader.Process_OneBamlRecord()
at System.Windows.Baml2006.Baml2006Reader.Process_BamlRecords()
at System.Windows.Baml2006.Baml2006Reader.Read()
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack\`1 stack, IStyleConnector styleConnector)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)

at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at TelerikProject.WindowA.InitializeComponent() in <pathToProject>\TelerikProject\WindowA.xaml:line 1

Update

According to Rob Relyea's suggestion, I also tried calling this in code. The following works in both scenarios without error. I hope I'm recreating it right.

var rect = new Rectangle();
rect.Width = 20;
rect.Height = 20;

var ext = new Windows8ResourceExtension();
ext.ResourceKey = (Windows8ResourceKey)(new Windows8ResourceKeyTypeConverter().ConvertFrom("AccentBrush"));
var resourceReferenceExpression = ext.ProvideValue(new MockServiceProvider(rect));
var type = resourceReferenceExpression.GetType();
var mi = type.GetMethod("GetValue", BindingFlags.NonPublic | BindingFlags.Instance);
rect.Fill = (Brush)mi.Invoke(resourceReferenceExpression, new object[] { rect, Shape.FillProperty });

And ProvideValue wanted an IServiceProvider as a parameter. I'm guessing this would feed it the element and property it's applying to, so I mocked the provider to give the rectangle I created. (Is this right?)

public class MockServiceProvider : IServiceProvider
{
    private Rectangle _rect;

    public MockServiceProvider(Rectangle rect)
    {
        _rect = rect;
    }

    public object GetService(Type serviceType)
    {
        if(serviceType.Name == "IProvideValueTarget")
        {
            return new MockProviderTarget(_rect, Rectangle.FillProperty);
        }
        else
        {
            throw new NotImplementedException();
        }
    }
}

public class MockProviderTarget : IProvideValueTarget
{
    private object _targetObject;
    private object _targetProperty;

    public MockProviderTarget(object targetObject, object targetProperty)
    {
        _targetObject = targetObject;
        _targetProperty = targetProperty;
    }

    public object TargetObject {
        get
        {
            return _targetObject;
        }
    }

    public object TargetProperty {
        get
        {
            return _targetProperty;
        }
    }
}


问:
Scroll Positioning for Overflow Container
How to set (horizontal) scroll position of overflow container?

JsFiddle:

http://jsfiddle.net/JeaffreyGilbert/FVrtx/

Preview:

答:
Use ScrollTo jQuery Plugin

Demo: http://jsfiddle.net/FVrtx/1/

```<code>$('.wrap').scrollTo('50%', 800);
</code>```

Body:
Use ScrollTo jQuery Plugin

Demo: http://jsfiddle.net/FVrtx/1/

$('.wrap').scrollTo('50%', 800);