问:
Color define into css
I need create a static list of color definitions into css file.
Like this:

```<code>.color_test: #00ff00;
</code>```

And use this definition in other classes, like this:

```<code>background-color: .color_test;
</code>```

It's possible using only css?

答:
I wanted to be able to do this with js, and change the valued of the defined colors arbritrarily, so I made this.

It watches where it modifies the css so it isn't constantly searching through it once it's found its targets.

The issue with it is that is currently only works for style elements, which can probably be changed pretty easily.

var colorWheel = ["#F8F", "#333", "#A68", "green", "orange", "rgba(0,0,0,0.5)"]

function randomColor() {
  var color = colorWheel[~~(Math.random() * colorWheel.length)];
  StyleVars.setVar('testColor', color);
}

/************************
 *  Style Vars CSS Hack
 *  by: Seph Reed
 *
 *
 *   A js way to replace keywords with values in style elements, at your leisure.
 *   Keeps track of insertion points to allow updates to key/value pairs without
 *   researching the entire style element
 *
 *************************/

StyleVars = {};
StyleVars.rules = {};
StyleVars.rules["lightShadow"] = "rgba(0,0,0,0.1)";
StyleVars.rules["medShadow"] = "rgba(0,0,0,0.3)";
StyleVars.rules["heavyShadow"] = "rgba(0,0,0,0.5)";
StyleVars.rules["testColor"] = "#0FF";

StyleVars.lastID = 0;
StyleVars.mods = [];

StyleVars.setVar = function(keyword, value) {
  for (var key in StyleVars.rules) {
    if (StyleVars.rules[key].includes("keyword") ||
      value.includes("key")) {
      err("Can not include a keyword in a value", keyword, key, value, StyleVars.rules[key]);
      return;
    }
  }

  StyleVars.rules[keyword] = value;

  for (var i = 0; i < StyleVars.mods.length; i++)
    StyleVars.applyVar(StyleVars.mods[i].domNode, keyword);
}

StyleVars.modStyle = function(modMe) {

  if (modMe.StyleID === undefined) {
    var ID = modMe.pineStyleID = StyleVars.lastID++;
    mod = StyleVars.mods[ID] = {};
    mod.domNode = modMe;
    mod.hist = [];
  }

  for (var key in StyleVars.rules) {
    StyleVars.injectVar(modMe, key);

  }

}

StyleVars.injectVar = function(modMe, key) {
  var ID = modMe.pineStyleID;
  var modHist = StyleVars.mods[ID].hist;
  var replaceWith = StyleVars.rules[key];

  var modHistIndex = 0;
  var currentModOffset = 0;

  var regex = new RegExp(key, 'g')

  modMe.textContent = modMe.textContent.replace(regex, function(match, offset) {

    while (modHistIndex < modHist.length && offset + currentModOffset > modHist[modHistIndex].virginOffset) {
      currentModOffset += modHist[modHistIndex].modOffset;
      modHistIndex++;
    }

    var addMod = {};
    addMod.virginOffset = offset - currentModOffset;
    //"older" relpaced with "new" = 3 - 5 = -2 offset for all folowing indexes
    addMod.modOffset = replaceWith.length - key.length;
    addMod.key = key;
    addMod.currentLength = replaceWith.length;
    modHist.splice(modHistIndex, 0, addMod);
    modHistIndex++;

    return replaceWith;
  });
}

StyleVars.applyVar = function(styleNode, key) {
  var ID = styleNode.pineStyleID;
  var modHist = StyleVars.mods[ID].hist;
  var replaceWith = StyleVars.rules[key];

  var modHistIndex = 0;
  var currentModOffset = 0;

  for (var i = 0; i < modHist.length; i++) {
    var mod = modHist[i];
    if (mod.key == key) {
      styleNode.textContent = styleNode.textContent.slice(0, mod.virginOffset + currentModOffset) +
        replaceWith +
        styleNode.textContent.slice(mod.virginOffset + currentModOffset + mod.currentLength);

      mod.modOffset = replaceWith.length - key.length;
      mod.currentLength = replaceWith.length;
    }

    currentModOffset += mod.modOffset;
  }
}

//apply to all style elemnts on content ready
//ready listener removed for use in snippet
//document.addEventListener("DOMContentReady", function() {
var styles = document.getElementsByTagName("style");

for (var i = 0; i < styles.length; i++) {
  StyleVars.modStyle(styles[i]);
}
//});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><style>
  div {
     margin: 20px;
  }

  #testDiv1,
  #testDiv2 {
    height: 50px;
    width: 50px;
    border: 1px solid black;
  }

    #testDiv1 {
       background: linear-gradient(testColor, blue);
    }

    #testDiv2 {
       border-color: testColor;
    }

  #testDiv3 {
    color: testColor;
  }
</style>

<div id="testDiv1"></div>
<div id="testDiv2">border</div>
<div id="testDiv3">This div has the color used for font</div>
<button onClick="randomColor()">Change Color</button></code>```

Title: Color define into css

Body:
I need create a static list of color definitions into css file.
Like this:

.color_test: #00ff00;

And use this definition in other classes, like this:

background-color: .color_test;

It's possible using only css?

Body:
I wanted to be able to do this with js, and change the valued of the defined colors arbritrarily, so I made this.

It watches where it modifies the css so it isn't constantly searching through it once it's found its targets.

The issue with it is that is currently only works for style elements, which can probably be changed pretty easily.

var colorWheel = ["#F8F", "#333", "#A68", "green", "orange", "rgba(0,0,0,0.5)"]

function randomColor() {
  var color = colorWheel[~~(Math.random() * colorWheel.length)];
  StyleVars.setVar('testColor', color);
}

/************************
 *  Style Vars CSS Hack
 *  by: Seph Reed
 *
 *
 *   A js way to replace keywords with values in style elements, at your leisure.
 *   Keeps track of insertion points to allow updates to key/value pairs without
 *   researching the entire style element
 *
 *************************/

StyleVars = {};
StyleVars.rules = {};
StyleVars.rules["lightShadow"] = "rgba(0,0,0,0.1)";
StyleVars.rules["medShadow"] = "rgba(0,0,0,0.3)";
StyleVars.rules["heavyShadow"] = "rgba(0,0,0,0.5)";
StyleVars.rules["testColor"] = "#0FF";

StyleVars.lastID = 0;
StyleVars.mods = [];

StyleVars.setVar = function(keyword, value) {
  for (var key in StyleVars.rules) {
    if (StyleVars.rules[key].includes("keyword") ||
      value.includes("key")) {
      err("Can not include a keyword in a value", keyword, key, value, StyleVars.rules[key]);
      return;
    }
  }

  StyleVars.rules[keyword] = value;

  for (var i = 0; i < StyleVars.mods.length; i++)
    StyleVars.applyVar(StyleVars.mods[i].domNode, keyword);
}

StyleVars.modStyle = function(modMe) {

  if (modMe.StyleID === undefined) {
    var ID = modMe.pineStyleID = StyleVars.lastID++;
    mod = StyleVars.mods[ID] = {};
    mod.domNode = modMe;
    mod.hist = [];
  }

  for (var key in StyleVars.rules) {
    StyleVars.injectVar(modMe, key);

  }

}

StyleVars.injectVar = function(modMe, key) {
  var ID = modMe.pineStyleID;
  var modHist = StyleVars.mods[ID].hist;
  var replaceWith = StyleVars.rules[key];

  var modHistIndex = 0;
  var currentModOffset = 0;

  var regex = new RegExp(key, 'g')

  modMe.textContent = modMe.textContent.replace(regex, function(match, offset) {

    while (modHistIndex < modHist.length && offset + currentModOffset > modHist[modHistIndex].virginOffset) {
      currentModOffset += modHist[modHistIndex].modOffset;
      modHistIndex++;
    }

    var addMod = {};
    addMod.virginOffset = offset - currentModOffset;
    //"older" relpaced with "new" = 3 - 5 = -2 offset for all folowing indexes
    addMod.modOffset = replaceWith.length - key.length;
    addMod.key = key;
    addMod.currentLength = replaceWith.length;
    modHist.splice(modHistIndex, 0, addMod);
    modHistIndex++;

    return replaceWith;
  });
}

StyleVars.applyVar = function(styleNode, key) {
  var ID = styleNode.pineStyleID;
  var modHist = StyleVars.mods[ID].hist;
  var replaceWith = StyleVars.rules[key];

  var modHistIndex = 0;
  var currentModOffset = 0;

  for (var i = 0; i < modHist.length; i++) {
    var mod = modHist[i];
    if (mod.key == key) {
      styleNode.textContent = styleNode.textContent.slice(0, mod.virginOffset + currentModOffset) +
        replaceWith +
        styleNode.textContent.slice(mod.virginOffset + currentModOffset + mod.currentLength);

      mod.modOffset = replaceWith.length - key.length;
      mod.currentLength = replaceWith.length;
    }

    currentModOffset += mod.modOffset;
  }
}

//apply to all style elemnts on content ready
//ready listener removed for use in snippet
//document.addEventListener("DOMContentReady", function() {
var styles = document.getElementsByTagName("style");

for (var i = 0; i < styles.length; i++) {
  StyleVars.modStyle(styles[i]);
}
//});

<style>
  div {
     margin: 20px;
  }

  #testDiv1,
  #testDiv2 {
    height: 50px;
    width: 50px;
    border: 1px solid black;
  }

    #testDiv1 {
       background: linear-gradient(testColor, blue);
    }

    #testDiv2 {
       border-color: testColor;
    }

  #testDiv3 {
    color: testColor;
  }
</style>

<div id="testDiv1"></div>
<div id="testDiv2">border</div>
<div id="testDiv3">This div has the color used for font</div>
<button onClick="randomColor()">Change Color</button>


来源: stackexchange

问:
PHP regex pattern match recursive
I have this in a function which is supposed to replace any sequence of parentheses with what is enclosed in it like (abc) becomes abc any where it appears even recursively because parens can be nested.

```<code>$return =   preg_replace_callback(
    '|(\((.+)\))+|',
    function ($matches) {
        return $matches[2];
    },
    $s
);
</code>```

when the above regex is fed this string "a(bcdefghijkl(mno)p)q" as input it returns "ap)onm(lkjihgfedcbq". This shows the regex is matched once. What can I do to make it continue to match even inside already made matches and produce this `abcdefghijklmnopq'"

