问:
How to convert SQL Query result to PANDAS Data Structure?
Any help on this problem will be greatly appreciated.

So basically I want to run a query to my SQL database and store the returned data as Pandas data structure.

I have attached code for query.

I am reading the documentation on Pandas, but I have problem to identify the return type of my query.

I tried to print the query result, but it doesn't give any useful information.

Thanks!!!!

from sqlalchemy import create_engine

engine2 = create_engine('mysql://THE DATABASE I AM ACCESSING')
connection2 = engine2.connect()
dataid = 1022
resoverall = connection2.execute("
    SELECT
       sum(BLABLA) AS BLA,
       sum(BLABLABLA2) AS BLABLABLA2,
       sum(SOME_INT) AS SOME_INT,
       sum(SOME_INT2) AS SOME_INT2,
       100*sum(SOME_INT2)/sum(SOME_INT) AS ctr,
       sum(SOME_INT2)/sum(SOME_INT) AS cpc
    FROM daily_report_cooked
    WHERE campaign_id = '%s'",
    %dataid
)
```

So I sort of want to understand what's the format/datatype of my variable "resoverall" and how to put it with PANDAS data structure.

答:
Here's the code I use. Hope this helps.</p>

```<code>import pandas as pd
from sqlalchemy import create_engine

def getData():
  # Parameters
  ServerName = "my_server"
  Database = "my_db"
  UserPwd = "user:pwd"
  Driver = "driver=SQL Server Native Client 11.0"

  # Create the connection
  engine = create_engine('mssql+pyodbc://' + UserPwd + '@' + ServerName + '/' + Database + "?" + Driver)

  sql = "select * from mytable"
  df = pd.read_sql(sql, engine)
  return df

df2 = getData()
print(df2)
</code>```

Body:
Any help on this problem will be greatly appreciated.

So basically I want to run a query to my SQL database and store the returned data as Pandas data structure.

I have attached code for query.

I am reading the documentation on Pandas, but I have problem to identify the return type of my query.

I tried to print the query result, but it doesn't give any useful information.

Thanks!!!!

from sqlalchemy import create_engine

engine2 = create_engine('mysql://THE DATABASE I AM ACCESSING')
connection2 = engine2.connect()
dataid = 1022
resoverall = connection2.execute("
    SELECT
       sum(BLABLA) AS BLA,
       sum(BLABLABLA2) AS BLABLABLA2,
       sum(SOME_INT) AS SOME_INT,
       sum(SOME_INT2) AS SOME_INT2,
       100*sum(SOME_INT2)/sum(SOME_INT) AS ctr,
       sum(SOME_INT2)/sum(SOME_INT) AS cpc
    FROM daily_report_cooked
    WHERE campaign_id = '%s'",
    %dataid
)

So I sort of want to understand what's the format/datatype of my variable "resoverall" and how to put it with PANDAS data structure.

Body:
Here's the code I use. Hope this helps.

import pandas as pd
from sqlalchemy import create_engine

def getData():
  # Parameters
  ServerName = "my_server"
  Database = "my_db"
  UserPwd = "user:pwd"
  Driver = "driver=SQL Server Native Client 11.0"

  # Create the connection
  engine = create_engine('mssql+pyodbc://' + UserPwd + '@' + ServerName + '/' + Database + "?" + Driver)

  sql = "select * from mytable"
  df = pd.read_sql(sql, engine)
  return df

df2 = getData()
print(df2)


来源: stackexchange

问:
R Using loop to create 4 separate graphs of matrices (using lines function)
I am currently doesn't some testing and analysis of the Micahelis-Menten enzyme kinetics model. And what my code is attempting to do is to change the rate parameter th1 to 50% up to 200% of it's max value.

What I want to do though is I want to produce 4 separate graphs which show what happens to MM1, MM2, MM3, MM4 when changing the rate parameter.

The issue that I have is regarding the "q" loop and where I use the "if", "else if" and "else" functions found near the end of my code.

```<code>MM <- list(Pre = matrix(c(1,0,0,1,0,0,0,1,1,0,0,0), ncol=4), Post =
matrix(c(0,1,0,0,1,1,1,0,0,0,0,1),ncol=4), M= c("x1"=301,"x2"=120, "x3"=0,
"x4"=0), h = function (x, t, th = c(1.66e-3, 1e-4 , 0.1))
{
  with(as.list(c(x, th)), {
    return(c(th[1] * x1 * x2, th[2] * x3, th[3] * x3))
  })
})

gillespied1 <- function (N, T = 100, dt = 1, ...)
{
  tt = 0
  n = T%/%dt
  x = N$M
  S = t(N$Post - N$Pre)
  u = nrow(S)
  v = ncol(S)
  xmat = matrix(ncol = u, nrow = n)
  i = 1
  target = 0
  repeat {
    h = N$h(x, tt, ...)
    h0 = sum(h)
    if (h0 < 1e-10)
      tt = 1e+99
    else if (h0>3000){
      tt=1e+99
      xmat[i] <- xmat[i-1] ###
      i = i + 1
      if(i > n)
        return(ts(xmat, start = 0, deltat = dt)) ###
    }
    else tt = tt + rexp(1, h0)
    while (tt >= target) {
      xmat[i, ] = x
      i = i + 1
      target = target + dt
      if (i > n)
        return(ts(xmat, start = 0, deltat = dt))
    }
    j = sample(v, 1, prob = h)
    x = x + S[, j]
  }
}

 cl = rainbow(13)
    for(q in 1:4){
      plot(1, type="n", xlab="Time", ylab="Concentration of Substrate",xaxt='n',

    xlim=c(0, 1200), ylim=c(0, 310), main="Micahaelis-Menten:Changing Substrate rate parameter")
      for(i in seq(from=50, to=200, by=25)){
        MM$h = function (x, t, th = c(1.66e-3*(i/100), 1e-4, 0.1))
        {
          with(as.list(c(x, th)), {
            return(c(th[1] * x1 * x2, th[2] * x3, th[3] * x3))
          })
        }
        out = gillespied1(MM,T=300,dt=0.1)
        MM1 <- out[,1]
        MM2 = out[,2]
        MM3 = out[,3]
        MM4 = out[,4]
        for (j in 1:40)  {
          out = gillespied1(MM, T=300, dt=0.1)
          MM1 = cbind(MM1,out[,1])
          MM2 = cbind(MM2,out[,2])
          MM3 = cbind(MM3,out[,3])
          MM4 = cbind(MM4,out[,4])
        }
        a =matrix(rowMeans(MM1))
        b = matrix(rowMeans(MM2))
        c = matrix(rowMeans(MM3))
        d = matrix(rowMeans(MM4))
        if (q = 1) {
          lines(a, lwd="1.5", col =cl[2*((i/25)-1)-1])
        } else if ( q=2) {
          lines(b, lwd="1.5", col =cl[2*((i/25)-1)-1])
        } else if ( q=3) {
          lines(c, lwd="1.5", col =cl[2*((i/25)-1)-1])
        } else
          lines(d, lwd="1.5", col =cl[2*((i/25)-1)-1])
      }
      axis(side = 1, at = (0:300)*10 , labels = 0:300)
      legend("topright", legend=c("50%","75%","100%","125%","150%","175%", "200%"), lty =c(rep(1)), lwd=c(rep(1)), title ="% of original substrate rate parameter", col=cl[seq(1,13,2)], cex=0.4)
    }
</code>```

I keep getting this error

```<code>Error: unexpected '}' in "}"
</code>```

but I can't tell why.

If my code was working perfectly I should end up with 4 graphs, each graph containing 7 lines.

Any help would be amazing. Thanks.

答:
From the link:

Relational Operators

Description

Binary operators which allow the comparison of values in atomic vectors.

Usage

```<code>x == y
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently doesn't some testing and analysis of the Micahelis-Menten enzyme kinetics model. And what my code is attempting to do is to change the rate parameter th1 to 50% up to 200% of it's max value.

What I want to do though is I want to produce 4 separate graphs which show what happens to MM1, MM2, MM3, MM4 when changing the rate parameter.

The issue that I have is regarding the "q" loop and where I use the "if", "else if" and "else" functions found near the end of my code.

MM <- list(Pre = matrix(c(1,0,0,1,0,0,0,1,1,0,0,0), ncol=4), Post =
matrix(c(0,1,0,0,1,1,1,0,0,0,0,1),ncol=4), M= c("x1"=301,"x2"=120, "x3"=0,
"x4"=0), h = function (x, t, th = c(1.66e-3, 1e-4 , 0.1))
{
  with(as.list(c(x, th)), {
    return(c(th[1] * x1 * x2, th[2] * x3, th[3] * x3))
  })
})

gillespied1 <- function (N, T = 100, dt = 1, ...)
{
  tt = 0
  n = T%/%dt
  x = N$M
  S = t(N$Post - N$Pre)
  u = nrow(S)
  v = ncol(S)
  xmat = matrix(ncol = u, nrow = n)
  i = 1
  target = 0
  repeat {
    h = N$h(x, tt, ...)
    h0 = sum(h)
    if (h0 < 1e-10)
      tt = 1e+99
    else if (h0>3000){
      tt=1e+99
      xmat[i] <- xmat[i-1] ###
      i = i + 1
      if(i > n)
        return(ts(xmat, start = 0, deltat = dt)) ###
    }
    else tt = tt + rexp(1, h0)
    while (tt >= target) {
      xmat[i, ] = x
      i = i + 1
      target = target + dt
      if (i > n)
        return(ts(xmat, start = 0, deltat = dt))
    }
    j = sample(v, 1, prob = h)
    x = x + S[, j]
  }
}

 cl = rainbow(13)
    for(q in 1:4){
      plot(1, type="n", xlab="Time", ylab="Concentration of Substrate",xaxt='n',

    xlim=c(0, 1200), ylim=c(0, 310), main="Micahaelis-Menten:Changing Substrate rate parameter")
      for(i in seq(from=50, to=200, by=25)){
        MM$h = function (x, t, th = c(1.66e-3*(i/100), 1e-4, 0.1))
        {
          with(as.list(c(x, th)), {
            return(c(th[1] * x1 * x2, th[2] * x3, th[3] * x3))
          })
        }
        out = gillespied1(MM,T=300,dt=0.1)
        MM1 <- out[,1]
        MM2 = out[,2]
        MM3 = out[,3]
        MM4 = out[,4]
        for (j in 1:40)  {
          out = gillespied1(MM, T=300, dt=0.1)
          MM1 = cbind(MM1,out[,1])
          MM2 = cbind(MM2,out[,2])
          MM3 = cbind(MM3,out[,3])
          MM4 = cbind(MM4,out[,4])
        }
        a =matrix(rowMeans(MM1))
        b = matrix(rowMeans(MM2))
        c = matrix(rowMeans(MM3))
        d = matrix(rowMeans(MM4))
        if (q = 1) {
          lines(a, lwd="1.5", col =cl[2*((i/25)-1)-1])
        } else if ( q=2) {
          lines(b, lwd="1.5", col =cl[2*((i/25)-1)-1])
        } else if ( q=3) {
          lines(c, lwd="1.5", col =cl[2*((i/25)-1)-1])
        } else
          lines(d, lwd="1.5", col =cl[2*((i/25)-1)-1])
      }
      axis(side = 1, at = (0:300)*10 , labels = 0:300)
      legend("topright", legend=c("50%","75%","100%","125%","150%","175%", "200%"), lty =c(rep(1)), lwd=c(rep(1)), title ="% of original substrate rate parameter", col=cl[seq(1,13,2)], cex=0.4)
    }