答:
To match balanced parenthetical substrings you may use a well-known \((?:[^()]++|(?R))*\) pattern (described in Matching Balanced Constructs), inside a preg_replace_callback method, where the match value can be further manipulated (just remove all ( and ) symbols from the match that is easy to do even without a regex:

```<code>$re = '/\((?:[^()]++|(?R))*\)/';
$str = 'a(bcdefghijkl(mno)p)q((('; // Added three ( at the end
$result = preg_replace_callback($re, function($m) {
    return str_replace(array('(',')'), '', $m[0]);
}, $str);
echo $result; // => abcdefghijklmnopq(((
</code>```

See the PHP demo

To get overlapping matches, you need to use a known technique, capturing inside a positive lookahead, but you won't be able to perform two operations at once (replacing and matching), you can run matching first, and then replace:

```<code>$re = '/(?=(\((?:[^()]++|(?1))*\)))/';
$str = 'a(bcdefghijkl(mno)p)q(((';
preg_match_all($re, $str, $m);
print_r($m[1]);
// => Array ( [0] => (bcdefghijkl(mno)p)  [1] => (mno) )
</code>```

See the PHP demo.

ContentLicense: CC BY-SA 3.0

Title: PHP regex pattern match recursive

Body:
I have this in a function which is supposed to replace any sequence of parentheses with what is enclosed in it like (abc) becomes abc any where it appears even recursively because parens can be nested.

$return =   preg_replace_callback(
    '|(\((.+)\))+|',
    function ($matches) {
        return $matches[2];
    },
    $s
);

when the above regex is fed this string "a(bcdefghijkl(mno)p)q" as input it returns "ap)onm(lkjihgfedcbq". This shows the regex is matched once. What can I do to make it continue to match even inside already made matches and produce this `abcdefghijklmnopq'"

Body:
To match balanced parenthetical substrings you may use a well-known \((?:[^()]++|(?R))*\) pattern (described in Matching Balanced Constructs), inside a preg_replace_callback method, where the match value can be further manipulated (just remove all ( and ) symbols from the match that is easy to do even without a regex:

$re = '/\((?:[^()]++|(?R))*\)/';
$str = 'a(bcdefghijkl(mno)p)q((('; // Added three ( at the end
$result = preg_replace_callback($re, function($m) {
    return str_replace(array('(',')'), '', $m[0]);
}, $str);
echo $result; // => abcdefghijklmnopq(((

See the PHP demo

To get overlapping matches, you need to use a known technique, capturing inside a positive lookahead, but you won't be able to perform two operations at once (replacing and matching), you can run matching first, and then replace:

$re = '/(?=(\((?:[^()]++|(?1))*\)))/';
$str = 'a(bcdefghijkl(mno)p)q(((';
preg_match_all($re, $str, $m);
print_r($m[1]);
// => Array ( [0] => (bcdefghijkl(mno)p)  [1] => (mno) )

See the PHP demo.


问:
Table rails_project.users doesn't exist: SHOW FULL FIELDS FROM users
I have been trying to move my current rails application's db from sqlite to MYSQL.
I have made the changes in database.yml file. But its been many times I ran rake:db create and migrate, but nothing does not work for me.

I end up in the error stating "Table 'rails_project.users' doesn't exist: SHOW FULL FIELDS FROM users".

My db name is rails_project and I am using devise authentication where the table name is users.

I am so frustrated with this issue.

Can anyone help me?

database.yml:

```<code>development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: rails_project
  pool: 5
  username: root
  password: root
  host : localhost
  socket: /var/run/mysqld/mysqld.sock
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: rails_project
  pool: 5
  username: root
  password: root
  host : localhost
  socket: /var/run/mysqld/mysqld.sock
production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: rails_project
  pool: 5
  username: root
  password: root
  host : localhost
  socket: /var/run/mysqld/mysqld.sock
</code>```

migrated file:

```<code>   class DeviseCreateUsers < ActiveRecord::Migration
    def change
      create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""
</code>```

答:
This means that you are trying to use something before define its table, in my case I tried to use some code in factories.rb:

```<code> Assesment.new.questions ...
</code>```

So when I ran my code on travis during rake db:schema:load all code is interpreted and in that part it got same error, solution is:

Avoid using a model before define its table

Use lazy syntax wrapping with { and }, at least in FactoryGirl use

Just tried to read carefully log to see was line of your code is triggering the error

Body:
I have been trying to move my current rails application's db from sqlite to MYSQL.
I have made the changes in database.yml file. But its been many times I ran rake:db create and migrate, but nothing does not work for me.

I end up in the error stating "Table 'rails_project.users' doesn't exist: SHOW FULL FIELDS FROM users".

My db name is rails_project and I am using devise authentication where the table name is users.

I am so frustrated with this issue.

Can anyone help me?

database.yml:

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: rails_project
  pool: 5
  username: root
  password: root
  host : localhost
  socket: /var/run/mysqld/mysqld.sock
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: rails_project
  pool: 5
  username: root
  password: root
  host : localhost
  socket: /var/run/mysqld/mysqld.sock
production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: rails_project
  pool: 5
  username: root
  password: root
  host : localhost
  socket: /var/run/mysqld/mysqld.sock

migrated file:

   class DeviseCreateUsers < ActiveRecord::Migration
    def change
      create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""

Body:
This means that you are trying to use something before define its table, in my case I tried to use some code in factories.rb:

 Assesment.new.questions ...

So when I ran my code on travis during rake db:schema:load all code is interpreted and in that part it got same error, solution is:

Avoid using a model before define its table

Use lazy syntax wrapping with { and }, at least in FactoryGirl use

Just tried to read carefully log to see was line of your code is triggering the error


问:
Place frame when taking photo Android Studio
I want to develop an application that takes a photograph and allows you to select a frame for photography.

I already have developed the interfaces, like taking the photo and storing it.

But I put a frame to the photo taken I could not.

Any recommendation?

答:
Thanks for the help, I put my solution :

ImageView Resultado;

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Bitmap miBitmap = Bitmap.createBitmap(1000, 1000, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(miBitmap);
    Paint paint = new Paint();

    c.drawBitmap(drawableToBitmap(R.mipmap.ic_launcher), 500, 500, paint); // draw your photo over canvas, keep indentation in mind (x and y)
    c.drawBitmap(drawableToBitmap(R.drawable.silver_frame), 0, 0, paint); // now draw your frame on top of the image

    Resultado.setImageBitmap(miBitmap);
}
public Bitmap drawableToBitmap(int imagen){
    return BitmapFactory.decodeResource(getApplicationContext().getResources(), imagen);
}
</code>```

Body:
Thanks for the help, I put my solution :

ImageView Resultado;

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

    Bitmap miBitmap = Bitmap.createBitmap(1000, 1000, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(miBitmap);
    Paint paint = new Paint();

    c.drawBitmap(drawableToBitmap(R.mipmap.ic_launcher), 500, 500, paint); // draw your photo over canvas, keep indentation in mind (x and y)
    c.drawBitmap(drawableToBitmap(R.drawable.silver_frame), 0, 0, paint); // now draw your frame on top of the image

    Resultado.setImageBitmap(miBitmap);
}
public Bitmap drawableToBitmap(int imagen){
    return BitmapFactory.decodeResource(getApplicationContext().getResources(), imagen);
}


问:
MDX How to use CASE to check a level value
I'm new to BI and MDX and have a need to do this. I have a dimension that looks like this:

```<code><Dimension name="JobDim">
    <Hierarchy name="Job" hasAll="true" primaryKey="jobID">
        <Table name="JobDim" schema="dw"/>
        <Level name="Job Code" column="jobCode" type="String" uniqueMembers="false"/>
    </Hierarchy>
    <Hierarchy name="Job Status" hasAll="true" primaryKey="jobID">
        <Table name="JobDim" schema="dw"/>
        <Level name="Job Status" column="status" type="String" hideMemberIf="IfBlankName"/>
    </Hierarchy>
</Dimension>
</code>```

I have a calculated measure and I need to set the value of this measure depending on the 'job status', so if the job is 'complete', set the measure to 100, otherwise set its value to 200 (the value to be used is more complex but for this example purpose, this is good enough). I'm using something like this:

```<code>    <CalculatedMember name="Earned Revenue" dimension="Measures" formatString="$#,###.00;($#,###.00)" aggregator="sum">
        <Formula>case [JobDim.Job Status].CurrentMember
                    when [JobDim.Job Status].[Complete] then 100
                    else 200
                 end
        </Formula>
    </CalculatedMember>
</code>```

I've tried different variations of the code above, but none seem to work (some even cause a crash when I try to run the report). Anyone has done something like this in the past that can provide me an answer?

答:
Better to use IIF than CASE if possible as it is generally quicker. Assuming [JobDim.Job Status].[Complete] is a member in your cube then the IS operator should be ok to use:

```<code>IIF(
     [JobDim.Job Status].CurrentMember
                    IS [JobDim.Job Status].[Complete]
     ,100
     ,200
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to BI and MDX and have a need to do this. I have a dimension that looks like this:

<Dimension name="JobDim">
    <Hierarchy name="Job" hasAll="true" primaryKey="jobID">

        <Level name="Job Code" column="jobCode" type="String" uniqueMembers="false"/>
    </Hierarchy>
    <Hierarchy name="Job Status" hasAll="true" primaryKey="jobID">

        <Level name="Job Status" column="status" type="String" hideMemberIf="IfBlankName"/>
    </Hierarchy>
</Dimension>

I have a calculated measure and I need to set the value of this measure depending on the 'job status', so if the job is 'complete', set the measure to 100, otherwise set its value to 200 (the value to be used is more complex but for this example purpose, this is good enough). I'm using something like this:

    <CalculatedMember name="Earned Revenue" dimension="Measures" formatString="$#,###.00;($#,###.00)" aggregator="sum">
        <Formula>case [JobDim.Job Status].CurrentMember
                    when [JobDim.Job Status].[Complete] then 100
                    else 200
                 end
        </Formula>
    </CalculatedMember>

I've tried different variations of the code above, but none seem to work (some even cause a crash when I try to run the report). Anyone has done something like this in the past that can provide me an answer?

Body:
Better to use IIF than CASE if possible as it is generally quicker. Assuming [JobDim.Job Status].[Complete] is a member in your cube then the IS operator should be ok to use:

IIF(
     [JobDim.Job Status].CurrentMember
                    IS [JobDim.Job Status].[Complete]
     ,100
     ,200
)


问:
Can not find implicit conversion for a parameter of method with lower type bound
I have this code:

```<code>class Action[T]

class Insert[T] extends Action[T]

case class Quoted[T]()

implicit def unquote[T](q: Quoted[T]): T = {
  throw new Exception("Success")
}

def test[A <: Action[_]](a: A): A = {
  return a
}

try {
  test[Insert[String]](Quoted[Insert[String]])
  test(unquote(Quoted[Insert[String]]))
  // test(Quoted[Insert[String]]) // does not compile
} catch {
  case e: Exception => print(e.getMessage())
}
</code>```

Scalafiddle

Commented line fails during compilation with:

```<code>error: inferred type arguments [ScalaFiddle.Quoted[ScalaFiddle.Insert[String]]] do not conform to method test's type parameter bounds [A <: ScalaFiddle.Action[_]]
    test(Quoted[Insert[String]])
error: type mismatch;
 found   : ScalaFiddle.Quoted[ScalaFiddle.Insert[String]]
 required: A
    test(Quoted[Insert[String]])
</code>```

Is there any way to make it compile without specifying type parameter or explicitly using conversion function as in previous two lines?

答:
Perhaps you could overload the test method like so:

```<code>def test[A, B <: Action[_]](a: A)(implicit f: A => B): B = f(a)
</code>```

Then this does compile and work:

```<code>test(Quoted[Insert[String]])
</code>```

I'm not positive about an explanation for why this is necessary, though. Perhaps if you're not explicit about the type parameter, it gets inferred and checked against bounds before any implicit conversions are applied. In your example, the implicit conversion search is triggered by a mismatch between the type parameter and the argument.

Body:
I have this code:

class Action[T]

class Insert[T] extends Action[T]

case class Quoted[T]()

implicit def unquote[T](q: Quoted[T]): T = {
  throw new Exception("Success")
}

def test[A <: Action[_]](a: A): A = {
  return a
}

try {
  test[Insert[String]](Quoted[Insert[String]])
  test(unquote(Quoted[Insert[String]]))
  // test(Quoted[Insert[String]]) // does not compile
} catch {
  case e: Exception => print(e.getMessage())
}

Scalafiddle

Commented line fails during compilation with:

error: inferred type arguments [ScalaFiddle.Quoted[ScalaFiddle.Insert[String]]] do not conform to method test's type parameter bounds [A <: ScalaFiddle.Action[_]]
    test(Quoted[Insert[String]])
error: type mismatch;
 found   : ScalaFiddle.Quoted[ScalaFiddle.Insert[String]]
 required: A
    test(Quoted[Insert[String]])

Is there any way to make it compile without specifying type parameter or explicitly using conversion function as in previous two lines?

Body:
Perhaps you could overload the test method like so:

def test[A, B <: Action[_]](a: A)(implicit f: A => B): B = f(a)

Then this does compile and work:

test(Quoted[Insert[String]])

I'm not positive about an explanation for why this is necessary, though. Perhaps if you're not explicit about the type parameter, it gets inferred and checked against bounds before any implicit conversions are applied. In your example, the implicit conversion search is triggered by a mismatch between the type parameter and the argument.


问:
Repeating image count for both directories
I'm using the glob function in PHP to browse directories and trying to also match up only the image files. This is working but when I try to count the images in each directory, it repeats the count of the first directory for the others. For example, directory 1 has 6 images and directory 2 has 4 images but when I try to display the count for each directory, it shows 6 images for directory 2 and so forth.

Here is the code I have in place:

```<code>public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();

    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }
    //var_dump($files); exit;

    $data = array(
        'albums' => array_values($dirname),
        'files'  => $files,
    );

    return new ViewModel(array('album' => $data['albums'], 'files' => $data['files']));
}
</code>```

The results of var_dump()

```<code> array(9) { [0]=> string(96) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/massive snow.jpg"
[1]=> string(91) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/mom-jon.jpg"
[2]=> string(90) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/sunset.jpg"
[3]=> string(85) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/cref.jpg"
[4]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/diploma.jpg"
[5]=> string(86) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/eeyor.jpg"
[6]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother-jaws.jpg"
[7]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother.jpg"
[8]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/goat_singing.jpg" }
</code>```

It is getting all the images from each directory as expected but what I really need to do is separate the images so I can have a accurate count for each directory and not just have it show the whole count (9)

The view code:

```<code><div class="w3-col m7">
    <div class="w3-row-padding">
        <div class="w3-col m12">
            <div class="w3-card-2 w3-round w3-white">
                <div class="w3-container w3-padding" id="view-photo-albums">
                    <p class="w3-center">Current Albums</p>
                    <br>
                    <?php
foreach ($this->album as $albums):
    ?>
                    <p>
                        <?php echo $albums; ?> - Number of images: <?php echo $this->files; ?>
                    </p>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Any help would be appreciated.

Update:

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

答:
In your public function de last dir will be the directory used in your second statement, which results in only the files counted in this folder.

change this:

```<code>foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);
    }

    foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
         $files[] = $images;
    }
</code>```

into

```<code>foreach (glob(getcwd() . '/images/albums/*', GLOB_ONLYDIR) as $dir)
{
     $dirname[] = basename($dir);

         foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images)
         {
          $files[] = $images;
         }
}
</code>```

Body:
I'm using the glob function in PHP to browse directories and trying to also match up only the image files. This is working but when I try to count the images in each directory, it repeats the count of the first directory for the others. For example, directory 1 has 6 images and directory 2 has 4 images but when I try to display the count for each directory, it shows 6 images for directory 2 and so forth.

Here is the code I have in place:

public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();

    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }
    //var_dump($files); exit;

    $data = array(
        'albums' => array_values($dirname),
        'files'  => $files,
    );

    return new ViewModel(array('album' => $data['albums'], 'files' => $data['files']));
}

The results of var_dump()

 array(9) { [0]=> string(96) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/massive snow.jpg"
[1]=> string(91) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/mom-jon.jpg"
[2]=> string(90) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/sunset.jpg"
[3]=> string(85) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/cref.jpg"
[4]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/diploma.jpg"
[5]=> string(86) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/eeyor.jpg"
[6]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother-jaws.jpg"
[7]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother.jpg"
[8]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/goat_singing.jpg" }

It is getting all the images from each directory as expected but what I really need to do is separate the images so I can have a accurate count for each directory and not just have it show the whole count (9)

The view code:

Current Albums

                    <?php
foreach ($this->album as $albums):
    ?>

                        <?php echo $albums; ?> - Number of images: <?php echo $this->files; ?>

                    <?php endforeach; ?>

Any help would be appreciated.

Update:

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

Body:
In your public function de last dir will be the directory used in your second statement, which results in only the files counted in this folder.

change this:

foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);
    }

    foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
         $files[] = $images;
    }

into

foreach (glob(getcwd() . '/images/albums/*', GLOB_ONLYDIR) as $dir)
{
     $dirname[] = basename($dir);

         foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images)
         {
          $files[] = $images;
         }
}


问:
Failed to resolve: com.crashlytics.sdk.android:crashlytics:2.6.7
I added the following the in my project's build.gradle file:

```<code>Buildscript {
   repositories {
       jcenter()
   maven { url 'https://maven.fabric.io/public' }
}
dependencies {
   classpath 'io.fabric.tools:gradle:1.14.3'
}
</code>```

I addded this in the AndroidManifest.xml file:

```<code><meta-data
   android:name="io.fabric.ApiKey"
   android:value="apiKeyValue"/>
</code>```

I added this in the build.gradle(app) file:

```<code>apply plugin: 'io.fabric'
</code>```

And the following dependency:

```<code>compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}
</code>```

After all this, why does not resolve the Crashlytics dependency?

答:
It is recommended to use 1.+ for the Fabric plugin dependency to use the latest version rather than specifying a specific version:

```<code>classpath 'io.fabric.tools:gradle:1.+'
</code>```

There are detailed instructions on how to integrate Crashlytics into Android studio here.

Body:
I added the following the in my project's build.gradle file:

Buildscript {
   repositories {
       jcenter()
   maven { url 'https://maven.fabric.io/public' }
}
dependencies {
   classpath 'io.fabric.tools:gradle:1.14.3'
}

I addded this in the AndroidManifest.xml file:

<meta-data
   android:name="io.fabric.ApiKey"
   android:value="apiKeyValue"/>

I added this in the build.gradle(app) file:

apply plugin: 'io.fabric'

And the following dependency:

compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
    transitive = true;
}