I keep getting this error

Error: unexpected '}' in "}"

but I can't tell why.

If my code was working perfectly I should end up with 4 graphs, each graph containing 7 lines.

Any help would be amazing. Thanks.

Body:
From the link:

Relational Operators

Description

Binary operators which allow the comparison of values in atomic vectors.

Usage

x == y


问:
How to add listener to UnityEvent in prefab programatically
I read about UnityEvent and am trying to implement it.

I have a "GameController.cs" script, attached to a GameObject "ScriptsHolder", and a "target.cs" script attached to a Prefab GameObject called "target".

"target" is not in the scene on startup: I initiate multiple targets at a certain point, which are renamed to "target0", "target1", ...

When a target receives damage, I want it to send its name to GameController.cs, which has a void that destroys that object.
Here's what I did:

target.cs:

```<code> using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Events;

 public class target : MonoBehaviour {

      public UnityEvent damageEvent;

     void Damage(float damage)
     {
         damageEvent.Invoke();
     }
 }
</code>```

Next, I click on my target Prefab and in the inspector, I try to add "ScriptsHolder" to the Damage Event. Here's my problem: I can't drop the ScriptsHolder in the Damage Event. Did some testing, and the reason for this appears to be the fact that "target" is not yet in my scene.

So I read about adding a listener instead, but I can't figure out how to do this.

Here what I have in "GameController.cs":

```<code> using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Events;
 public class GameController : MonoBehaviour {
 UnityEvent damageEvent;
 void Awake()
 {
     damageEvent.AddListener(targetReceivedDamage);
 }
 void targetReceivedDamage()
 { // do some stuff }
 }
</code>```

But that doesn't work. What am I doing wrong? Or how can I add the ScriptsHolder to the Damage Event even though "target" isn't inside the scene?

Any help is much appreciated!

答:
You need to add listener when you instantiate target object. For example:

Change your prefab declaration to Target type and reassign target prefab in the inspector.

```<code>public Target targetPrefab;
</code>```

then

```<code>Target target = Instantiate(targetPrefab);

target.damageEvent.AddListener(targetReceivedDamage);
</code>```

Hope this helps :)

Body:
I read about UnityEvent and am trying to implement it.

I have a "GameController.cs" script, attached to a GameObject "ScriptsHolder", and a "target.cs" script attached to a Prefab GameObject called "target".

"target" is not in the scene on startup: I initiate multiple targets at a certain point, which are renamed to "target0", "target1", ...

When a target receives damage, I want it to send its name to GameController.cs, which has a void that destroys that object.
Here's what I did:

target.cs:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Events;

 public class target : MonoBehaviour {

      public UnityEvent damageEvent;

     void Damage(float damage)
     {
         damageEvent.Invoke();
     }
 }

Next, I click on my target Prefab and in the inspector, I try to add "ScriptsHolder" to the Damage Event. Here's my problem: I can't drop the ScriptsHolder in the Damage Event. Did some testing, and the reason for this appears to be the fact that "target" is not yet in my scene.

So I read about adding a listener instead, but I can't figure out how to do this.

Here what I have in "GameController.cs":

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Events;
 public class GameController : MonoBehaviour {
 UnityEvent damageEvent;
 void Awake()
 {
     damageEvent.AddListener(targetReceivedDamage);
 }
 void targetReceivedDamage()
 { // do some stuff }
 }

But that doesn't work. What am I doing wrong? Or how can I add the ScriptsHolder to the Damage Event even though "target" isn't inside the scene?

Any help is much appreciated!

Body:
You need to add listener when you instantiate target object. For example:

Change your prefab declaration to Target type and reassign target prefab in the inspector.

public Target targetPrefab;

then

Target target = Instantiate(targetPrefab);

target.damageEvent.AddListener(targetReceivedDamage);

Hope this helps :)


问:
How to compare through complete JSON and bind it to another JSON

I have a JSON which looks like this:-

```<code>{
    "property" : value,
    "property" : value,
    "subProperty" : {
        "subProperty1" : {
            "subProperty1a" : {
                "property" : value,
                "property" : value
            },
            "subProperty1b" : {
                "property" : ["1", "2"],
                "property" : value
            },
            .....
        },
        "subProperty2" : {
            "subProperty2a" : {
                "property" : value,
                "property" : value
            },
            "subProperty2b" : {
                "property" : value,
                "property" : value
            },
            .....
        },
        "subProperty3" : {
            "subProperty3a" : {
                "property" : value,
                "property" : value
            },
            "subProperty3b" : {
                "property" : value,
                "property" : value
            },
            .....
        }
    }
}
</code>```

This JSON can have any number of fields added later on in any position.What I want is when I add new fields, then I want to compare old JSON with new JSON. If any propert is missing, bind that property with new one.

Right now I am using following code to achieve this:-

```<code>    scope.tempObj = {};
    scope.findObjectByLabel = function(obj1, obj2, obj3){
                        for(var i in obj1)
                            {
                                obj3[i] = obj2[i];
                                if(obj2[i] == undefined)
                                {
                                    obj3[i] = obj1[i];
                                }
                                if(typeof(obj1[i]) == 'object')
                                {
                                    scope.findObjectByLabel(obj1[i], obj2[i],obj3[i]);
                                }
                            }
                            return obj3;
                    }

scope.newJSON = scope.findObjectByLabel(scope.newJSON, scope.oldJSON ,scope.tempObj);
</code>```

But the above code can only compare through one level. Can any one suggest me any improvement on the above code so that it can compare through entire JSON.

答:
You can use this _.merge polyfill from GitHub by @anvk.

function mergeDeep(out) {
  out = out || {};

  for (var i = 1, len = arguments.length; i < len; ++i) {
    var obj = arguments[i];

    if (!obj) {
      continue;
    }

    for (var key in obj) {
      if (!obj.hasOwnProperty(key)) {
        continue;
      }

      // based on https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
      if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
        out[key] = mergeDeep(out[key], obj[key]);
        continue;
      }

      out[key] = obj[key];
    }
  }

  return out;
};

var merged = mergeDeep({a: 1}, { b : { c: { d: { e: 12345}}}});
console.dir(merged); // { a: 1, b: { c: { d: { e: 12345 } } } }```

Body:
I have a JSON which looks like this:-

{
    "property" : value,
    "property" : value,
    "subProperty" : {
        "subProperty1" : {
            "subProperty1a" : {
                "property" : value,
                "property" : value
            },
            "subProperty1b" : {
                "property" : ["1", "2"],
                "property" : value
            },
            .....
        },
        "subProperty2" : {
            "subProperty2a" : {
                "property" : value,
                "property" : value
            },
            "subProperty2b" : {
                "property" : value,
                "property" : value
            },
            .....
        },
        "subProperty3" : {
            "subProperty3a" : {
                "property" : value,
                "property" : value
            },
            "subProperty3b" : {
                "property" : value,
                "property" : value
            },
            .....
        }
    }
}

This JSON can have any number of fields added later on in any position.What I want is when I add new fields, then I want to compare old JSON with new JSON. If any propert is missing, bind that property with new one.

Right now I am using following code to achieve this:-

    scope.tempObj = {};
    scope.findObjectByLabel = function(obj1, obj2, obj3){
                        for(var i in obj1)
                            {
                                obj3[i] = obj2[i];
                                if(obj2[i] == undefined)
                                {
                                    obj3[i] = obj1[i];
                                }
                                if(typeof(obj1[i]) == 'object')
                                {
                                    scope.findObjectByLabel(obj1[i], obj2[i],obj3[i]);
                                }
                            }
                            return obj3;
                    }

scope.newJSON = scope.findObjectByLabel(scope.newJSON, scope.oldJSON ,scope.tempObj);

But the above code can only compare through one level. Can any one suggest me any improvement on the above code so that it can compare through entire JSON.


问:
PhpStorm choking and freezing while editing code
I have experienced sudden drop in PhpStorm performance. IDE which was performing very well (without any noticeable signs of delay in response) started to be sluggish and freeze for a fraction of a second every time any autocomplete was performed.

Despite available 16GB memory (and increasing max memory for program in PhpStorm settings up to 2 GB) IDE does not use any of the additional memory and still freezes every few second. None of available suggestions all over Internet regarding disabling unnecessary plugins, clearing indexes or changing memory were successful.  Reducing highlighting level has no effect on described issues.

Question: is there any other option I could do to restore normal performance without disabling some vital IDE functionalities?

答:
I've experienced those kind of performance problems in the past. Options I've used are

Increase heap memory to 4gb

Exclude folders from indexing

Disable some plugins (last time the problem was with PHP Inspections plugin)


问:
PL/SQL How to compare an expression in a trigger?
I'm trying to output a message each time a student's new GPA is lower than their old GPA by 1 or more.

```<code>Create or Replace TRIGGER AUGPA
  after update on students
  for each row -- or should I put 'for GPA' the column name
begin
  if (:new.gpa - :old.gpa) >= 1 -- How do I compare these expressions? I get an error here.
    THEN
      dbms_output.put_line ('Old GPA is lower than previous GPA by at least 1 point.')
  End if;
End;
/
</code>```

Students Table

```<code>SNUM  SNAME  STANDING  MAJOR  GPA  MAJORGPA
****  *****  ********  *****  ***  ********
121   Liz      2       FIN   2.8     3.2
</code>```

答:
Follow the below steps and this code to get the desired results.</p>

```<code>Create or Replace TRIGGER AUGPA
  after update on students
  for each row
begin
  if :new.gpa - :old.gpa  >= 1
    THEN
      dbms_output.put_line ('Old GPA is lower than current GPA by at least 1 point.');
  End if;
End;
/

set serveroutput on;
update Students set gpa  = gpa + 1 ;
commit;
</code>```

Body:
I'm trying to output a message each time a student's new GPA is lower than their old GPA by 1 or more.

Create or Replace TRIGGER AUGPA
  after update on students
  for each row -- or should I put 'for GPA' the column name
begin
  if (:new.gpa - :old.gpa) >= 1 -- How do I compare these expressions? I get an error here.
    THEN
      dbms_output.put_line ('Old GPA is lower than previous GPA by at least 1 point.')
  End if;
End;
/

Students Table

SNUM  SNAME  STANDING  MAJOR  GPA  MAJORGPA
****  *****  ********  *****  ***  ********
121   Liz      2       FIN   2.8     3.2

Body:
Follow the below steps and this code to get the desired results.