After all this, why does not resolve the Crashlytics dependency?

Body:
It is recommended to use 1.+ for the Fabric plugin dependency to use the latest version rather than specifying a specific version:

classpath 'io.fabric.tools:gradle:1.+'

There are detailed instructions on how to integrate Crashlytics into Android studio here.


问:
Format data from store before binding
I have a store with data like this:

name: "black", color: "RGB: 0, 0, 0"

Now I want to create a grid that shows the data with an extra column that shows a thumbnail of the color. Basically just a small square with a background color. I know there is tpl and renderer but the documentation advises using bind. So how can I transform a field from the store with bind? There's Ext.util.Format and I can make it work by combining several formatters but it would be much cleaner if I could use my own function.

答:
The first thing you have to do is to generate a color value in an format accepted by css. For this you can use the calculate method of Ext.data.field.Field. There are many other ways to do this.

```<code>Ext.define('Color', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'color',
        type: 'string'
    }, {
        name: 'displayColor',
        type: 'string',
        calculate: function (data) {

            var color = data.color;
            //parse your value to CSS Colors here
            return '#FF0000';
        }
    }]
});
</code>```

To display the background color in the column, I would create a new column widget. This would take care of drawing the cell.

```<code>Ext.define('Ext.ux.BackgroundVisualize', {
    extend: 'Ext.Gadget',
    xtype: ['myBackgroundwidget'],

    template: [{
        reference: 'backgroundEl'
    }],

    defaultBindProperty: 'value',

    setValue: function (value, oldValue) {
        this.el.up('td').setStyle('background', value);
    }
});
</code>```

This new widget must then only be used as a column in the grid.

```<code>{
    text: 'Preview',
    xtype: 'widgetcolumn',
    widget: {
        xtype: 'myBackgroundwidget',
        bind: '{record.displayColor}'
    }
}
</code>```

Here is the complete example:

https://fiddle.sencha.com/#view/editor&fiddle/22ln

Title: Format data from store before binding

Body:
The first thing you have to do is to generate a color value in an format accepted by css. For this you can use the calculate method of Ext.data.field.Field. There are many other ways to do this.

Ext.define('Color', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'color',
        type: 'string'
    }, {
        name: 'displayColor',
        type: 'string',
        calculate: function (data) {

            var color = data.color;
            //parse your value to CSS Colors here
            return '#FF0000';
        }
    }]
});

To display the background color in the column, I would create a new column widget. This would take care of drawing the cell.

Ext.define('Ext.ux.BackgroundVisualize', {
    extend: 'Ext.Gadget',
    xtype: ['myBackgroundwidget'],

    template: [{
        reference: 'backgroundEl'
    }],

    defaultBindProperty: 'value',

    setValue: function (value, oldValue) {
        this.el.up('td').setStyle('background', value);
    }
});

This new widget must then only be used as a column in the grid.

{
    text: 'Preview',
    xtype: 'widgetcolumn',
    widget: {
        xtype: 'myBackgroundwidget',
        bind: '{record.displayColor}'
    }
}

Here is the complete example:

https://fiddle.sencha.com/#view/editor&fiddle/22ln


问:
Changing the Trashcan icon in the dock
Is it possible to write a program for Mac OS X that monitors the trashcan and changes the icon dynamically when you fill the can?</p>

答:
The NSDockTile class allows you to make changes to your application's icon in the dock:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSDockTile_Class/Reference/Reference.html

The Trash is actually a hidden folder in the user's home folder called .Trash
I guess you could monitor whether or not it's empty by periodically finding the size of the folder. Or you could run ls using NSTask, and find out whether there are any files left in it.

ContentLicense: CC BY-SA 2.5

Title: Changing the Trashcan icon in the dock


问:
comm.bcast not working properly
I am trying to test a simple mpi code on python with the following code :

```<code>from scipy.sparse import csr_matrix
from mpi4py import MPI

comm=MPI.COMM_WORLD
rank=comm.Get_rank()
size=comm.Get_size()

if rank == 0:
    data = [1, 2, 3, 4, 5]
    indices = [1, 3, 2, 1, 0]
    indptr = [0, 2, 3, 4, 5]
    #A=csr_matrix((data,indices,indptr),shape=(4,4))

data=comm.bcast(data, root=0)
indices=comm.bcast(indices, root=0)
indptr=comm.bcast(indptr, root=0)

print rank,data,indices,indptr
</code>```

which returns the following error:

```<code>Traceback (most recent call last):
  File "test.py", line 14, in <module>
    data=comm.bcast(data, root=0)
NameError: name 'data' is not defined
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    data=comm.bcast(data, root=0)
NameError: name 'data' is not defined
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    data=comm.bcast(data, root=0)
NameError: name 'data' is not defined
0 [1, 2, 3, 4, 5] [1, 3, 2, 1, 0] [0, 2, 3, 4, 5]
-------------------------------------------------------
Primary job  terminated normally, but 1 process returned
a non-zero exit code.. Per user-direction, the job has been aborted.
-------------------------------------------------------
--------------------------------------------------------------------------
mpirun detected that one or more processes exited with non-zero status, thus causing
the job to be terminated. The first process to do so was:

  Process name: [[10263,1],1]
  Exit code:    1
</code>```

It seems like the error is due to me not using comm.bcast properly, but that is exactly how its used in the docs.

答:
you are defining data in the if block. What happens when the if block is false? the variable data is not defined.

```<code>from scipy.sparse import csr_matrix
from mpi4py import MPI

comm=MPI.COMM_WORLD
rank=comm.Get_rank()
size=comm.Get_size()

data = []
indices = []
indptr = []

if rank == 0:
    data = [1, 2, 3, 4, 5]
    indices = [1, 3, 2, 1, 0]
    indptr = [0, 2, 3, 4, 5]
    #A=csr_matrix((data,indices,indptr),shape=(4,4))

data=comm.bcast(data, root=0)
indices=comm.bcast(indices, root=0)
indptr=comm.bcast(indptr, root=0)

print rank,data,indices,indptr
</code>```

This should now work.

Title: comm.bcast not working properly

Body:
I am trying to test a simple mpi code on python with the following code :

from scipy.sparse import csr_matrix
from mpi4py import MPI

comm=MPI.COMM_WORLD
rank=comm.Get_rank()
size=comm.Get_size()

if rank == 0:
    data = [1, 2, 3, 4, 5]
    indices = [1, 3, 2, 1, 0]
    indptr = [0, 2, 3, 4, 5]
    #A=csr_matrix((data,indices,indptr),shape=(4,4))

data=comm.bcast(data, root=0)
indices=comm.bcast(indices, root=0)
indptr=comm.bcast(indptr, root=0)

print rank,data,indices,indptr

which returns the following error:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    data=comm.bcast(data, root=0)
NameError: name 'data' is not defined
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    data=comm.bcast(data, root=0)
NameError: name 'data' is not defined
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    data=comm.bcast(data, root=0)
NameError: name 'data' is not defined
0 [1, 2, 3, 4, 5] [1, 3, 2, 1, 0] [0, 2, 3, 4, 5]
-------------------------------------------------------
Primary job  terminated normally, but 1 process returned
a non-zero exit code.. Per user-direction, the job has been aborted.
-------------------------------------------------------
--------------------------------------------------------------------------
mpirun detected that one or more processes exited with non-zero status, thus causing
the job to be terminated. The first process to do so was:

  Process name: [[10263,1],1]
  Exit code:    1

It seems like the error is due to me not using comm.bcast properly, but that is exactly how its used in the docs.

Body:
you are defining data in the if block. What happens when the if block is false? the variable data is not defined.

from scipy.sparse import csr_matrix
from mpi4py import MPI

comm=MPI.COMM_WORLD
rank=comm.Get_rank()
size=comm.Get_size()

data = []
indices = []
indptr = []

if rank == 0:
    data = [1, 2, 3, 4, 5]
    indices = [1, 3, 2, 1, 0]
    indptr = [0, 2, 3, 4, 5]
    #A=csr_matrix((data,indices,indptr),shape=(4,4))

data=comm.bcast(data, root=0)
indices=comm.bcast(indices, root=0)
indptr=comm.bcast(indptr, root=0)

print rank,data,indices,indptr

This should now work.


问:
posting the respinse from an ajax call to another page
I am getting a Json array as response from an ajax call, I want to post this Json array data immediately to another page and redirect to that page. Does anyone know how I can do that

```<code> $.post("flightsearch/searchhome.php",{
                    fromairport2  : fromairport1,
                    toairport2    : toairport1
                }, function(data){
                       alert(data);
                       //var response = data;
                       //window.location.replace("flight-detail.php");
                });
</code>```

I want to post the response data i am getting to that page and redirecting to that page at the same time

答:
Once you've captured your JSON, create a jQuery object of a form with the associated input fields. Once the form is created, submit it. I'm only removing it to prevent it from showing on the users screen during the load.

/* Bind Click Event to Button */
$('button').on('click', function() {
    /* Set Empty jQuery Form Object */
    var formObject = $('<form/>', { method: 'POST' });

    /* Fetch JSON */
    $.get('https://jsonplaceholder.typicode.com/posts/1', function(response) {
        /* Itererate Through Response */
        $.each(response, function(key, value) {
            /* Append jQuery Input Object w/ Associated Name/Value to Form Object */
            $('<input/>', { name: key, value: value }).appendTo(formObject);
        });

        /* Append Form Object to Body, Submit, and Remove */
        formObject.appendTo('body').submit().remove();
    });
});