Create or Replace TRIGGER AUGPA
  after update on students
  for each row
begin
  if :new.gpa - :old.gpa  >= 1
    THEN
      dbms_output.put_line ('Old GPA is lower than current GPA by at least 1 point.');
  End if;
End;
/

set serveroutput on;
update Students set gpa  = gpa + 1 ;
commit;


问:
Command prompt won't change directory to another drive
I'm trying to compile some java (learning java currently), and to do so I need to change command-prompt's directory.

```<code>C:\...\Admin> cd D:\Docs\Java
C:\...\Admin> cd
C:\...\Admin
</code>```

It doesn't change the directory. I try again using quotes:

```<code>C:\...\Admin> cd "D:\Docs\Java"
C:\...\Admin>
</code>```

Again it doesn't change the directory. What am I doing wrong?

答:
you should use a /d before path as below :</p>

```<code>cd /d e:\
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to compile some java (learning java currently), and to do so I need to change command-prompt's directory.

C:\...\Admin> cd D:\Docs\Java
C:\...\Admin> cd
C:\...\Admin

It doesn't change the directory. I try again using quotes:

C:\...\Admin> cd "D:\Docs\Java"
C:\...\Admin>

Again it doesn't change the directory. What am I doing wrong?

Body:
you should use a /d before path as below :

cd /d e:\


问:
How to add a blurred drop shadow to a button?
I need to add blurred drop shadow to my button:

I tried to create background with layer-list xml drawable, but it not looks like blur.

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#007879E8" />

        </shape>
    </item>
    //////   10 more items
        <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#177879E8" />

        </shape>
    </item>

    <!-- Background -->
    <item>
        <shape>
            <corners android:radius="45dp" />
            <stroke
                android:width="2dp"
                android:color="@color/main_purple_text_color" />
        </shape>
    </item>

</layer-list>
</code>```

Also i tried to use background element behind button with blured png but it uses to many resources and i cannot create selector to change background on hover or click.

I need to have single background file for button and use selector to change blur and gradient on hover/click.
Any ideas how to achieve such effect with Android SDK ?

UPDATE 1

Thanks everybody for answers, but I'm not asking how to create gradient. I've already done this. I need to create blurred drop-shadow.

答:
Well i found the solution: we need to create 9.png with blurred drop-shadow via this generator and pass it to drawable layer-list that contain button background gradient:

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/blurred_9_path_png" />
    <item>
        <shape android:shape="rectangle" android:padding="10dp">
            <corners android:radius="45dp" />
            <gradient
                android:angle="45"
                android:endColor="@color/facebook_btn_fill_grad2"
                android:startColor="@color/facebook_btn_fill_grad1"
                android:type="linear" />
            <padding
                android:bottom="0dp"
                android:left="0dp"
                android:right="0dp"
                android:top="0dp" />
        </shape>
    </item>

</layer-list>
</code>```

After that we can use such drawables with different 9.path blurred shadow to create selector.

Body:
I need to add blurred drop shadow to my button:

I tried to create background with layer-list xml drawable, but it not looks like blur.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#007879E8" />

        </shape>
    </item>
    //////   10 more items
        <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#177879E8" />

        </shape>
    </item>

    <item>
        <shape>
            <corners android:radius="45dp" />
            <stroke
                android:width="2dp"
                android:color="@color/main_purple_text_color" />
        </shape>
    </item>

</layer-list>

Also i tried to use background element behind button with blured png but it uses to many resources and i cannot create selector to change background on hover or click.

I need to have single background file for button and use selector to change blur and gradient on hover/click.
Any ideas how to achieve such effect with Android SDK ?

UPDATE 1

Thanks everybody for answers, but I'm not asking how to create gradient. I've already done this. I need to create blurred drop-shadow.

Body:
Well i found the solution: we need to create 9.png with blurred drop-shadow via this generator and pass it to drawable layer-list that contain button background gradient:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/blurred_9_path_png" />
    <item>
        <shape android:shape="rectangle" android:padding="10dp">
            <corners android:radius="45dp" />
            <gradient
                android:angle="45"
                android:endColor="@color/facebook_btn_fill_grad2"
                android:startColor="@color/facebook_btn_fill_grad1"
                android:type="linear" />
            <padding
                android:bottom="0dp"
                android:left="0dp"
                android:right="0dp"
                android:top="0dp" />
        </shape>
    </item>

</layer-list>

After that we can use such drawables with different 9.path blurred shadow to create selector.


问:
Using aliases when importing from other modules in elm
I wonder if there is a way to import something from a module and rename it straight away.

Here’s what I can do in a JavaScript file assuming that "my-module" exports myFunction and somethingElse:

```<code>import { myFunction as myRenamedFunction, somethingElse } from "my-module";
</code>```

Here’s what I’m trying to like to do in Elm, but this produces a syntax error:

```<code>import MyModule exposing (myFunction as myRenamedFunction, somethingElse)
</code>```

答:
No, there is no syntax for renaming imports as of Elm 0.18. The closest you can get is to declare a function like this:

import MyModule exposing (somethingElse)

myRenamedFunction = MyModule.myFunction
```

Body:
I wonder if there is a way to import something from a module and rename it straight away.

Here’s what I can do in a JavaScript file assuming that "my-module" exports myFunction and somethingElse:

import { myFunction as myRenamedFunction, somethingElse } from "my-module";

Here’s what I’m trying to like to do in Elm, but this produces a syntax error:

import MyModule exposing (myFunction as myRenamedFunction, somethingElse)


问:
How to store variable value after clicking "Submit"?
Solution:

```<code><?php
    $typeAnag = filter_input ( INPUT_GET, 'typeAnag', FILTER_SANITIZE_STRING );
    $filter = filter_input ( INPUT_GET, 'filter', FILTER_SANITIZE_STRING );
    ?>

    <nav class="navbar navbar-light bg-light">
        <form class="form-inline">
            <button class="btn btn-sm align-middle btn-outline-secondary"
                type="submit" name="typeAnag" value="all">All</button>
        </form>

        <form class="form-inline pull-xs-right" >
            <input type="filter" name="filter" id="filter"
                class="form-control mr-sm-2" placeholder="Filter...">
<input type="hidden" name="typeAnag" value="<?=$typeAnag?>">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Filtra</button>
        </form>
    </nav>
</code>```

I have this php page with two forms:

```<code><?php
$typeAnag = filter_input ( INPUT_GET, 'typeAnag', FILTER_SANITIZE_STRING );
$filter = filter_input ( INPUT_GET, 'filter', FILTER_SANITIZE_STRING );
?>

<nav class="navbar navbar-light bg-light">
    <form class="form-inline">
        <button class="btn btn-sm align-middle btn-outline-secondary"
            type="submit" name="typeAnag" value="all">All</button>
    </form>

    <form class="form-inline pull-xs-right" >
        <input type="filter" name="filter" id="filter"
            class="form-control mr-sm-2" placeholder="Filter...">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Filtra</button>
    </form>
</nav>
</code>```

When I click the submit form "typeAnag" I obtain in the url ../index.php?typeAnag=all and for the form "filter" ../index.php?filter=word

But I would like to store the value typeAnag=all and composite my url like this: ../index.php?typeAnag=all&filter=word

But when I click the form, I lost the variable value of the previous submit.

I try to use $_SESSION but doesn't work.

Any help would be appreciated

答: Problem is when u click on second form data in url will be contain just elements from that form not from first form so if u want in second form get information about typeAnag u need to create hidden input in second form....</p>

Body:
Solution:

<?php
    $typeAnag = filter_input ( INPUT_GET, 'typeAnag', FILTER_SANITIZE_STRING );
    $filter = filter_input ( INPUT_GET, 'filter', FILTER_SANITIZE_STRING );
    ?>

        <form class="form-inline">
            <button class="btn btn-sm align-middle btn-outline-secondary"
                type="submit" name="typeAnag" value="all">All</button>
        </form>

        <form class="form-inline pull-xs-right" >
            <input type="filter" name="filter" id="filter"
                class="form-control mr-sm-2" placeholder="Filter...">
<input type="hidden" name="typeAnag" value="<?=$typeAnag?>">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Filtra</button>
        </form>

I have this php page with two forms:

<?php
$typeAnag = filter_input ( INPUT_GET, 'typeAnag', FILTER_SANITIZE_STRING );
$filter = filter_input ( INPUT_GET, 'filter', FILTER_SANITIZE_STRING );
?>

    <form class="form-inline">
        <button class="btn btn-sm align-middle btn-outline-secondary"
            type="submit" name="typeAnag" value="all">All</button>
    </form>

    <form class="form-inline pull-xs-right" >
        <input type="filter" name="filter" id="filter"
            class="form-control mr-sm-2" placeholder="Filter...">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Filtra</button>
    </form>

When I click the submit form "typeAnag" I obtain in the url ../index.php?typeAnag=all and for the form "filter" ../index.php?filter=word

But I would like to store the value typeAnag=all and composite my url like this: ../index.php?typeAnag=all&filter=word

But when I click the form, I lost the variable value of the previous submit.

I try to use $_SESSION but doesn't work.

Any help would be appreciated


问:
does not allow data from static types
i m making an API in .net , that will communicate with its client with xml data.
client software can be in any language php,asp.net etc.
what is the best way to develop such API,
i was trying to use the .net webservices', but [webmethods] does not allow non static data,
and in my API there are lots of things that will work only with the non static data.
can you please suggest any solution to this problem, ?
any way to develpop it without using .net webservies?</p>

答:
Based on the comments, you actually mean "does not allow static classes". So... Don't SE static class. I would suggest moving those static properties into a default instance:

```<code>class Foo {
    private static readonly Foo @default =
        new Foo();
    public static Foo Default { get { return @default; } }
    public int A { get; set; }
    public string B { get; set; }

}
</code>```

And treat the Foo.Default object's properties like the existing static ones.

Note that with XmlSerializer you need a public ctor, hence I haven't called this a singleton, as strictly speaking it won't be.

ContentLicense: CC BY-SA 2.5

Title: does not allow data from static types

Body:
Based on the comments, you actually mean "does not allow static classes". So... Don't SE static class. I would suggest moving those static properties into a default instance:

class Foo {
    private static readonly Foo @default =
        new Foo();
    public static Foo Default { get { return @default; } }
    public int A { get; set; }
    public string B { get; set; }

}

And treat the Foo.Default object's properties like the existing static ones.

Note that with XmlSerializer you need a public ctor, hence I haven't called this a singleton, as strictly speaking it won't be.


问:
CORS Error : Deleting a record of a given ID using REST API
In my code base, I am making use of REST APIs to delete a record for a specific ID. I subscribe to the delete service as below :

```<code>deleteScheduleViewService(id : number) : Observable<any> {
    let url = `http://localhost:8080/schedules/${id}`;
    return this.http.delete(url)
    .map(response => response.json() as any);
}
</code>```

My REST endpoint in Java is as follows :

```<code>@RequestMapping(value = "/schedules/{id}", method = RequestMethod.DELETE)
public void deleteSchedules(@PathVariable("id") Long id)
{
    scheduleServiceManager.deleteSchedule(id);
}
</code>```

My key problem is how do I match an arbitrary ID with that of the delete endpoint URL. Do I put in a sort of regex expression and then extract the ID?

Edits

I get the following error upon trying to access the REST endpoint:

```<code>Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8090' is therefore not allowed access. The response had HTTP status code 405.
</code>```

It seems like I am getting the Cross Origin Resource Sharing Error now.

答:
To solve "Access-Control-Allow-Origin", add CrossOrigin to your controller class. For example:</p>

```<code>@CrossOrigin("*")
@Controller
public class YourSuperController
</code>```

Body:
In my code base, I am making use of REST APIs to delete a record for a specific ID. I subscribe to the delete service as below :

deleteScheduleViewService(id : number) : Observable<any> {
    let url = `http://localhost:8080/schedules/${id}`;
    return this.http.delete(url)
    .map(response => response.json() as any);
}

My REST endpoint in Java is as follows :

@RequestMapping(value = "/schedules/{id}", method = RequestMethod.DELETE)
public void deleteSchedules(@PathVariable("id") Long id)
{
    scheduleServiceManager.deleteSchedule(id);
}

My key problem is how do I match an arbitrary ID with that of the delete endpoint URL. Do I put in a sort of regex expression and then extract the ID?

Edits

I get the following error upon trying to access the REST endpoint:

Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8090' is therefore not allowed access. The response had HTTP status code 405.

It seems like I am getting the Cross Origin Resource Sharing Error now.

Body:
To solve "Access-Control-Allow-Origin", add CrossOrigin to your controller class. For example:

@CrossOrigin("*")
@Controller
public class YourSuperController


问:
DNN 8 scheduler errros on azure web app
I remember reading that the DNN platform edition struggles with the MS Azure web app environment in regards to the scheduler tasks.

this quote comes for this DNN connect blog

The DNN Platform / Community scheduler does not support Azure Web
  Sites as the server names running the web site are ever changing as
  Azure scales up and down, or upgrades underlying machines. There is a
  solution for Evoq.

I am getting the following scheduler errors in my DNN instances on Azure:

THREAD ID:59
  TYPE:DotNetNuke.Services.Search.SearchEngineScheduler,DOTNETNUKE
  EXCEPTION:Lock obtain timed out:
  NativeFSLock@D:\home\site\wwwroot\App_Data\Search\write.lock

It is happening A LOT.  THis is on a 08.00.04 version

I am also getting the following error on a 08.00.01 version

TYPE:DotNetNuke.Services.Scheduling.PurgeScheduleHistory, DOTNETNUKE
  EXCEPTION:Execution Timeout Expired. The timeout period elapsed prior
  to completion of the operation or the server is not responding.

My question is whether dnn platform's scheduler works properly in the azure web app environment, and what version saw this delivered.  This will help me in getting these errors resolved.

Thanks

答:
We often host Test and QA Evoq environments in Azure and the machine names do change, therefore require us to reactivate licensing. But these are on the Free or Shared pricing tiers.  I believe if you move to Basic and above, the environment should be dedicated.  You can also confirm with DNN Corp on this because their own OnDemand hosting uses Azure.

The Search write-lock error I have seen on other environments so I don't believe it's an Azure problem necessarily.  For this issue, restart the app pool and delete all files in the App_Data\Search folder.  Then start the site, go to Settings > Site Settings > Search and click the Re-index Content button.  Then start the Site Crawler job from the scheduler.  Ensure in Site Settings > Servers > Server Settings > Web Servers, that only the current server name is there -- delete any old server names.  In Settings > Scheduler, edit the Search: Site Crawler task.  In the Servers textbox, you can enter the name of the server so that it ensures it only runs on that server to ensure no overlap in processing (thinking it's in webfarm mode).

Title: DNN 8 scheduler errros on azure web app


问:
JQuery if both conditions are true perform action
I have the following code which executes on mobile screens, but the problem is it also executes on large screens.
Can this be change to execute only if both conditions are true?

Thanks

```<code>$(window).scroll(function(){

        var ww = $(window).width();
        var sc = $(window).scrollTop();

        if (ww < 769 && sc > 100){
            $('header').addClass('fixed-header');
            $('.page-sidebar').css('top', 65);
        } else {
            $('header').removeClass('fixed-header');
            $('.page-sidebar').css('top', 115);
        }

    });
</code>```

答:
So from your comment you need to provide a conditional for the else block, or the whole block, to prevent it from running.

```<code>    if (ww < 769 && sc > 100){
        $('header').addClass('fixed-header');
        $('.page-sidebar').css('top', 65);
    } else if (ww < 2048) { //or whatever your value for a 'large' screen starts at
        $('header').removeClass('fixed-header');
        $('.page-sidebar').css('top', 115);
    }
</code>```

or

```<code>    if (www < 2048) {
      if (ww < 769 && sc > 100){
          $('header').addClass('fixed-header');
          $('.page-sidebar').css('top', 65);
      } else {
          $('header').removeClass('fixed-header');
          $('.page-sidebar').css('top', 115);
      }
    }
</code>```

The first would prevent the else from happening for large screens.  The second would prevent the whole if else from happening for large screens.

Body:
I have the following code which executes on mobile screens, but the problem is it also executes on large screens.
Can this be change to execute only if both conditions are true?

Thanks

$(window).scroll(function(){

        var ww = $(window).width();
        var sc = $(window).scrollTop();

        if (ww < 769 && sc > 100){
            $('header').addClass('fixed-header');
            $('.page-sidebar').css('top', 65);
        } else {
            $('header').removeClass('fixed-header');
            $('.page-sidebar').css('top', 115);
        }

    });

Body:
So from your comment you need to provide a conditional for the else block, or the whole block, to prevent it from running.

    if (ww < 769 && sc > 100){
        $('header').addClass('fixed-header');
        $('.page-sidebar').css('top', 65);
    } else if (ww < 2048) { //or whatever your value for a 'large' screen starts at
        $('header').removeClass('fixed-header');
        $('.page-sidebar').css('top', 115);
    }

or

    if (www < 2048) {
      if (ww < 769 && sc > 100){
          $('header').addClass('fixed-header');
          $('.page-sidebar').css('top', 65);
      } else {
          $('header').removeClass('fixed-header');
          $('.page-sidebar').css('top', 115);
      }
    }

The first would prevent the else from happening for large screens.  The second would prevent the whole if else from happening for large screens.


问:
Hyperledger Fabric chaincode instantiation returns timeout expired
I've been working around with Fabric for a a few months now, and I've been trying to run a somewhat complex virtual machine, the Ethereum Virtual Machine within a chaincode. It is written in JavaScript so I worked with the nodeJS chaincode version.
I packed the the VM with my chaincode in a directory that i install and instantiate onto the peer. The install completes and exits with no errors, however the instantiation after hanging for a few minutes returns me an error:

```<code>Error: Error endorsing chaincode: rpc error: code = Unknown desc = timeout expired while starting chaincode mychaincode:1.0(networkid:dev,peerid:peer0.org1.example.com,tx:....
</code>```

It should run for quite a few minutes at least as the added packages are ~15MB, according to the example nodejs chaincode runs for a minute at least.

The example nodejs chaincode (chaincode_example02) runs perfectly on both BYFN network from the tutorial and on a basic-network that I've started. My environment was set up according to the documentation (v1.1.0) from the fabric-samples repository (v1.1.0). Even if I only add one package to the example chaincode with the require method, it hangs, than return error.

I've been searching for a flag or config where I can set the timeout value for chaincode instantiation, but with no luck. Where could I increase the timeout value?
Which log should I provide in order to step forward in searching for the soution?

Thanks is advance,
Balint

答: You can modify the chaincode.startuptimeout config by adding a CORE_CHAINCODE_STARTUPTIMEOUT environment variable to the base/peer-base.yaml docker compose file specifying something other than the default.

Body:
I've been working around with Fabric for a a few months now, and I've been trying to run a somewhat complex virtual machine, the Ethereum Virtual Machine within a chaincode. It is written in JavaScript so I worked with the nodeJS chaincode version.
I packed the the VM with my chaincode in a directory that i install and instantiate onto the peer. The install completes and exits with no errors, however the instantiation after hanging for a few minutes returns me an error:

Error: Error endorsing chaincode: rpc error: code = Unknown desc = timeout expired while starting chaincode mychaincode:1.0(networkid:dev,peerid:peer0.org1.example.com,tx:....

It should run for quite a few minutes at least as the added packages are ~15MB, according to the example nodejs chaincode runs for a minute at least.

The example nodejs chaincode (chaincode_example02) runs perfectly on both BYFN network from the tutorial and on a basic-network that I've started. My environment was set up according to the documentation (v1.1.0) from the fabric-samples repository (v1.1.0). Even if I only add one package to the example chaincode with the require method, it hangs, than return error.

I've been searching for a flag or config where I can set the timeout value for chaincode instantiation, but with no luck. Where could I increase the timeout value?
Which log should I provide in order to step forward in searching for the soution?

Thanks is advance,
Balint


问:
Bug - duplication of the status "In stock" (WooCommerce)
The answer to this question - Replace Variable Product Price by the chosen variation price in WooCommerce 3 - was the answer with the solution of the problem.

How do I fix this bug?

If the Variable product has the same price of variations, then there is a duplication of the status "In stock", Like this:

```<code>add_action( 'woocommerce_before_single_product', 'check_if_variable_first' );
function check_if_variable_first(){
if ( is_product() ) {
    global $post;
    $product = wc_get_product( $post->ID );
    if ( $product->is_type( 'variable' ) ) {
        // removing the price of variable products
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );

// Change location of
add_action( 'woocommerce_single_product_summary', 'custom_wc_template_single_price', 10 );
function custom_wc_template_single_price(){
global $product;

// Variable product only
if($product->is_type('variable')):

// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice && $product->is_on_sale() ) {
    $price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
}

?>
<style>
    div.woocommerce-variation-price,
    div.woocommerce-variation-availability,
    div.hidden-variable-price {
        height: 0px !important;
        overflow:hidden;
        position:relative;
        line-height: 0px !important;
        font-size: 0% !important;
    }
</style>
<script>
jQuery(document).ready(function($) {
    $('select').blur( function(){
        if( '' != $('input.variation_id').val() ){
            $('p.price').html($('div.woocommerce-variation-price > span.price').html()).append('<p class="availability">'+$('div.woocommerce-variation-availability').html()+'</p>');
            console.log($('input.variation_id').val());
        } else {
            $('p.price').html($('div.hidden-variable-price').html());
            if($('p.availability'))
                $('p.availability').remove();
            console.log('NULL');
        }
    });
});
</script>
<?php

echo '<p class="price">'.$price.'</p>
<div class="hidden-variable-price" >'.$price.'</div>';

endif;
}

      }
   }
}
</code>```

答:
My answer on this thread was working nice in WooCommerce 3 on Storefront theme…

Try instead this revisited code:

```<code>add_action( 'woocommerce_before_single_product', 'custom_template_single_price', 1 );
function custom_template_single_price(){
    if ( ! is_product() ) return; // Only on single product pages

    global $product, $post;

    if ( $product->is_type( 'variable' ) ) {
        // removing the price of variable products
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );

        // Change location of
        add_action( 'woocommerce_single_product_summary', 'replace_template_single_price', 10 );
    }
}

function replace_template_single_price(){
    global $product;

    // Main Price
    $prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
    $price = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

    // Sale Price
    $prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
    sort( $prices );
    $saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

    if ( $price !== $saleprice && $product->is_on_sale() ) {
        $price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
    }

    ?>
    <style>
        div.woocommerce-variation-price,
        div.woocommerce-variation-availability,
        div.hidden-variable-price {
            height: 0px !important;
            overflow:hidden;
            position:relative;
            line-height: 0px !important;
            font-size: 0% !important;
        }
    </style>
    <script>
    jQuery(document).ready(function($) {
        $('select').blur( function(){
            if( '' != $('input.variation_id').val() ){
                if($('p.availability'))
                    $('p.availability').remove();
                if($('p.stock'))
                    $('p.stock').remove();
                $('p.price').html($('div.woocommerce-variation-price > span.price').html()).append('<p class="availability">'+$('div.woocommerce-variation-availability').html()+'</p>');
            } else {
                $('p.price').html($('div.hidden-variable-price').html());
                if($('p.availability'))
                    $('p.availability').remove();
                if($('p.stock'))
                    $('p.stock').remove();
            }
        });
    });
    </script>
    <?php

    echo '<p class="price">'.$price.'</p>
    <div class="hidden-variable-price" >'.$price.'</div>';
}
</code>```

Tested in WooCommerce 3.2.x and works (on storefront theme)

I have added some jQuery code to remove the stock availability label before setting it. It should work for you too.

For some themes with customizations on the html structure and classes names, you will need to make some changes in the code

Body:
The answer to this question - Replace Variable Product Price by the chosen variation price in WooCommerce 3 - was the answer with the solution of the problem.

How do I fix this bug?

If the Variable product has the same price of variations, then there is a duplication of the status "In stock", Like this:

add_action( 'woocommerce_before_single_product', 'check_if_variable_first' );
function check_if_variable_first(){
if ( is_product() ) {
    global $post;
    $product = wc_get_product( $post->ID );
    if ( $product->is_type( 'variable' ) ) {
        // removing the price of variable products
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );

// Change location of
add_action( 'woocommerce_single_product_summary', 'custom_wc_template_single_price', 10 );
function custom_wc_template_single_price(){
global $product;

// Variable product only
if($product->is_type('variable')):

// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice && $product->is_on_sale() ) {
    $price = '' . $saleprice . $product->get_price_suffix() . ' ' . $price . $product->get_price_suffix() . '';
}

?>

<?php

echo '
'.$price.'

'.$price.'
';

endif;
}

      }
   }
}