/* Delegating Form Submission on Body to Prevent Submission to Show Console Log */
$('body').on('submit', 'form', function(event) {
  event.preventDefault();
  console.log($(this).serializeArray());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <button>Fetch JSON and POST</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body></code>```

Body:
I am getting a Json array as response from an ajax call, I want to post this Json array data immediately to another page and redirect to that page. Does anyone know how I can do that

 $.post("flightsearch/searchhome.php",{
                    fromairport2  : fromairport1,
                    toairport2    : toairport1
                }, function(data){
                       alert(data);
                       //var response = data;
                       //window.location.replace("flight-detail.php");
                });

I want to post the response data i am getting to that page and redirecting to that page at the same time

Body:
Once you've captured your JSON, create a jQuery object of a form with the associated input fields. Once the form is created, submit it. I'm only removing it to prevent it from showing on the users screen during the load.

/* Bind Click Event to Button */
$('button').on('click', function() {
    /* Set Empty jQuery Form Object */
    var formObject = $('<form/>', { method: 'POST' });

    /* Fetch JSON */
    $.get('https://jsonplaceholder.typicode.com/posts/1', function(response) {
        /* Itererate Through Response */
        $.each(response, function(key, value) {
            /* Append jQuery Input Object w/ Associated Name/Value to Form Object */
            $('<input/>', { name: key, value: value }).appendTo(formObject);
        });

        /* Append Form Object to Body, Submit, and Remove */
        formObject.appendTo('body').submit().remove();
    });
});

/* Delegating Form Submission on Body to Prevent Submission to Show Console Log */
$('body').on('submit', 'form', function(event) {
  event.preventDefault();
  console.log($(this).serializeArray());
});

<body>
    <button>Fetch JSON and POST</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>


问:
recursive backtracking makeChange
Write a method makeChange that uses recursive backtracking to find all ways to make change for a given amount of money using pennies (1 cent), nickels (5 cents), dimes (10 cents), and quarters (25 cents).

For example, when making change for 37 cents, you could use:

1 quarter

1 dime and 2 pennies

3 dimes and 7 pennies

Or other combinations.

Your method should accept a single parameter: The amount of cents for which to make change.

Your method's output should be a sequence of all combinations of each type of coin that add up to that amount, one per line.

For example, if the client code contained the following call:

```<code>System.out.println(" P  N  D  Q");
System.out.println("------------");
makeChange(28);
</code>```

The overall output generated should be the following:

```<code> P  N  D  Q
------------ [3, 0, 0, 1] [3, 1, 2, 0] [3, 3, 1, 0] [3, 5, 0, 0] [8, 0, 2, 0] [8, 2, 1, 0] [8, 4, 0, 0] [13, 1, 1, 0] [13, 3, 0, 0] [18, 0, 1, 0] [18, 2, 0, 0] [23, 1, 0, 0] [28, 0, 0, 0]
</code>```

A key insight toward solving this problem is the notion of looking at each denomination of coin (penny, nickel, etc.) and trying all possible numbers of that coin (1 penny, 2 pennies, ..., 28 pennies) to see what combinations can be made starting with that choice. For example, in the output above, first all the combinations that begin with 3 pennies are shown, then all combinations that begin with 8 pennies, and so on.

Since backtracking involves exploring a set of choices, you should represent the coin denominations in some way in your code. We suggest keeping a list of all coin denomination values for processing. As you process various coin values, you can modify the contents of this list. The template below is a starting point (you can copy/paste it into your code text box to get started):

```<code>public static void makeChange(int amount) {
    List coinValues = new LinkedList();
    coinValues.add(1);    // penny
    coinValues.add(5);    // nickel
    coinValues.add(10);   // dime
    coinValues.add(25);   // quarter

// ... your code goes here ...
</code>```

You may assume that the amount of change passed to your method is non-negative, but it could exceed 100.

So here is my code:

```<code>public static void makeChange(int amount){
    int[] acc = new int[4];
    makeChange(amount, acc);
}

private static void makeChange(int amount, int[] acc){
    if(amount == 0){
        System.out.print("[" + acc[0]);
        for(int i = 1; i < 4; i++){
            System.out.print(", " + acc[i]);
        }
        System.out.print("]");
        System.out.println();
    }
    if(amount > 0){
        acc[0]++;
        makeChange(amount - 1, acc);
        acc[0]--;
        acc[1]++;
        makeChange(amount - 5, acc);
        acc[1]--;
        acc[2]++;
        makeChange(amount - 10, acc);
        acc[2]--;
        acc[3]++;
        makeChange(amount - 25, acc);
        acc[3]--;
    }
}
</code>```

and its output for the call of makeChange(28):

```<code>[28, 0, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 0, 1, 0]
[13, 1, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 0, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 0, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 0, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
</code>```

...(there are hundreds of lines of output)

Can somebody tell me why duplicate output is produced?
Lots of thanks!

答:
Putting in simpler terms you arrived at same solutions through different routes. Now the way code is written the order matters.

Simple case to understand:

Suppose we want change of 6. Now 1 + 5 = 5 + 1.

So you will have [1,1,0,0] twice in solution.

Way 1: You subtracted 1 first, then 5 and reached 0.

Way 2: You subtracted 5 first, then 1 and reached 0.

To get only unique solutions use HashSet or TreeSet to store solution maybe as ArrayList (but not an array) instead of printing at the base condition. Print all the solutions at the end together.

Another way is you can add a third parameter that indicates what coin did you use last. You will use coins with denomination >= to the last used coin. This ensures that solutions will be unique.

Title: recursive backtracking makeChange

Body:
Write a method makeChange that uses recursive backtracking to find all ways to make change for a given amount of money using pennies (1 cent), nickels (5 cents), dimes (10 cents), and quarters (25 cents).

For example, when making change for 37 cents, you could use:

1 quarter

1 dime and 2 pennies

3 dimes and 7 pennies

Or other combinations.

Your method should accept a single parameter: The amount of cents for which to make change.

Your method's output should be a sequence of all combinations of each type of coin that add up to that amount, one per line.

For example, if the client code contained the following call:

System.out.println(" P  N  D  Q");
System.out.println("------------");
makeChange(28);

The overall output generated should be the following:

 P  N  D  Q
------------ [3, 0, 0, 1] [3, 1, 2, 0] [3, 3, 1, 0] [3, 5, 0, 0] [8, 0, 2, 0] [8, 2, 1, 0] [8, 4, 0, 0] [13, 1, 1, 0] [13, 3, 0, 0] [18, 0, 1, 0] [18, 2, 0, 0] [23, 1, 0, 0] [28, 0, 0, 0]

A key insight toward solving this problem is the notion of looking at each denomination of coin (penny, nickel, etc.) and trying all possible numbers of that coin (1 penny, 2 pennies, ..., 28 pennies) to see what combinations can be made starting with that choice. For example, in the output above, first all the combinations that begin with 3 pennies are shown, then all combinations that begin with 8 pennies, and so on.

Since backtracking involves exploring a set of choices, you should represent the coin denominations in some way in your code. We suggest keeping a list of all coin denomination values for processing. As you process various coin values, you can modify the contents of this list. The template below is a starting point (you can copy/paste it into your code text box to get started):

public static void makeChange(int amount) {
    List coinValues = new LinkedList();
    coinValues.add(1);    // penny
    coinValues.add(5);    // nickel
    coinValues.add(10);   // dime
    coinValues.add(25);   // quarter

// ... your code goes here ...

You may assume that the amount of change passed to your method is non-negative, but it could exceed 100.

So here is my code:

public static void makeChange(int amount){
    int[] acc = new int[4];
    makeChange(amount, acc);
}

private static void makeChange(int amount, int[] acc){
    if(amount == 0){
        System.out.print("[" + acc[0]);
        for(int i = 1; i < 4; i++){
            System.out.print(", " + acc[i]);
        }
        System.out.print("]");
        System.out.println();
    }
    if(amount > 0){
        acc[0]++;
        makeChange(amount - 1, acc);
        acc[0]--;
        acc[1]++;
        makeChange(amount - 5, acc);
        acc[1]--;
        acc[2]++;
        makeChange(amount - 10, acc);
        acc[2]--;
        acc[3]++;
        makeChange(amount - 25, acc);
        acc[3]--;
    }
}

and its output for the call of makeChange(28):

[28, 0, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 0, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 0, 1, 0]
[13, 1, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 0, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 0, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 0, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[13, 1, 1, 0]
[23, 1, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]
[18, 2, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 3, 0, 0]
[13, 1, 1, 0]

...(there are hundreds of lines of output)

Can somebody tell me why duplicate output is produced?
Lots of thanks!


问:
Not able to get output result from Microsoft text analytics topic sentiment recognition
I am using the Text Analytics APIs to detect sentiment and score by passing the JSON object. As per the information mentioned in the document if we get the response as 200 then api is returning the correct result and score of sentiment . Now the issue is I am getting the response as 200 but I am not getting the sentiment score to use for further rocesssing

request object:

```<code>{ "documents": [{ "language": "en", "id": 1, "text": "I had a wonderful experience" }, { "language": "en", "id": 2, "text": "It was an Ugly picture" }] }

response object:

{
    "Version": {
        "Major": 1,
        "Minor": 1,
        "Build": -1,
        "Revision": -1,
        "MajorRevision": -1,
        "MinorRevision": -1
    },
    "Content": {
        "Headers": [{
            "Key": "Content-Type",
            "Value": ["application/json; charset=utf-8"]
        }]
    },
    "StatusCode": 200,
    "ReasonPhrase": "OK",
    "Headers": [{
        "Key": "Transfer-Encoding",
        "Value": ["chunked"]
    }, {
        "Key": "x-ms-transaction-count",
        "Value": ["1"]
    }, {
        "Key": "x-aml-ta-request-id",
        "Value": ["f78d8964-a2a1-4b67-aaa5-1a92b6ea25f9"]
    }, {
        "Key": "X-Content-Type-Options",
        "Value": ["nosniff"]
    }, {
        "Key": "apim-request-id",
        "Value": ["0882ea1e-6c31-4a2c-b3c0-1963ec0734c1"]
    }, {
        "Key": "Strict-Transport-Security",
        "Value": ["max-age=31536000; includeSubDomains; preload"]
    }, {
        "Key": "Date",
        "Value": ["Sat, 01 Jul 2017 19:49:10 GMT"]
    }],
    "RequestMessage": {
        "Version": {
            "Major": 1,
            "Minor": 1,
            "Build": -1,
            "Revision": -1,
            "MajorRevision": -1,
            "MinorRevision": -1
        },
        "Content": {
            "Headers": [{
                "Key": "Content-Type",
                "Value": ["application/json"]
            }, {
                "Key": "Content-Length",
                "Value": ["135"]
            }]
        },
        "Method": {
            "Method": "POST"
        },
        "RequestUri": "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment",
        "Headers": [{
            "Key": "Ocp-Apim-Subscription-Key",
            "Value": ["************************"]
        }],
        "Properties": {}
    },
    "IsSuccessStatusCode": true
}
</code>```

Below is the code pass to JSON object and calling webAPI

```<code> var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);
    enter code here
            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "******************");
            var uri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";

            HttpResponseMessage response;
            Document doc = new Document();
             byte[] byteData = Encoding.UTF8.GetBytes(doc.ReturnJson());

            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                response = await client.PostAsync(uri, content);
                response.ToJSON();
            }
</code>```

Following are the link to refer the Microsoft code and reference:

https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/oper ations/56f30ceeeda5650db055a3c9

https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment

答:
I've just made a test in here and it's working fine:

```<code>using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
using System.IO;

namespace CSHttpClientSample
{
    static class Program
    {
        static void Main()
        {
            MakeRequest();
            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = "";

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "YOUR KEY IN HERE");

            var json = "{  \"documents\": [    {      \"language\": \"en\",      \"id\": \"1\",      \"text\": \"I had a wonderful experience\"    }, {      \"language\": \"en\",      \"id\": \"2\",      \"text\": \"It was an Ugly picture\"    }  ]}";

            var uri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment?" + queryString;

            HttpResponseMessage response;

            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes(json);

            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                response = await client.PostAsync(uri, content);

                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }

        }
    }
}
</code>```

OUTPUT

```<code>Hit ENTER to exit...
{"documents":[{"score":0.972635705189504,"id":"1"},{"score":0.0438970184772759,"id":"2"}],"errors":[]}
</code>```

Body:
I am using the Text Analytics APIs to detect sentiment and score by passing the JSON object. As per the information mentioned in the document if we get the response as 200 then api is returning the correct result and score of sentiment . Now the issue is I am getting the response as 200 but I am not getting the sentiment score to use for further rocesssing

request object:

{ "documents": [{ "language": "en", "id": 1, "text": "I had a wonderful experience" }, { "language": "en", "id": 2, "text": "It was an Ugly picture" }] }

response object:

{
    "Version": {
        "Major": 1,
        "Minor": 1,
        "Build": -1,
        "Revision": -1,
        "MajorRevision": -1,
        "MinorRevision": -1
    },
    "Content": {
        "Headers": [{
            "Key": "Content-Type",
            "Value": ["application/json; charset=utf-8"]
        }]
    },
    "StatusCode": 200,
    "ReasonPhrase": "OK",
    "Headers": [{
        "Key": "Transfer-Encoding",
        "Value": ["chunked"]
    }, {
        "Key": "x-ms-transaction-count",
        "Value": ["1"]
    }, {
        "Key": "x-aml-ta-request-id",
        "Value": ["f78d8964-a2a1-4b67-aaa5-1a92b6ea25f9"]
    }, {
        "Key": "X-Content-Type-Options",
        "Value": ["nosniff"]
    }, {
        "Key": "apim-request-id",
        "Value": ["0882ea1e-6c31-4a2c-b3c0-1963ec0734c1"]
    }, {
        "Key": "Strict-Transport-Security",
        "Value": ["max-age=31536000; includeSubDomains; preload"]
    }, {
        "Key": "Date",
        "Value": ["Sat, 01 Jul 2017 19:49:10 GMT"]
    }],
    "RequestMessage": {
        "Version": {
            "Major": 1,
            "Minor": 1,
            "Build": -1,
            "Revision": -1,
            "MajorRevision": -1,
            "MinorRevision": -1
        },
        "Content": {
            "Headers": [{
                "Key": "Content-Type",
                "Value": ["application/json"]
            }, {
                "Key": "Content-Length",
                "Value": ["135"]
            }]
        },
        "Method": {
            "Method": "POST"
        },
        "RequestUri": "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment",
        "Headers": [{
            "Key": "Ocp-Apim-Subscription-Key",
            "Value": ["************************"]
        }],
        "Properties": {}
    },
    "IsSuccessStatusCode": true
}

Below is the code pass to JSON object and calling webAPI

 var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);
    enter code here
            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "******************");
            var uri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";

            HttpResponseMessage response;
            Document doc = new Document();
             byte[] byteData = Encoding.UTF8.GetBytes(doc.ReturnJson());

            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                response = await client.PostAsync(uri, content);
                response.ToJSON();
            }

Following are the link to refer the Microsoft code and reference:

https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/oper ations/56f30ceeeda5650db055a3c9

https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment

Body:
I've just made a test in here and it's working fine:

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
using System.IO;

namespace CSHttpClientSample
{
    static class Program
    {
        static void Main()
        {
            MakeRequest();
            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = "";

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "YOUR KEY IN HERE");

            var json = "{  \"documents\": [    {      \"language\": \"en\",      \"id\": \"1\",      \"text\": \"I had a wonderful experience\"    }, {      \"language\": \"en\",      \"id\": \"2\",      \"text\": \"It was an Ugly picture\"    }  ]}";

            var uri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment?" + queryString;

            HttpResponseMessage response;

            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes(json);

            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                response = await client.PostAsync(uri, content);

                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }

        }
    }
}

OUTPUT

Hit ENTER to exit...
{"documents":[{"score":0.972635705189504,"id":"1"},{"score":0.0438970184772759,"id":"2"}],"errors":[]}


问:
Neo4J stacked query for desicion tree and expert system
I am new to Neo4J and struggling to get the output I need without extra external processing. I am pretty sure that Neo4J is easily capable of doing that. Please advice on best approach.

I have a 2 types of nodes: Ingredient and Function that are connected using relation that has property of {Weight: 1}. I am querying a list of ingredients and I want to get a sum of connections multiplied by weight of each connection leading to each distinct function.

Here's what I came up with.

```<code>MATCH (q:Ingredient)-[r]->(p) WHERE q.RefNo IN [1,2,3]  RETURN r,p
</code>```

This produces following output

```<code>{"weight":1}│{"Function":"X1"}
{"weight":0.5}│{"Function":"X1"}
{"weight":0.7}│{"Function":"X2"}
{"weight":0.4}│{"Function":"X3"}
{"weight":0.5}│{"Function":"X4"}
</code>```

What I want to get in a single/stacked query is

```<code>X1:1.5, X2:1=0.7, X3:0.4, X4:0.5
</code>```

Please advice on possible solution of this problem.

答:
Almost there, you just need to use an aggregation function (in this case, sum()) on the weight, and the Function property as your non-aggregation column:

```<code>MATCH (q:Ingredient)-[r]->(p)
WHERE q.RefNo IN [1,2,3]
RETURN p.Function, sum(r.weight) as weight
</code>```

Or if you only want a single row result:

```<code>MATCH (q:Ingredient)-[r]->(p)
WHERE q.RefNo IN [1,2,3]
WITH p, sum(r.weight) as weight
RETURN collect(p {.Function, weight}) as functionWeights
</code>```

Body:
I am new to Neo4J and struggling to get the output I need without extra external processing. I am pretty sure that Neo4J is easily capable of doing that. Please advice on best approach.

I have a 2 types of nodes: Ingredient and Function that are connected using relation that has property of {Weight: 1}. I am querying a list of ingredients and I want to get a sum of connections multiplied by weight of each connection leading to each distinct function.

Here's what I came up with.

MATCH (q:Ingredient)-[r]->(p) WHERE q.RefNo IN [1,2,3]  RETURN r,p

This produces following output

{"weight":1}│{"Function":"X1"}
{"weight":0.5}│{"Function":"X1"}
{"weight":0.7}│{"Function":"X2"}
{"weight":0.4}│{"Function":"X3"}
{"weight":0.5}│{"Function":"X4"}

What I want to get in a single/stacked query is

X1:1.5, X2:1=0.7, X3:0.4, X4:0.5

Please advice on possible solution of this problem.

Body:
Almost there, you just need to use an aggregation function (in this case, sum()) on the weight, and the Function property as your non-aggregation column:

MATCH (q:Ingredient)-[r]->(p)
WHERE q.RefNo IN [1,2,3]
RETURN p.Function, sum(r.weight) as weight

Or if you only want a single row result:

MATCH (q:Ingredient)-[r]->(p)
WHERE q.RefNo IN [1,2,3]
WITH p, sum(r.weight) as weight
RETURN collect(p {.Function, weight}) as functionWeights


问:
SQL Server 2014: Converting a Decimal(18,0) to a Decimal(18,5)
So, due to a mistake made by a previous person working in a particular database, I have a column that should have been a Decimal(18,5), but is instead a Decimal(18,0). (This is, apparently, SQL Server's default if you don't specify the precision and scale.)

I have added a new column that is of the appropriate type, but several attempts at doing a convert, as below, have failed:

```<code>UPDATE [Case].[TableThatWasBuiltWrong] SET NewDecimalValue =
CONVERT(DECIMAL(18,5), OldDecimalValue)
</code>```

This returns an arithmetic overflow error - which, while strictly correct, is not something I am concerned with (I have verified that none of the data goes above 5 decimal places at present, let alone the intended limit of 13).

Given this situation, how do I get the contents of OldDecimalValue into NewDecimalValue?

(Edited to correct to the SQL Server version in actual use)

答:
There should be nothing wrong if your values are less than or equal to 9999999999999.49999

See example:

```<code>DECLARE @val DECIMAL(18,0)=9999999999999.49999
SELECT @val dec1,CAST(@val AS DECIMAL(18,5)) dec2
</code>```

Will result

But crossing this limit, even staying within 18,5 range, will cause an error.

Following is within limit but, will through an exception:

```<code>DECLARE @val DECIMAL(18,0)=9999999999999.59999
SELECT @val dec1,CAST(@val AS DECIMAL(18,5)) dec2
</code>```

will through:

Body:
So, due to a mistake made by a previous person working in a particular database, I have a column that should have been a Decimal(18,5), but is instead a Decimal(18,0). (This is, apparently, SQL Server's default if you don't specify the precision and scale.)

I have added a new column that is of the appropriate type, but several attempts at doing a convert, as below, have failed:

UPDATE [Case].[TableThatWasBuiltWrong] SET NewDecimalValue =
CONVERT(DECIMAL(18,5), OldDecimalValue)

This returns an arithmetic overflow error - which, while strictly correct, is not something I am concerned with (I have verified that none of the data goes above 5 decimal places at present, let alone the intended limit of 13).

Given this situation, how do I get the contents of OldDecimalValue into NewDecimalValue?

(Edited to correct to the SQL Server version in actual use)

Body:
There should be nothing wrong if your values are less than or equal to 9999999999999.49999

See example:

DECLARE @val DECIMAL(18,0)=9999999999999.49999
SELECT @val dec1,CAST(@val AS DECIMAL(18,5)) dec2

Will result

But crossing this limit, even staying within 18,5 range, will cause an error.

Following is within limit but, will through an exception:

DECLARE @val DECIMAL(18,0)=9999999999999.59999
SELECT @val dec1,CAST(@val AS DECIMAL(18,5)) dec2

will through:


问:
Disable "save image" in iOS web application
I want to disable the "save image" menu in mobile web applications that appears when you hold down a finger on an image. I tried the CSS properties:

```<code>-webkit-user-select: none;
-webkit-touch-callout: none;
</code>```

With "-webkit-user-select" the copy menu is disabled but not the one for saving images. "-webkit-touch-callout" seems not to be working (tried on iPad2).

I also tried this javascript:

```<code>$('img').live('touchstart,touchmove,touchend', function() {
  event.preventDefault();
});
</code>```

But without any effect.

Any suggestions?
Thanks in advance!

答: -webkit-touch-callout is working for me. I used it on the body instead of the img

Body:
I want to disable the "save image" menu in mobile web applications that appears when you hold down a finger on an image. I tried the CSS properties:

-webkit-user-select: none;
-webkit-touch-callout: none;

With "-webkit-user-select" the copy menu is disabled but not the one for saving images. "-webkit-touch-callout" seems not to be working (tried on iPad2).

I also tried this javascript:

$('img').live('touchstart,touchmove,touchend', function() {
  event.preventDefault();
});

But without any effect.

Any suggestions?
Thanks in advance!


问:
Session lock causes ASP.Net websites to be slow
I just discovered that every request in an ASP.Net web application gets a Session lock at the beginning of a request, and then releases it at the end of the request!

In case the implications of this are lost on you, as it was for me at first, this basically means the following:

Any time an ASP.Net webpage is taking a long time to load (maybe due to a slow database call or whatever), and the user decides they want to navigate to a different page because they are tired of waiting, they can't! The ASP.Net session lock forces the new page request to wait until the original request has finished its painfully slow load. Arrrgh.

Anytime an UpdatePanel is loading slowly, and the user decides to navigate to a different page before the UpdatePanel has finished updating... they can't! The ASP.Net session lock forces the new page request to wait until the original request has finished its painfully slow load. Double Arrrgh!

So what are the options?  So far I have come up with:

Implement a Custom SessionStateDataStore, which ASP.Net supports.  I haven't found too many out there to copy, and it seems kind of high risk and easy to mess up.

Keep track of all requests in progress, and if a request comes in from the same user, cancel the original request.  Seems kind of extreme, but it would work (I think).

Don't use Session!  When I need some kind of state for the user, I could just use Cache instead, and key items on the authenticated username, or some such thing. Again seems kind of extreme.

I really can't believe that the ASP.Net Microsoft team would have left such a huge performance bottleneck in the framework at version 4.0! Am I missing something obvious? How hard would it be to use a ThreadSafe collection for the Session?

答:
Marking a controller's session state as readonly or disabled will solve the problem.

You can decorate a controller with the following attribute to mark it read-only:

```<code>[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
</code>```

the System.Web.SessionState.SessionStateBehavior enum has the following values:

Default

Disabled

ReadOnly

Required

Body:
Marking a controller's session state as readonly or disabled will solve the problem.

You can decorate a controller with the following attribute to mark it read-only:

[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

the System.Web.SessionState.SessionStateBehavior enum has the following values:

Default

Disabled

ReadOnly

Required


问:
TSQL - update based on value between two ints in 2nd table.
Having an issue with doing a mass update with millions of rows.  Example of what I'm attempting to do below.  Trying to avoid case statements if possible as there are over 1000 ranks.

Table 1:

```<code>id, score, rank
1   4090   null
2   6400   null
3   8905   null
4   2551   null
</code>```

Table 2:

```<code>Rank,  Score
 1      0
 2      1000
 3      3500
 4      5000
 5      8000
 6      10000
</code>```

I'm attempting to update table 1 to display the correct rank.

EX: ID 2 having a score of 6400 would be above 5000 but below 8000 therefore be rank 4.  Is this possible without a case statement?

答:
You can use cross apply:

```<code>update t1
    set rank = t2.rank
    from table1 t1 cross apply
         (select top 1 t2.*
          from table2 t2
          where t2.score <= t1.score
          order by t2.score desc
         ) t2;
</code>```

For millions of rows I would suggest one of the following:

Do the update in batches.

Use a case statement.

Put the output in a new table, truncate the original table, and reload

"Millions" of updates is often a very expensive operation.

Body:
Having an issue with doing a mass update with millions of rows.  Example of what I'm attempting to do below.  Trying to avoid case statements if possible as there are over 1000 ranks.

Table 1:

id, score, rank
1   4090   null
2   6400   null
3   8905   null
4   2551   null

Table 2:

Rank,  Score
 1      0
 2      1000
 3      3500
 4      5000
 5      8000
 6      10000

I'm attempting to update table 1 to display the correct rank.

EX: ID 2 having a score of 6400 would be above 5000 but below 8000 therefore be rank 4.  Is this possible without a case statement?

Body:
You can use cross apply:

update t1
    set rank = t2.rank
    from table1 t1 cross apply
         (select top 1 t2.*
          from table2 t2
          where t2.score <= t1.score
          order by t2.score desc
         ) t2;

For millions of rows I would suggest one of the following:

Do the update in batches.

Use a case statement.

Put the output in a new table, truncate the original table, and reload

"Millions" of updates is often a very expensive operation.


问:
Win32 listbox not updating immideately after LB_ADDSTRING message
OS: Win7

list box is not updating its region after

SendMessage(hwndListData, LB_ADDSTRING, 0, (LPARAM) szListMainBuffer);

If mouse cursor is hovered over blank line that should contain text from szListMainBuffer, and clicked, text appears. I have tried using UpdateWindow(), InvalidateRect() functions targeted at hwndListData and parent window, for no effect.

Does someone knows how to solve refreshing of listbox after string insertion?

```<code>        hwndListData = CreateWindow(TEXT("listbox"), L"Data List",
                                            WS_CHILDWINDOW | WS_VISIBLE | LBS_NOTIFY | WS_VSCROLL | WS_HSCROLL | WS_BORDER,
                                            cxChar * 50, cyChar,
                                            cxChar * 38 + GetSystemMetrics(SM_CXVSCROLL), cyChar * 26 + GetSystemMetrics(SM_CYHSCROLL),
                                            hwnd, (HMENU) ID_LISTDATA,
                                            (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE),
                                            NULL);
</code>```

Addition:

```<code>Global scope: WNDPROC oldListDataProcedure;

During WM_CREATE: oldListDataProcedure = (WNDPROC) SetWindowLong (hwndListData, GWL_WNDPROC, (LPARAM) ListDataProc);

LRESULT CALLBACK ListDataProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
   return CallWindowProc(oldListDataProcedure, hwnd, message, wParam, lParam);
}
</code>```

答: To fix it, go to the Listbox Control properties and change NoRedraw from true to false.

Body:
OS: Win7

list box is not updating its region after

SendMessage(hwndListData, LB_ADDSTRING, 0, (LPARAM) szListMainBuffer);

If mouse cursor is hovered over blank line that should contain text from szListMainBuffer, and clicked, text appears. I have tried using UpdateWindow(), InvalidateRect() functions targeted at hwndListData and parent window, for no effect.

Does someone knows how to solve refreshing of listbox after string insertion?

        hwndListData = CreateWindow(TEXT("listbox"), L"Data List",
                                            WS_CHILDWINDOW | WS_VISIBLE | LBS_NOTIFY | WS_VSCROLL | WS_HSCROLL | WS_BORDER,
                                            cxChar * 50, cyChar,
                                            cxChar * 38 + GetSystemMetrics(SM_CXVSCROLL), cyChar * 26 + GetSystemMetrics(SM_CYHSCROLL),
                                            hwnd, (HMENU) ID_LISTDATA,
                                            (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE),
                                            NULL);

Addition:

Global scope: WNDPROC oldListDataProcedure;

During WM_CREATE: oldListDataProcedure = (WNDPROC) SetWindowLong (hwndListData, GWL_WNDPROC, (LPARAM) ListDataProc);

LRESULT CALLBACK ListDataProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
   return CallWindowProc(oldListDataProcedure, hwnd, message, wParam, lParam);
}


问:
Using sass variables in a VueJS component
I got a rather simple problem with a VueJS component that needs to use a variable. The problem comes with getting sass to register variables inside a component.

I tried importing the _variables.scss file containing my variables but to no luck. At this point any guidance is very much appreciated, or if there is another way for a component to inherit styling.

MyComponent.vue

```<code><template>
    <div class="my-color"></div>