Body:
My answer on this thread was working nice in WooCommerce 3 on Storefront theme…

Try instead this revisited code:

add_action( 'woocommerce_before_single_product', 'custom_template_single_price', 1 );
function custom_template_single_price(){
    if ( ! is_product() ) return; // Only on single product pages

    global $product, $post;

    if ( $product->is_type( 'variable' ) ) {
        // removing the price of variable products
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );

        // Change location of
        add_action( 'woocommerce_single_product_summary', 'replace_template_single_price', 10 );
    }
}

function replace_template_single_price(){
    global $product;

    // Main Price
    $prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
    $price = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

    // Sale Price
    $prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
    sort( $prices );
    $saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

    if ( $price !== $saleprice && $product->is_on_sale() ) {
        $price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
    }

    ?>
    <style>
        div.woocommerce-variation-price,
        div.woocommerce-variation-availability,
        div.hidden-variable-price {
            height: 0px !important;
            overflow:hidden;
            position:relative;
            line-height: 0px !important;
            font-size: 0% !important;
        }
    </style>
    <script>
    jQuery(document).ready(function($) {
        $('select').blur( function(){
            if( '' != $('input.variation_id').val() ){
                if($('p.availability'))
                    $('p.availability').remove();
                if($('p.stock'))
                    $('p.stock').remove();
                $('p.price').html($('div.woocommerce-variation-price > span.price').html()).append('<p class="availability">'+$('div.woocommerce-variation-availability').html()+'</p>');
            } else {
                $('p.price').html($('div.hidden-variable-price').html());
                if($('p.availability'))
                    $('p.availability').remove();
                if($('p.stock'))
                    $('p.stock').remove();
            }
        });
    });
    </script>
    <?php

    echo '<p class="price">'.$price.'</p>
    <div class="hidden-variable-price" >'.$price.'</div>';
}

Tested in WooCommerce 3.2.x and works (on storefront theme)

I have added some jQuery code to remove the stock availability label before setting it. It should work for you too.

For some themes with customizations on the html structure and classes names, you will need to make some changes in the code


问:
IOS : Distribution (release) configuration bugs and crashes
I've created an app to solve sudoku grids...but
here is my problem : my app has some bug and even crashes with my Distribution Configuration for compiling (equivalent to Release Configuration).

Here is the code where it bugs :

```<code>- (int*)completeNb:(int[9][9])aMatrix {
    int n, nb;
    int cell[2];
    int *pcell;
    BOOL found = FALSE;
    BOOL pos = FALSE;
    for (int k = 1; k <= 9; k++) {
        n = 0;
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (aMatrix[i][j] == k)
                    n++;
            }
        }
        if (n == 8) {
            found = TRUE;
            nb = k;
            break;
        }
    }
    if (found) {
        for (int l = 0; l < 9; l++) {
            for (int m = 0; m < 9; m++) {
                if ([self isPossibleValue:aMatrix value:nb line:l column:m]) {
                    cell[0] = l;
                    cell[1] = m;
                    pos = TRUE;
                    break;
                }
            }
            if (pos)
                break;
        }
        pcell = cell;
    }
    else {
        pcell = nil;
    }
    return pcell;
}
</code>```

I have a special sudoku grid where I should find {6,6} as the right position for number 6 (6 should at i=6 and j=6 in the grid). It works perfectly in Debug Configuration, but with Distrib Conf, it seems like I have problem with the l and m vars -> the loop breaks well at l=6 and m=6 (hence, isPossibleValue function seems to work well), but then my cell variable is equal to {1;0}, instead of {6;6} !

I am using this kind of process (returning a cell[2]) with many other functions, and I don't have any problem with the Distrib Conf.

My second problem, - and this one is provoking the app to crash - is with the following code (again, perfectly working with debug configuration).

```<code>- (void)solver:(int[9][9])aMatrix {
    if (!Termine) {
        int *emptyCell = [self firstEmptyCell:aMatrix];
        if (emptyCell != nil) {
            int i = emptyCell[0];
            int j = emptyCell[1];
            for (int k = 1; k <= 9; k++) {
                if ([self isPossibleValue:aMatrix value:k line:i column:j]) {
                    aMatrix[i][j] = k;
                    [self solver:aMatrix];
                    aMatrix[i][j] = 0;
                }
            }
        }
        else {
            if (!Termine) {
                Termine = TRUE;
                for (int i = 0; i < 9; i++)
                    for (int j = 0; j < 9; j++)
                        res[i][j] = aMatrix[i][j];
            }
        }

    }
}
</code>```

Note : one solution, - I am not sure that's the best one - is to change optimization level from "fastest, smallest" to "none".

Thanks for your help !

答:
For the first case the problem is in int cell[2];. It has a local scope, and after you return from the function the memory zone pointed by this array very likely will be reallocated for other needs. A quick solution is to add static specifier:

```<code>static int cell[2];
</code>```

For the second snippet, make sure that emptyCell each time assigns to i and j values which doesn't exceed aMatrix bounds [0..8][0..8].

Body:
I've created an app to solve sudoku grids...but
here is my problem : my app has some bug and even crashes with my Distribution Configuration for compiling (equivalent to Release Configuration).

Here is the code where it bugs :

- (int*)completeNb:(int[9][9])aMatrix {
    int n, nb;
    int cell[2];
    int *pcell;
    BOOL found = FALSE;
    BOOL pos = FALSE;
    for (int k = 1; k <= 9; k++) {
        n = 0;
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (aMatrix[i][j] == k)
                    n++;
            }
        }
        if (n == 8) {
            found = TRUE;
            nb = k;
            break;
        }
    }
    if (found) {
        for (int l = 0; l < 9; l++) {
            for (int m = 0; m < 9; m++) {
                if ([self isPossibleValue:aMatrix value:nb line:l column:m]) {
                    cell[0] = l;
                    cell[1] = m;
                    pos = TRUE;
                    break;
                }
            }
            if (pos)
                break;
        }
        pcell = cell;
    }
    else {
        pcell = nil;
    }
    return pcell;
}

I have a special sudoku grid where I should find {6,6} as the right position for number 6 (6 should at i=6 and j=6 in the grid). It works perfectly in Debug Configuration, but with Distrib Conf, it seems like I have problem with the l and m vars -> the loop breaks well at l=6 and m=6 (hence, isPossibleValue function seems to work well), but then my cell variable is equal to {1;0}, instead of {6;6} !

I am using this kind of process (returning a cell[2]) with many other functions, and I don't have any problem with the Distrib Conf.

My second problem, - and this one is provoking the app to crash - is with the following code (again, perfectly working with debug configuration).

- (void)solver:(int[9][9])aMatrix {
    if (!Termine) {
        int *emptyCell = [self firstEmptyCell:aMatrix];
        if (emptyCell != nil) {
            int i = emptyCell[0];
            int j = emptyCell[1];
            for (int k = 1; k <= 9; k++) {
                if ([self isPossibleValue:aMatrix value:k line:i column:j]) {
                    aMatrix[i][j] = k;
                    [self solver:aMatrix];
                    aMatrix[i][j] = 0;
                }
            }
        }
        else {
            if (!Termine) {
                Termine = TRUE;
                for (int i = 0; i < 9; i++)
                    for (int j = 0; j < 9; j++)
                        res[i][j] = aMatrix[i][j];
            }
        }

    }
}

Note : one solution, - I am not sure that's the best one - is to change optimization level from "fastest, smallest" to "none".

Thanks for your help !

Body:
For the first case the problem is in int cell[2];. It has a local scope, and after you return from the function the memory zone pointed by this array very likely will be reallocated for other needs. A quick solution is to add static specifier:

static int cell[2];

For the second snippet, make sure that emptyCell each time assigns to i and j values which doesn't exceed aMatrix bounds [0..8][0..8].


问:
GitLab Pages API 404 error for certain projects
I have been writing automation scripts to generate and update SSL certificates using Namesilo, Letsencrypt and Gitlab APIs.
I almost got to the end, but I am getting a 404 error when trying to update the SSL certificate on Gitlab.