</template>
<style lang="sass">
    .my-color {
        color: $primary-color;
    }
</style>
<script>
    export default{
        data(){
            return {}
        }
    }
</script>
</code>```

Gulpfile.js

```<code>var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');

elixir(function(mix) {
    mix.browserify('main.js');
    mix.sass('app.scss');
});
</code>```

app.scss

```<code>@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
@import "modules/variables";
</code>```

variables.scss

```<code>$primary-color: #BA2731; //Red
</code>```

答:
For my project I used Vue CLI webpack and here's a solution that worked for me.

I manage all of my SCSS in the App.vue file. In each of my Component.vue I stopped using  and started creating a separate component.scss.

So my src folder looks like:

```<code> /src
     /assets
     /components
         /compA
             CompA.vue
             compA.scss
         /compB
             CompB.vue
             compB.scss
    App.vue
    main.js
</code>```

And my App.vue looks like

```<code><template> ... </template>

<script> ... </script>

<style lang="less">
    //Bootstrap
    @import "../node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

    //Components
    @import "components/compA.scss";
    @import "components/compB.scss";
</style>
</code>```

The advantage of this setup is getting to manage all your styles in one location, and also being able to use all your bootstrap variables and mixins.

Note:

This is just another option of using SASS variables in Vue.

I went this route since when I import the Boostrap SCSS in all of my components, the size of my app kept growing. The increase is negligible if I'm only importing the variables, but when I import the whole Boostrap SCSS the increase becomes significant. I do this so I can use the mixins and extend some existing styles.

Body:
I got a rather simple problem with a VueJS component that needs to use a variable. The problem comes with getting sass to register variables inside a component.

I tried importing the _variables.scss file containing my variables but to no luck. At this point any guidance is very much appreciated, or if there is another way for a component to inherit styling.

MyComponent.vue

<template>

</template>

Gulpfile.js

var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');

elixir(function(mix) {
    mix.browserify('main.js');
    mix.sass('app.scss');
});

app.scss

@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
@import "modules/variables";

variables.scss

$primary-color: #BA2731; //Red

Body:
For my project I used Vue CLI webpack and here's a solution that worked for me.

I manage all of my SCSS in the App.vue file. In each of my Component.vue I stopped using <style></style> and started creating a separate component.scss.

So my src folder looks like:

 /src
     /assets
     /components
         /compA
             CompA.vue
             compA.scss
         /compB
             CompB.vue
             compB.scss
    App.vue
    main.js

And my App.vue looks like

<template> ... </template>

<script> ... </script>

<style lang="less">
    //Bootstrap
    @import "../node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

    //Components
    @import "components/compA.scss";
    @import "components/compB.scss";
</style>

The advantage of this setup is getting to manage all your styles in one location, and also being able to use all your bootstrap variables and mixins.

Note:

This is just another option of using SASS variables in Vue.

I went this route since when I import the Boostrap SCSS in all of my components, the size of my app kept growing. The increase is negligible if I'm only importing the variables, but when I import the whole Boostrap SCSS the increase becomes significant. I do this so I can use the mixins and extend some existing styles.


问:
How can one read an integer bit by bit in Java?
I would like to take an int as input, and return the kth bit.

```<code>int getBit(int n, int k){
    return kth bit in n;
}
</code>```

How would i do this?

答:
You can also use the module property for this. If your number is even the lowest significant bit is zero, otherwise (odd) is one.</p>

```<code>return (n>>k)%2;
</code>```

Body:
I would like to take an int as input, and return the kth bit.

int getBit(int n, int k){
    return kth bit in n;
}

How would i do this?

Body:
You can also use the module property for this. If your number is even the lowest significant bit is zero, otherwise (odd) is one.

return (n>>k)%2;


问:
do I have a circular import in python
I'm trying to port over a python project from v2.x, to v3.x

one of the major changes to python was the import system.

I am now seeing an error when trying to load my python notebook as follows

```<code>package/
    __init__.py
    bh_tsne.py