The weird part is that the error happens on only one of my two projects. Specifically, running:

```<code>curl --header "Private-Token: XXXXXX" "https://gitlab.com/api/v4/projects/pallavagarwal07%2Fshort-links/pages/domains/pallav.xyz"
</code>```

works fine and fetches the details of domain pallav.xyz in project short-links.

But, running:

```<code>curl --header "Private-Token: XXXXX" "https://gitlab.com/api/v4/projects/pallavagarwal07%2Fpallavagarwal07.gitlab.io/pages/domains/varstack.com"
</code>```

returns a 404 error. However, what makes it weirder is that if I remove the domain name varstack.com from the URL, it gives me the list of domains as expected:

```<code>curl --header "Private-Token: XXXXX" "https://gitlab.com/api/v4/projects/pallavagarwal07%2Fpallavagarwal07.gitlab.io/pages/domains"
</code>```

returns:

```<code>[{"domain":"varstack.com","url":"https://varstack.com","certificate":....]
</code>```

答:
I finally figured it out (although I would still classify this as a bug on the part of GitLab).

The ID needs to be url-encoded, which is why I had replaced / in the repository name by %2F. However the character . should not have been a problem (- in the former URL did not cause any problem). However, replacing . by %2E gives expected (correct) results.

I think this is a bug because:

This behavior is not documented (which characters are allowed?).

The URL without the domain name works flawlessly even without encoding ., including the API to add new domains (which also takes domain as a form parameter, and not in URL).

TL;DR

Using:

```<code>pallavagarwal07%2Fpallavagarwal07%2Egitlab%2Eio
</code>```

instead of

```<code>pallavagarwal07%2Fpallavagarwal07.gitlab.io
</code>```

in the URL makes it work.

Body:
I have been writing automation scripts to generate and update SSL certificates using Namesilo, Letsencrypt and Gitlab APIs.
I almost got to the end, but I am getting a 404 error when trying to update the SSL certificate on Gitlab.

The weird part is that the error happens on only one of my two projects. Specifically, running:

curl --header "Private-Token: XXXXXX" "https://gitlab.com/api/v4/projects/pallavagarwal07%2Fshort-links/pages/domains/pallav.xyz"

works fine and fetches the details of domain pallav.xyz in project short-links.

But, running:

curl --header "Private-Token: XXXXX" "https://gitlab.com/api/v4/projects/pallavagarwal07%2Fpallavagarwal07.gitlab.io/pages/domains/varstack.com"

returns a 404 error. However, what makes it weirder is that if I remove the domain name varstack.com from the URL, it gives me the list of domains as expected:

curl --header "Private-Token: XXXXX" "https://gitlab.com/api/v4/projects/pallavagarwal07%2Fpallavagarwal07.gitlab.io/pages/domains"

returns:

[{"domain":"varstack.com","url":"https://varstack.com","certificate":....]

Body:
I finally figured it out (although I would still classify this as a bug on the part of GitLab).

The ID needs to be url-encoded, which is why I had replaced / in the repository name by %2F. However the character . should not have been a problem (- in the former URL did not cause any problem). However, replacing . by %2E gives expected (correct) results.

I think this is a bug because:

This behavior is not documented (which characters are allowed?).

The URL without the domain name works flawlessly even without encoding ., including the API to add new domains (which also takes domain as a form parameter, and not in URL).

TL;DR

Using:

pallavagarwal07%2Fpallavagarwal07%2Egitlab%2Eio

instead of

pallavagarwal07%2Fpallavagarwal07.gitlab.io

in the URL makes it work.


问:
VBA Clear and Copy without blank rows to another sheet on entering value greater than
My 2010 macro updates on opening a sheet. Does 2016 work the same when when they have the target sheet opened in a new 'instance'? It has to be idiot proof (I don't know why they asked me to do it :P). So the macro has to run once when opening the sheet; if the sheet is opened on the second monitor run every time a value is inserted over 119 in the source sheet; Don't run unnecessary because of the potentially very large sheets and meh laptops.

I've made this macro so the sheets my colleges are using don't need 'complex' formulas or macros to clear blank rows before it's exported to Word. I've made it in 2010, but I can't test it on 2016 til next week.

The macro that on the target sheet (J03);

```<code>Private Sub worksheet_activate()
</code>```

And on the source sheet (WTB);

```<code> Private Sub Run_When_Value_Greather_Than_119_Is_Entered_In_Column_G()
</code>```

Google is clogged with answers and results about blank rows, copying, blank rows, running on other activation ways and non blank rows. I probably don't know what to look for either.

The full code;

```<code>Private Sub worksheet_activate()
  Dim Max As Long, MaxD As Long       'Determine the amount of filled rows
  Dim wsWtB As Worksheet, wsJ03 As Worksheet
  Dim wb As Workbook
  Dim i As Integer, j As Integer      'i and j for the row numbers

  Application.ScreenUpdating = False  'screenupdating of for max speeds

  Set wb = ThisWorkbook
  Set wsJ03 = Sheets("J_03")
  Set wsWtB = Sheets("WTB")

  Max = WorksheetFunction.Max(wsWtB.Range("A3:A1600"))  'Amount of rows with data
  Max = Max + 3                                         'Ignore the headers
  MaxD = WorksheetFunction.Max(wsJ03.Range("A3:A1600"))
  MaxD = MaxD + 2
  j = 9                   'The rownumber where the copying needs to start
    wsJ03.Range("B9", Cells(MaxD, 5)).ClearContents  'Clear the old values
      For i = 3 To Max    'The copying loop has to start after the headers at row 3
        If wsWtB.Cells(i, 7).Value > 119 Then   'Do stuff if...
          wsJ03.Cells(j, "B").Value = Chr(39) & wsWtB.Cells(i, "B").Value 'At a  '
          wsJ03.Cells(j, "C").Value = Chr(39) & wsWtB.Cells(i, "C").Value 'at the start
          wsJ03.Cells(j, "D").Value = Chr(39) & wsWtB.Cells(i, "D").Value 'so a zero is
          wsJ03.Cells(j, "E").Value = Chr(39) & wsWtB.Cells(i, "E").Value 'displayed
          j = j + 1       'Set the next row for the target sheet
        Else
      End If
    Next i
  Application.ScreenUpdating = True
End Sub
</code>```

It's the first piece of code that I got working without hiccups :-) Feel free to comment and ad the propper tags.

Koen.

Edit; (Alternative ways to look for the last cell)

```<code>?thisworkbook.sheets("WTB").cells(rows.Count,"A").end(xlup).row
  1047 '<- Rownumber of the last cell with a Formula to create/force
        successive
        numbers
?thisworkbook.sheets("WTB").columns("A").Find(What:="*", LookIn:=xlValues,
 SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
  5    '<- Rownumber of the last cell with a value. Includes the header
        rows
?WorksheetFunction.Max(thisworkbook.sheets("WTB").Range("A3:A1600"))
  3    '<- Highest number in A3:A1600 and also the amount units/rows that
        need to be copied to "J_03"
</code>```

I needed a function that gave me the amount of 'things' on the sheet. In this case it's 3, but it could go up to 1600.

Edit 2; (google sheet so you can see what i'm working on)
https://docs.google.com/spreadsheets/d/1I5qLeOS0DWcwncs_ium_J0Vp6b4nzTsiE0ndbKtpsC0/edit?usp=sharing

Edit 3; there was an error in the clear range part.
 wsJ03.Range("B9", Cells(MaxD, 5)).ClearContents  'Clear the old values

答:
You could use something like the following, but make sure you place the code in the Sheet where the values might be changing (Sheets("WTB")):</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 7 Then 'If something changed in column G
        If Target.Value > 119 Then 'and if the value is higher than 119
        NextFreeRow = Sheets("J_03").Cells(.Rows.Count, "B").End(xlUp).Row + 1
        'Or Do your copying stuff, you can use Target.column or Target.row to find the address of the cell that got a value higher than 119
            Sheets("J_03").Cells(NextFreeRow, "B").Value = Chr(39) & Sheets("WTB").Cells(Target.Row, "B").Value 'At a  '
            Sheets("J_03").Cells(NextFreeRow, "C").Value = Chr(39) & Sheets("WTB").Cells(Target.Row, "C").Value 'at the start
            Sheets("J_03").Cells(NextFreeRow, "D").Value = Chr(39) & Sheets("WTB").Cells(Target.Row, "D").Value 'so a zero is
            Sheets("J_03").Cells(NextFreeRow, "E").Value = Chr(39) & Sheets("WTB").Cells(Target.Row, "E").Value 'displayed
        End If
    End If
End Sub
</code>```

Body:
My 2010 macro updates on opening a sheet. Does 2016 work the same when when they have the target sheet opened in a new 'instance'? It has to be idiot proof (I don't know why they asked me to do it :P). So the macro has to run once when opening the sheet; if the sheet is opened on the second monitor run every time a value is inserted over 119 in the source sheet; Don't run unnecessary because of the potentially very large sheets and meh laptops.

I've made this macro so the sheets my colleges are using don't need 'complex' formulas or macros to clear blank rows before it's exported to Word. I've made it in 2010, but I can't test it on 2016 til next week.

The macro that on the target sheet (J03);

Private Sub worksheet_activate()

And on the source sheet (WTB);

 Private Sub Run_When_Value_Greather_Than_119_Is_Entered_In_Column_G()

Google is clogged with answers and results about blank rows, copying, blank rows, running on other activation ways and non blank rows. I probably don't know what to look for either.

The full code;

Private Sub worksheet_activate()
  Dim Max As Long, MaxD As Long       'Determine the amount of filled rows
  Dim wsWtB As Worksheet, wsJ03 As Worksheet
  Dim wb As Workbook
  Dim i As Integer, j As Integer      'i and j for the row numbers

  Application.ScreenUpdating = False  'screenupdating of for max speeds

  Set wb = ThisWorkbook
  Set wsJ03 = Sheets("J_03")
  Set wsWtB = Sheets("WTB")

  Max = WorksheetFunction.Max(wsWtB.Range("A3:A1600"))  'Amount of rows with data
  Max = Max + 3                                         'Ignore the headers
  MaxD = WorksheetFunction.Max(wsJ03.Range("A3:A1600"))
  MaxD = MaxD + 2
  j = 9                   'The rownumber where the copying needs to start
    wsJ03.Range("B9", Cells(MaxD, 5)).ClearContents  'Clear the old values
      For i = 3 To Max    'The copying loop has to start after the headers at row 3
        If wsWtB.Cells(i, 7).Value > 119 Then   'Do stuff if...
          wsJ03.Cells(j, "B").Value = Chr(39) & wsWtB.Cells(i, "B").Value 'At a  '
          wsJ03.Cells(j, "C").Value = Chr(39) & wsWtB.Cells(i, "C").Value 'at the start
          wsJ03.Cells(j, "D").Value = Chr(39) & wsWtB.Cells(i, "D").Value 'so a zero is
          wsJ03.Cells(j, "E").Value = Chr(39) & wsWtB.Cells(i, "E").Value 'displayed
          j = j + 1       'Set the next row for the target sheet
        Else
      End If
    Next i
  Application.ScreenUpdating = True
End Sub

It's the first piece of code that I got working without hiccups :-) Feel free to comment and ad the propper tags.

Koen.

Edit; (Alternative ways to look for the last cell)

?thisworkbook.sheets("WTB").cells(rows.Count,"A").end(xlup).row
  1047 '<- Rownumber of the last cell with a Formula to create/force
        successive
        numbers
?thisworkbook.sheets("WTB").columns("A").Find(What:="*", LookIn:=xlValues,
 SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
  5    '<- Rownumber of the last cell with a value. Includes the header
        rows
?WorksheetFunction.Max(thisworkbook.sheets("WTB").Range("A3:A1600"))
  3    '<- Highest number in A3:A1600 and also the amount units/rows that
        need to be copied to "J_03"

I needed a function that gave me the amount of 'things' on the sheet. In this case it's 3, but it could go up to 1600.

Edit 2; (google sheet so you can see what i'm working on)
https://docs.google.com/spreadsheets/d/1I5qLeOS0DWcwncs_ium_J0Vp6b4nzTsiE0ndbKtpsC0/edit?usp=sharing

Edit 3; there was an error in the clear range part.
 wsJ03.Range("B9", Cells(MaxD, 5)).ClearContents  'Clear the old values

Body:
You could use something like the following, but make sure you place the code in the Sheet where the values might be changing (Sheets("WTB")):

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 7 Then 'If something changed in column G
        If Target.Value > 119 Then 'and if the value is higher than 119
        NextFreeRow = Sheets("J_03").Cells(.Rows.Count, "B").End(xlUp).Row + 1
        'Or Do your copying stuff, you can use Target.column or Target.row to find the address of the cell that got a value higher than 119
            Sheets("J_03").Cells(NextFreeRow, "B").Value = Chr(39) & Sheets("WTB").Cells(Target.Row, "B").Value 'At a  '
            Sheets("J_03").Cells(NextFreeRow, "C").Value = Chr(39) & Sheets("WTB").Cells(Target.Row, "C").Value 'at the start
            Sheets("J_03").Cells(NextFreeRow, "D").Value = Chr(39) & Sheets("WTB").Cells(Target.Row, "D").Value 'so a zero is
            Sheets("J_03").Cells(NextFreeRow, "E").Value = Chr(39) & Sheets("WTB").Cells(Target.Row, "E").Value 'displayed
        End If
    End If
End Sub


问:
HTML/CSS not able to be a sticky element?
I am trying to create an image that is a sticky element. However, when I try to make it work, it simply doesn't follow those rules. The sticky property works for every other element on the page, so I am not sure what is happening. Any help would be appreciated.

HTML -

```<code><HTML>
<head>
    <title> Stunning Web Design </title>
    <link rel = 'stylesheet' type = "text/css" href = "main.css">
    <div id = "fonts">
    <link href="https://fonts.googleapis.com/css?family=Cabin" rel="stylesheet">
    </div>
</head>
<body>
    <div id = "images">
    <img id = "fall_bridge" src = "Photos/fall_bridge.jpg" alt = "Beautiful Paris Photo" width = 1482 height = 720>
    </div>
    <p id = 'backPlate'> </p>
    <h1 id = "mainTitle"> Stunning Web Design </h1>
</body>
</code>```

My CSS -

```<code>#fall_bridge {
    position: -webkit-sticky; /* safari enabled */
    position: sticky;
    top: 0;
    border: 5px solid white;
    -webkit-filter: grayscale(100%);
     filter: grayscale(100%);

}

#mainTitle {
    border: 8px double white;
    background-color: rgba(148, 149, 153, .8);
    width: 680px;
    padding: 10px 10px;
    position: relative;
    bottom: 1100px;
    left: 380px;
    color: white;
    font-family: 'Cabin', sans-serif;
    font-size: 100px;
    text-align: center;
}

img {

}

#backPlate {
    position: relative;
    border: 1px solid black;
    width: 1488px;
    height: 500px;
}
</code>```

答:
The surrounding div #images is affecting it. If you apply the sticky properties to #images instead of #fall_bridge, it should work (if that is your desired result).

A bit off-topic but I noticed you have your web fonts in your head inside of a div? Any reason for that? Divs shouldn't need to be in your head tag.

Body:
I am trying to create an image that is a sticky element. However, when I try to make it work, it simply doesn't follow those rules. The sticky property works for every other element on the page, so I am not sure what is happening. Any help would be appreciated.

HTML -

    <title> Stunning Web Design </title>
    <link rel = 'stylesheet' type = "text/css" href = "main.css">

    <link href="https://fonts.googleapis.com/css?family=Cabin" rel="stylesheet">

 Stunning Web Design

My CSS -

#fall_bridge {
    position: -webkit-sticky; /* safari enabled */
    position: sticky;
    top: 0;
    border: 5px solid white;
    -webkit-filter: grayscale(100%);
     filter: grayscale(100%);

}

#mainTitle {
    border: 8px double white;
    background-color: rgba(148, 149, 153, .8);
    width: 680px;
    padding: 10px 10px;
    position: relative;
    bottom: 1100px;
    left: 380px;
    color: white;
    font-family: 'Cabin', sans-serif;
    font-size: 100px;
    text-align: center;
}

img {

}

#backPlate {
    position: relative;
    border: 1px solid black;
    width: 1488px;
    height: 500px;
}


问:
Gitlab "Forbidden" error
I are running GitLab - Version:10.0.3 and encountered the Forbidden error and Gitlab is forbidding our own office IP. I have already added our office IP in the gitlab_rails['rack_attack_git_basic_auth'] section in gitlab.rb file and also restart gitlab gitlab-ctl restart but still no luck. Please help to resolve.

GitLab information
Version: 10.0.3

Thanks

答:
The whitelist you defined is only used for the 'Fail2Ban' part (basic auth brute-forcing) of the Rack attack gem.

For throttling there is no whitelist configurable via gitlab.rb at present.

You can tune the behaviour of the throttling part of Rack Attack in general via gitlab.rb  by adding below options (experiment with the values)

```<code>#gitlab_rails['rate_limit_requests_per_period'] = 10
#gitlab_rails['rate_limit_period'] = 60
</code>```

Don't forget to do a gitlab-ctl reconfigure (maybe you did, but you did not mention it explicitly)

Title: Gitlab "Forbidden" error

Body:
The whitelist you defined is only used for the 'Fail2Ban' part (basic auth brute-forcing) of the Rack attack gem.

For throttling there is no whitelist configurable via gitlab.rb at present.

You can tune the behaviour of the throttling part of Rack Attack in general via gitlab.rb  by adding below options (experiment with the values)

#gitlab_rails['rate_limit_requests_per_period'] = 10
#gitlab_rails['rate_limit_period'] = 60

Don't forget to do a gitlab-ctl reconfigure (maybe you did, but you did not mention it explicitly)


问:
Error when trying to retrieve data from a table using ExecuteScalar<object>?
I have this class:

```<code>public class BtnCountViews
{
    public int btnCount { get; set; }
    public int views { get; set; }
}
</code>```

I'm trying to retrieve data for one row from my database:

```<code>sql = " AVG (BTNACOUNT + BTNBCOUNT) AS btnCount, AVG (VIEWS) As views ";
var avg = db2.ExecuteScalar<BtnCountViews>("SELECT " + sql + " FROM CLICKHISTORY");
</code>```

But this is throwing an exception saying:

```<code>System.NotSupportedException: Don't know how to read Japanese.BtnCountViews
at SQLite.SQLiteCommand.ReadCol (SQLitePCL.sqlite3_stmt stmt,
</code>```

I tried to look into ExecuteScalar and it seems like it can take an object.

Does anyone have any idea why it could be throwing an exception?

For reference here's the object definition for the CLICKHISTORY table:

```<code>public class ClickHistory
{
    [PrimaryKey, NotNull]
    public string Yymmdd { get; set; }
    public int DayOfYear { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
    public int BtnACount { get; set; }
    public int BtnBCount { get; set; }
    public int BtnCCount { get; set; }
    public int BtnDCount { get; set; }
    public int Views { get; set; }
}
</code>```

答:
You are trying to return a type of BtnCountViews , not a scalar value.

Either return the projected BtnCountViews via a Query:

```<code>var sql = "AVG (BTNACOUNT + BTNBCOUNT) AS btnCount, AVG (VIEWS) As views ";
var avg = conn.Query<BtnCountViews>("SELECT " + sql + " FROM CLICKHISTORY").First();

Log.Debug(TAG, $"{avg.btnCount} : {avg.views}");
</code>```

Or bring back the scalars in two separate queries via ExecuteScalar:

```<code>var sql2 = "(AVG (BTNACOUNT + BTNBCOUNT))";
var btnABAvg = conn.ExecuteScalar<int>("SELECT " + sql2 + " FROM CLICKHISTORY");

var sql3 = "(AVG (VIEWS))";
var viewAvg = conn.ExecuteScalar<int>("SELECT " + sql3 + " FROM CLICKHISTORY");

Log.Debug(TAG, $"{btnABAvg} : {viewAvg}");
</code>```

Body:
I have this class:

public class BtnCountViews
{
    public int btnCount { get; set; }
    public int views { get; set; }
}

I'm trying to retrieve data for one row from my database:

sql = " AVG (BTNACOUNT + BTNBCOUNT) AS btnCount, AVG (VIEWS) As views ";
var avg = db2.ExecuteScalar<BtnCountViews>("SELECT " + sql + " FROM CLICKHISTORY");

But this is throwing an exception saying:

System.NotSupportedException: Don't know how to read Japanese.BtnCountViews
at SQLite.SQLiteCommand.ReadCol (SQLitePCL.sqlite3_stmt stmt,

I tried to look into ExecuteScalar and it seems like it can take an object.

Does anyone have any idea why it could be throwing an exception?

For reference here's the object definition for the CLICKHISTORY table:

public class ClickHistory
{
    [PrimaryKey, NotNull]
    public string Yymmdd { get; set; }
    public int DayOfYear { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
    public int BtnACount { get; set; }
    public int BtnBCount { get; set; }
    public int BtnCCount { get; set; }
    public int BtnDCount { get; set; }
    public int Views { get; set; }
}

Body:
You are trying to return a type of BtnCountViews , not a scalar value.

Either return the projected BtnCountViews via a Query:

var sql = "AVG (BTNACOUNT + BTNBCOUNT) AS btnCount, AVG (VIEWS) As views ";
var avg = conn.Query<BtnCountViews>("SELECT " + sql + " FROM CLICKHISTORY").First();

Log.Debug(TAG, $"{avg.btnCount} : {avg.views}");

Or bring back the scalars in two separate queries via ExecuteScalar:

var sql2 = "(AVG (BTNACOUNT + BTNBCOUNT))";
var btnABAvg = conn.ExecuteScalar<int>("SELECT " + sql2 + " FROM CLICKHISTORY");

var sql3 = "(AVG (VIEWS))";
var viewAvg = conn.ExecuteScalar<int>("SELECT " + sql3 + " FROM CLICKHISTORY");

Log.Debug(TAG, $"{btnABAvg} : {viewAvg}");


问:
For loop is only checking last value
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

```<code>public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}
</code>```

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

答:
You are checking every value, but you retrieve it from the last one. You basically need an exit condition which you already have. Change your code to this</p>

```<code>public boolean checkUserInDatabase(String username, String email) {
    List<User> localArray = getUserList();
    for (User u: localArray) {
        if (u.getUsername().equals(username)) {
            return true;
        }
    }
    return false;
}
</code>```

Title: For loop is only checking last value

Body:
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

Body:
You are checking every value, but you retrieve it from the last one. You basically need an exit condition which you already have. Change your code to this

public boolean checkUserInDatabase(String username, String email) {
    List<User> localArray = getUserList();
    for (User u: localArray) {
        if (u.getUsername().equals(username)) {
            return true;
        }
    }
    return false;
}


问:
Partial template specialization only for a single function
I've a template where I want to use a pointer type or an instance type as the template parameter. An Example:

```<code>class FOO {};

class ItemGetter {
    virtual FOO * GetItem(int index) = 0;
};

template<class T>
class ArrayContainer : public ItemGetter {
    T *array;
    ArrayContainer(T * array) {
        this->array = array;
    }

    /*
     * A lot of other functions.
     * I want to write them only once
     * ....
     */

    /* If the T Parameter is an instance Type */
    FOO * GetItem(int index) {
        return &this->array[index];
    }
    /* If the T Parameter is an pointer Type */
    FOO * GetItem(int index) {
        return this->array[index];
    }
};

void usage() {
  FOO fooArray[100];
  FOO * fooPointerArray[100];

  auto bar1 = ArrayContainer<FOO>(fooArray);
  auto bar2 = ArrayContainer<FOO*>(fooPointerArray);
}
</code>```

How can I specialize the GetItem() function for the pointer and the instance variant (without writing all the other functions twice)?

答:
Defer to an overloaded free function:

```<code>#include <cstddef>

class FOO {};

template<class T>
T* get_t(T* array, std::size_t index)
{
    return array + index;
}

template<class T>
T* get_t(T** array, std::size_t index)
{
    return array[index];
}

template<class T>
class ArrayContainer {
    T *array;
public:
    ArrayContainer(T * array)
    : array(array)
    {
    }

    /*
     * A lot of other functions.
     * I want to write them only once
     * ....
     */

     auto GetItem(std::size_t index)
     {
         return get_t(array, index);
     }

};

void usage() {
  FOO fooArray[100];
  FOO * fooPointerArray[100];

  auto bar1 = ArrayContainer<FOO>(fooArray);
  auto bar2 = ArrayContainer<FOO*>(fooPointerArray);

  FOO* f = bar1.GetItem(2);
  f = bar2.GetItem(5);
}
</code>```

or, for better encapsulation, derive privately from a services class which exports the getter function overloads as static members.

```<code>#include <cstddef>

class FOO {};

struct ArrayContainerServices
{
    template<class T>
    static
    T* ImplementGetItem(T* array, std::size_t index)
    {
        return array + index;
    }

    template<class T>
    static
    T* ImplementGetItem(T** array, std::size_t index)
    {
        return array[index];
    }
};

template<class T>
class ArrayContainer
: private ArrayContainerServices  // note - private inheritance
{
    T *array;
public:
    ArrayContainer(T * array)
    : array(array)
    {
    }

    /*
     * A lot of other functions.
     * I want to write them only once
     * ....
     */

     auto GetItem(std::size_t index)
     {
         return ImplementGetItem(array, index);
     }

};

void usage() {
  FOO fooArray[100];
  FOO * fooPointerArray[100];

  auto bar1 = ArrayContainer<FOO>(fooArray);
  auto bar2 = ArrayContainer<FOO*>(fooPointerArray);

  FOO* f = bar1.GetItem(2);
  f = bar2.GetItem(5);
}
</code>```

Body:
I've a template where I want to use a pointer type or an instance type as the template parameter. An Example:

class FOO {};

class ItemGetter {
    virtual FOO * GetItem(int index) = 0;
};

template<class T>
class ArrayContainer : public ItemGetter {
    T *array;
    ArrayContainer(T * array) {
        this->array = array;
    }

    /*
     * A lot of other functions.
     * I want to write them only once
     * ....
     */

    /* If the T Parameter is an instance Type */
    FOO * GetItem(int index) {
        return &this->array[index];
    }
    /* If the T Parameter is an pointer Type */
    FOO * GetItem(int index) {
        return this->array[index];
    }
};

void usage() {
  FOO fooArray[100];
  FOO * fooPointerArray[100];

  auto bar1 = ArrayContainer<FOO>(fooArray);
  auto bar2 = ArrayContainer<FOO*>(fooPointerArray);
}

How can I specialize the GetItem() function for the pointer and the instance variant (without writing all the other functions twice)?

Body:
Defer to an overloaded free function:

#include <cstddef>

class FOO {};

template<class T>
T* get_t(T* array, std::size_t index)
{
    return array + index;
}

template<class T>
T* get_t(T** array, std::size_t index)
{
    return array[index];
}

template<class T>
class ArrayContainer {
    T *array;
public:
    ArrayContainer(T * array)
    : array(array)
    {
    }

    /*
     * A lot of other functions.
     * I want to write them only once
     * ....
     */

     auto GetItem(std::size_t index)
     {
         return get_t(array, index);
     }

};

void usage() {
  FOO fooArray[100];
  FOO * fooPointerArray[100];

  auto bar1 = ArrayContainer<FOO>(fooArray);
  auto bar2 = ArrayContainer<FOO*>(fooPointerArray);

  FOO* f = bar1.GetItem(2);
  f = bar2.GetItem(5);
}

or, for better encapsulation, derive privately from a services class which exports the getter function overloads as static members.

#include <cstddef>

class FOO {};

struct ArrayContainerServices
{
    template<class T>
    static
    T* ImplementGetItem(T* array, std::size_t index)
    {
        return array + index;
    }

    template<class T>
    static
    T* ImplementGetItem(T** array, std::size_t index)
    {
        return array[index];
    }
};

template<class T>
class ArrayContainer
: private ArrayContainerServices  // note - private inheritance
{
    T *array;
public:
    ArrayContainer(T * array)
    : array(array)
    {
    }

    /*
     * A lot of other functions.
     * I want to write them only once
     * ....
     */

     auto GetItem(std::size_t index)
     {
         return ImplementGetItem(array, index);
     }

};

void usage() {
  FOO fooArray[100];
  FOO * fooPointerArray[100];

  auto bar1 = ArrayContainer<FOO>(fooArray);
  auto bar2 = ArrayContainer<FOO*>(fooPointerArray);

  FOO* f = bar1.GetItem(2);
  f = bar2.GetItem(5);
}


问:
unexpected EOF and busy buffer in (go-sql-driver/mysql) packets.go
I am getting the unexpected EOF and busy buffer error in go-sql-driver/mysql despite after setting the SetConnMaxLifetime, SetMaxIdleConns and SetMaxOpenConns as suggested here. Can anyone tell me the proper solution of this issue nothing seems to work for me?

```<code>db, err := sql.Open("mysql", "USERNAME:PASSWORD@tcp(IP:PORT)/DB?charset=utf8")
checkErr(err)
db.SetConnMaxLifetime(time.Second * 5)
db.SetMaxIdleConns(0)
db.SetMaxOpenConns(151)

rows, err := db.Query("Select col1, col2, col3 from tbl")
checkErr(err)

for rows.Next() {
    var col1 string
    var col2 int32
    var col3 uint64

    err = rows.Scan(&col1, &col2, &col3)
    checkErr(err)
    Process(col1, col2, col3)

}
</code>```

答:
I setup a local MySQL database and ran your code:

```<code>package main

import (
    "database/sql"
    "fmt"
    "log"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "root@tcp(localhost)/test?charset=utf8")
    if err != nil {
        log.Fatalln(err)
    }

    db.SetConnMaxLifetime(time.Second * 5)
    db.SetMaxIdleConns(0)
    db.SetMaxOpenConns(151)

    rows, err := db.Query("SELECT col1, col2, col3 FROM tbl2")
    if err != nil {
        log.Fatalln(err)
    }

    for rows.Next() {
        var col1 string
        var col2 int32
        var col3 uint64

        err = rows.Scan(&col1, &col2, &col3)
        if err != nil {
            log.Fatalln(err)
        }

        fmt.Println(col1, col2, col3)
    }
}
</code>```

..and it worked just fine for me. My CREATE TABLE statement looks like this:

```<code>CREATE TABLE `tbl2` (
`col1` varchar(25) DEFAULT NULL,
`col2` int(11) DEFAULT NULL,
`col3` bigint(20) unsigned DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

What does your table structure look like?

Body:
I am getting the unexpected EOF and busy buffer error in go-sql-driver/mysql despite after setting the SetConnMaxLifetime, SetMaxIdleConns and SetMaxOpenConns as suggested here. Can anyone tell me the proper solution of this issue nothing seems to work for me?

db, err := sql.Open("mysql", "USERNAME:PASSWORD@tcp(IP:PORT)/DB?charset=utf8")
checkErr(err)
db.SetConnMaxLifetime(time.Second * 5)
db.SetMaxIdleConns(0)
db.SetMaxOpenConns(151)

rows, err := db.Query("Select col1, col2, col3 from tbl")
checkErr(err)

for rows.Next() {
    var col1 string
    var col2 int32
    var col3 uint64

    err = rows.Scan(&col1, &col2, &col3)
    checkErr(err)
    Process(col1, col2, col3)

}

Body:
I setup a local MySQL database and ran your code:

package main

import (
    "database/sql"
    "fmt"
    "log"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "root@tcp(localhost)/test?charset=utf8")
    if err != nil {
        log.Fatalln(err)
    }

    db.SetConnMaxLifetime(time.Second * 5)
    db.SetMaxIdleConns(0)
    db.SetMaxOpenConns(151)

    rows, err := db.Query("SELECT col1, col2, col3 FROM tbl2")
    if err != nil {
        log.Fatalln(err)
    }

    for rows.Next() {
        var col1 string
        var col2 int32
        var col3 uint64

        err = rows.Scan(&col1, &col2, &col3)
        if err != nil {
            log.Fatalln(err)
        }

        fmt.Println(col1, col2, col3)
    }
}

..and it worked just fine for me. My CREATE TABLE statement looks like this:

CREATE TABLE `tbl2` (
`col1` varchar(25) DEFAULT NULL,
`col2` int(11) DEFAULT NULL,
`col3` bigint(20) unsigned DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

What does your table structure look like?