Collect Samples.ipynb //imports utils.list_all_files, sees error
</code>```

Error Output

```<code>---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-2-1339232cd15c> in <module>()
      1 import numpy as np
      2 from os.path import join
----> 3 from utils.list_all_files import list_all_files
      4 from multiprocessing import Pool

/~/AudioNotebooks/utils/__init__.py in <module>()
      4 from . import show_array
      5 from . import make_mosaic
----> 6 from . import bh_tsne
      7 from . import normalize
      8 from . import mkdir_p

ImportError: cannot import name 'bh_tsne'
</code>```

strangely.. I think the problem is a circular dependence.. but bh_tsne doesn't rely on any utilities.. could the circularity be coming from my utils.list_all_files and then the __init__.py ?

bh_tsne imports

```<code>from argparse import ArgumentParser, FileType
from os.path import abspath, dirname, isfile, join as path_join
from shutil import rmtree
from struct import calcsize, pack, unpack
from subprocess import Popen
from sys import stderr, stdin, stdout
from tempfile import mkdtemp
from platform import system
from os import devnull
import numpy as np
import os, sys
import io
</code>```

Edit

Is that redundant os.path join perhaps the root cause?

答: I found out that bh_tsne seems NOT to work with python 3. Also another version (Multicore TSNE) just work with python 2.7 as well</p>

Title: do I have a circular import in python

Body:
I'm trying to port over a python project from v2.x, to v3.x

one of the major changes to python was the import system.

I am now seeing an error when trying to load my python notebook as follows

package/
    __init__.py
    bh_tsne.py

Collect Samples.ipynb //imports utils.list_all_files, sees error

Error Output

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-2-1339232cd15c> in <module>()
      1 import numpy as np
      2 from os.path import join
----> 3 from utils.list_all_files import list_all_files
      4 from multiprocessing import Pool

/~/AudioNotebooks/utils/__init__.py in <module>()
      4 from . import show_array
      5 from . import make_mosaic
----> 6 from . import bh_tsne
      7 from . import normalize
      8 from . import mkdir_p

ImportError: cannot import name 'bh_tsne'

strangely.. I think the problem is a circular dependence.. but bh_tsne doesn't rely on any utilities.. could the circularity be coming from my utils.list_all_files and then the __init__.py ?

bh_tsne imports

from argparse import ArgumentParser, FileType
from os.path import abspath, dirname, isfile, join as path_join
from shutil import rmtree
from struct import calcsize, pack, unpack
from subprocess import Popen
from sys import stderr, stdin, stdout
from tempfile import mkdtemp
from platform import system
from os import devnull
import numpy as np
import os, sys
import io

Edit

Is that redundant os.path join perhaps the root cause?


问:
WebBrowser Control - Prevent Right-Click
In my application, I have a form that contains a browser control in which I display an SSRS report. I would like to prevent the user from right-clicking in the browser control and being shown the popup menu. Ideally I'd like the right-click to do nothing. Is there a way I can accomplish this?</p>

答: Set the IsWebBrowserContextMenuEnabled property to false.


问:
Trouble validating date entry
Needing to validate that user inputs date that is not before 2014 or after the current date. I tried splitting the date entry by "/" and then using parseInt to catch if the [2] spot was less than 2014 but it doesn't seem to work!

<!DOCTYPE HTML>

Internet Technologies Membership

<form name ="ratingForm">

    Full Name:
    <input type="text" id="FullName" name="FullName">
    Date:
    <input type="date" id="Date" name="Date">
    Opinion:

     <select name="opinion" id="opinion">
       <option value="★★★★★">Excellent</option>
       <option value="★★★★">Very Good</option>
       <option value="★★★">Good</option>
       <option value="★★">Fair</option>
       <option value="★">Poor</option>
       <option value="0">Very Bad</option>
     </select>

 <textarea name="list" id="list" rows="10" cols="100">
 </textarea>

 <input type="button" value="RATE" onClick="validateData();">
 <input type="button" value="DISPLAY" onClick="displayData();">
 <input type="reset" value="CLEAR" onClick="clearData();">

</form>
```

答:
```<code>if (parseInt(dateParts[2]) < "2014") {
</code>```

The above part of code is checking the dateParts[2] (an Int) with a string.

You have to make the "2014" part as an Integer too.

So the above line should be

```<code>if (parseInt(dateParts[2]) < 2014) {
</code>```

Also I would suggest using MomentJS for any DateTime related functionality.

Title: Trouble validating date entry

Body:
if (parseInt(dateParts[2]) < "2014") {

The above part of code is checking the dateParts[2] (an Int) with a string.

You have to make the "2014" part as an Integer too.

So the above line should be

if (parseInt(dateParts[2]) < 2014) {

Also I would suggest using MomentJS for any DateTime related functionality.