问:
Android Studio NDK iostream file not found and does not able to enable neon in CMakeList
I am new on using NDK and CMake, and got the problem when I compiled my C++ library, Android studio keeps compiling that

Error:(28, 2) error: "NEON support not enabled"

Error:error: 'neon_vector_type' attribute is not supported for this
  target

Error:(17, 10) fatal error: 'iostream' file not found

I have see some solution saying that I should add APP_STL := stlport_static in Application.mk

However, I am using CMakeLists instead of Application.mk.

So I added -DANDROID_ARM_NEON=TRUE -DAPP_STL=stlport_static on CMAKE_C_FLAGS, but it still produce the same error

This is my CMakeLists

```<code>set (pathToProject /home/user/project)
set (pathToOpenCv /home/user/project/OpenCV330)
FILE(GLOB_RECURSE cppfiles src/main/cpp/src/*)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED on)

find_package(OpenMP)
add_definitions(-fPIC)
add_definitions(-fopenmp)
add_definitions(-Ofast)
add_definitions(-DANDROID_STL=c++_shared)
add_definitions(-flax-vector-conversions)
add_definitions(-fopenmp)

cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fpermissive -DANDROID_ARM_NEON=TRUE -DAPP_STL=stlport_static")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")

include_directories(${pathToProject}/app/src/main/cpp/src/include)
include_directories(${pathToOpenCv}/sdk/native/jni/include)

add_library(lib_opencv SHARED IMPORTED)
add_library(native-lib SHARED src/main/cpp/native-lib.cpp )
add_library(mylibrary SHARED ${cppfiles} )

set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION ${pathToProject}/app/src/main/jniLibs/${ANDROID_ABI}/libopencv_java3.so)

find_library(log-lib log)

target_link_libraries(
                       native-lib
                       ${log-lib}
                       lib_opencv
                       mylibrary
                       )
</code>```

Updated:

I also found 1 more compiling message, looks like the -std=c++11 is not actually applied while compiling

```<code>[10/11] Building CXX object CMakeFiles/mylibrary.dir/src/main/cpp/src/yuv420sp.cpp.o
FAILED: /home/user/Downloads/android-ndk-r14b/toolchains/llvm/prebuilt/linux-x86_64/bin/clang  --target=i686-none-linux-android --gcc-toolchain=/home/user/Downloads/android-ndk-r14b/toolchains/x86-4.9/prebuilt/linux-x86_64 --sysroot=/home/user/Downloads/android-ndk-r14b/platforms/android-24/arch-x86 -Dmylibrary_EXPORTS -I../../../../src/main/cpp/include -I/home/user/git/project/OpenCV-android-sdk3.3.0/sdk/native/jni/include -I../../../../src/main/cpp/build/include -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -mstackrealign -Wa,--noexecstack -Wformat -Werror=format-security -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -mstackrealign -Wa,--noexecstack -Wformat -Werror=format-security   -O0 -fno-limit-debug-info -O0 -fno-limit-debug-info  -fPIC -MD -MT CMakeFiles/mylibrary.dir/src/main/cpp/src/object_wrap.c.o -MF CMakeFiles/mylibrary.dir/src/main/cpp/src/object_wrap.c.o.d -o CMakeFiles/mylibrary.dir/src/main/cpp/object_wrap.c.o   -c /home/user/git/project/app/src/main/cpp/object_wrap.c
In file included from /home/user/git/project/app/src/main/cpp/src/object_wrap.c:209:
/home/user/git/project/app/src/main/cpp/src/object.h:17:10: fatal error: 'iostream' file not found
#include <iostream>
         ^
</code>```

Also tried to set the flag in app gradle, still not working

```<code>externalNativeBuild {
  cmake {
    cppFlags "-std=c++11", "-Wno-error=format-security"
    arguments "-DANDROID_STL=gnustl_static", "-DANDROID_ARM_NEON=TRUE"
  }
}
</code>```

if I set -DANDROID_STL=stlport_static, it will give two more error

Error:(25, 10) fatal error: 'thread' file not found

Error:(424, 14) fatal error: 'array' file not found

答:
After changing the to gcc toolchain in gradle, problem solved.</p>

```<code>arguments "-DANDROID_TOOLCHAIN=gcc","-DANDROID_ARM_NEON=TRUE" ,"-DANDROID_STL_FORCE_FEATURES=OFF"
cppFlags "-std=gnu++11", "-Wno-error=format-security"
</code>```

Body:
I am new on using NDK and CMake, and got the problem when I compiled my C++ library, Android studio keeps compiling that

Error:(28, 2) error: "NEON support not enabled"

Error:error: 'neon_vector_type' attribute is not supported for this
  target

Error:(17, 10) fatal error: 'iostream' file not found

I have see some solution saying that I should add APP_STL := stlport_static in Application.mk

However, I am using CMakeLists instead of Application.mk.

So I added -DANDROID_ARM_NEON=TRUE -DAPP_STL=stlport_static on CMAKE_C_FLAGS, but it still produce the same error

This is my CMakeLists

set (pathToProject /home/user/project)
set (pathToOpenCv /home/user/project/OpenCV330)
FILE(GLOB_RECURSE cppfiles src/main/cpp/src/*)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED on)

find_package(OpenMP)
add_definitions(-fPIC)
add_definitions(-fopenmp)
add_definitions(-Ofast)
add_definitions(-DANDROID_STL=c++_shared)
add_definitions(-flax-vector-conversions)
add_definitions(-fopenmp)

cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fpermissive -DANDROID_ARM_NEON=TRUE -DAPP_STL=stlport_static")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")

include_directories(${pathToProject}/app/src/main/cpp/src/include)
include_directories(${pathToOpenCv}/sdk/native/jni/include)

add_library(lib_opencv SHARED IMPORTED)
add_library(native-lib SHARED src/main/cpp/native-lib.cpp )
add_library(mylibrary SHARED ${cppfiles} )

set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION ${pathToProject}/app/src/main/jniLibs/${ANDROID_ABI}/libopencv_java3.so)

find_library(log-lib log)

target_link_libraries(
                       native-lib
                       ${log-lib}
                       lib_opencv
                       mylibrary
                       )

Updated:

I also found 1 more compiling message, looks like the -std=c++11 is not actually applied while compiling

[10/11] Building CXX object CMakeFiles/mylibrary.dir/src/main/cpp/src/yuv420sp.cpp.o
FAILED: /home/user/Downloads/android-ndk-r14b/toolchains/llvm/prebuilt/linux-x86_64/bin/clang  --target=i686-none-linux-android --gcc-toolchain=/home/user/Downloads/android-ndk-r14b/toolchains/x86-4.9/prebuilt/linux-x86_64 --sysroot=/home/user/Downloads/android-ndk-r14b/platforms/android-24/arch-x86 -Dmylibrary_EXPORTS -I../../../../src/main/cpp/include -I/home/user/git/project/OpenCV-android-sdk3.3.0/sdk/native/jni/include -I../../../../src/main/cpp/build/include -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -mstackrealign -Wa,--noexecstack -Wformat -Werror=format-security -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -mstackrealign -Wa,--noexecstack -Wformat -Werror=format-security   -O0 -fno-limit-debug-info -O0 -fno-limit-debug-info  -fPIC -MD -MT CMakeFiles/mylibrary.dir/src/main/cpp/src/object_wrap.c.o -MF CMakeFiles/mylibrary.dir/src/main/cpp/src/object_wrap.c.o.d -o CMakeFiles/mylibrary.dir/src/main/cpp/object_wrap.c.o   -c /home/user/git/project/app/src/main/cpp/object_wrap.c
In file included from /home/user/git/project/app/src/main/cpp/src/object_wrap.c:209:
/home/user/git/project/app/src/main/cpp/src/object.h:17:10: fatal error: 'iostream' file not found
#include <iostream>
         ^

Also tried to set the flag in app gradle, still not working

externalNativeBuild {
  cmake {
    cppFlags "-std=c++11", "-Wno-error=format-security"
    arguments "-DANDROID_STL=gnustl_static", "-DANDROID_ARM_NEON=TRUE"
  }
}

if I set -DANDROID_STL=stlport_static, it will give two more error

Error:(25, 10) fatal error: 'thread' file not found

Error:(424, 14) fatal error: 'array' file not found

Body:
After changing the to gcc toolchain in gradle, problem solved.

arguments "-DANDROID_TOOLCHAIN=gcc","-DANDROID_ARM_NEON=TRUE" ,"-DANDROID_STL_FORCE_FEATURES=OFF"
cppFlags "-std=gnu++11", "-Wno-error=format-security"


来源: stackexchange

问:
module 'tensorflow.contrib.learn' has no attribute 'python'
```<code>import tensorflow.contrib.learn.python.learn as learn

home/michael/miniconda3/lib/python3.6/importlib/_bootstrap.py:219:
RuntimeWarning: compiletime version 3.5 of module
'tensorflow.python.framework.fast_tensor_util' does not match runtime
version 3.6
return f(*args, **kwds)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-630a74eb6a34> in <module>()
----> 1 import tensorflow.contrib.learn.python.learn as learn

AttributeError: module 'tensorflow.contrib.learn' has no attribute 'python'
</code>```

I am trying to import this library in jupyter in linux environment, and I could not find any answer on google.

答:
Actually, the module tensorflow.contrib.learn reimports everything from tensorflow.contrib.learn.python.learn:

```<code> 91 # pylint: disable=wildcard-import
 92 from tensorflow.contrib.learn.python.learn import *
 93 # pylint: enable=wildcard-import
 94
 95 from tensorflow.contrib.learn.python.learn import learn_runner_lib as learn_runner
</code>```

So you can just import it directly:

```<code>import tensorflow.contrib.learn as learn
</code>```

or

```<code>from tensorflow.contrib import learn
</code>```

ContentLicense: CC BY-SA 3.0

Body:
import tensorflow.contrib.learn.python.learn as learn

home/michael/miniconda3/lib/python3.6/importlib/_bootstrap.py:219:
RuntimeWarning: compiletime version 3.5 of module
'tensorflow.python.framework.fast_tensor_util' does not match runtime
version 3.6
return f(*args, **kwds)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-630a74eb6a34> in <module>()
----> 1 import tensorflow.contrib.learn.python.learn as learn

AttributeError: module 'tensorflow.contrib.learn' has no attribute 'python'

I am trying to import this library in jupyter in linux environment, and I could not find any answer on google.

Body:
Actually, the module tensorflow.contrib.learn reimports everything from tensorflow.contrib.learn.python.learn:

 91 # pylint: disable=wildcard-import
 92 from tensorflow.contrib.learn.python.learn import *
 93 # pylint: enable=wildcard-import
 94
 95 from tensorflow.contrib.learn.python.learn import learn_runner_lib as learn_runner

So you can just import it directly:

import tensorflow.contrib.learn as learn

or

from tensorflow.contrib import learn


问:
PHP/Wordpress Display the user search query inside of a search input
I'm trying to create a custom index.php page and would like to make the users search result save inside of a search box. Here was what I peiced together that works a little bit:

```<code><li class="result-searh"><form role="search" method="get" id="searchform" class="searchform" action="http://droogle.dil/">
                <div>
                    <input type="text" value=<?php printf( esc_html__( '%s', stackstar ), '<span>' . get_search_query() . '</span>' ); ?> name="s" id="s">
                    <input type="submit" id="searchsubmit" value="Search">
                </div>
            </form></li>
</code>```

Which looks like this:

When I search for "my search". As you can see, its is showing up. Just a bit funny looking. I am quite terrible at PHP so forgive me if this looks bad. I Frankenstein'd this code together using other plugins' code.

-

EDIT: changed it to this:

```<code><input type="text" value=<?php printf( esc_html__( '%s', stackstar ), get_search_query()); ?> name="s" id="s">
</code>```

and now when I search for "Hello I am joe" inspecting the element gives me this:

```<code><input type="text" value="hello" I="" am="" joe="" name="s" id="s">
</code>```

答:
Going out on an untested limb and proposing enclosing the <php .. ?> with double quotes might fix this:

<input type="text" value="<?php printf( esc_html__( '%s', stackstar ), get_search_query()); ?>" name="s" id="s">

Body:
I'm trying to create a custom index.php page and would like to make the users search result save inside of a search box. Here was what I peiced together that works a little bit:

<form role="search" method="get" id="searchform" class="searchform" action="http://droogle.dil/">

                    <input type="text" value=<?php printf( esc_html__( '%s', stackstar ), '' . get_search_query() . '' ); ?> name="s" id="s">
                    <input type="submit" id="searchsubmit" value="Search">

            </form>

Which looks like this:

When I search for "my search". As you can see, its is showing up. Just a bit funny looking. I am quite terrible at PHP so forgive me if this looks bad. I Frankenstein'd this code together using other plugins' code.

-

EDIT: changed it to this:

<input type="text" value=<?php printf( esc_html__( '%s', stackstar ), get_search_query()); ?> name="s" id="s">

and now when I search for "Hello I am joe" inspecting the element gives me this:

<input type="text" value="hello" I="" am="" joe="" name="s" id="s">


问:
Delete currently selected bound combobox item and then have it select nothing?
How can I make a combobox select nothing (ie. SelectedIndex = -1) after deleting the bound item that was currently selected.  I don't like how the next item gets selected  after the currently selected item gets deleted.  This could lead to some problems with the wrong value being selected.  Would be ideal if there was a way to add this behaviour directly to an inherited combobox.

答: I also like the suggestion made by @Cody Gray in the comments. However, I thought about this and another way you might be able to do this is by attaching an Event which fires when you remove an item from the ComboBox. Set the SelectedIndex = -1 in that event handler. Now, I am not sure if there is such a readily available event, so it might be worthwhile to look into it.

ContentLicense: CC BY-SA 2.5


问:
AutoCAD Plugin Development by Example
I am interested in developing an AutoCAD plugin and am trying to understand the relationships between several different types of AutoCAD plugin files:

Managed DLLs that ship with AutoCAD plugins

ARX files that ship with AutoCAD plugins

CUIX files that ship with AutoCAD plugins

From what I can tell these three files are all inter-related and work together to initialize and load a plugin, I'm just not seeing the forest through the trees as to what information each file type contains, which files loads or depends on the others, etc.

It sounds like a plugin's core functionality is supposed to go inside the ARX file, and written in C++ and compiled for the native/target platform.

It also sounds like, at startup, AutoCAD loads its plugin DLLs, which are all managed .NET libraries (typically written in C#), and in turn they invoke their native/compiled respective ARX files. As to where the CUIX file comes into play, I still have no idea.

Can anyone help explain the relatioships & dependencies of these files, and what types of code/logic/data goes inside of them? Thanks in advance!

答:
AutoCAD core libraries are all written in unmanaged code (C++ I believe). Ultimately, whatever API you choose to develop your plugins, you will be manipulating the unmanaged AutoCAD objects from those core libraries via one of their APIs.  Aside from the three types of files you mentioned, there is a number of other ways to create plugins for AutoCAD. Some examples include: Lisp Scripting, VBA Script, COM Clients  (VB, Java, Delphi). Most of these are now outdated, and these days the .Net and C++(ObjectARX) APIs are most popular. However, the rest are still in use for legacy reasons. If you're starting a new module, you would use either .Net or ARX.

.NET API is a set of .NET wrapper libraries that wrap the ObjectARX API. Most common dlls you would reference are accoremgd.dll, acdbmgd.dll and acmgd.dll, but there are others. These libraries allow you to manipulate native AutoCad objects though a .NET language. If you would like to create plug-ins for AutoCad in C#, then you only need to code in C#. It is great for development speed, but the performance of your code will be somewhat inferior to ARX plugins. That being said, I really want to emphasize that it is still damn fast. I have not found the need to code in C++ for AutoCAD due to performance issues. Overall it is very powerful and feature rich. You can do pretty well anything to a drawing using C# only.

Have a look at this answer I gave recently. It should answer most if not all your questions about getting started with AutoCAD plug-in development in .Net.

ObjectARX API is very similar to what I described for the .NET API, except you code in C++. Some of the libraries include rxapi.lib, accore.lib, acgiapi.lib, acdrawbridge.lib as well as some others. Development using C++ is considerably more cumbersome than when using C#, but C++ code runs faster, although not by a large margin.

CUIX files live in a whole different galaxy. They are used for customizing the UI among other related things. You can browse various uses of cuix files here.

Your choice will really come down to what you are doing. If you are writing code that will batch process hundreds of thousands of drawings as fast as possible, you will want to explore the C++ API. If you are processing just hundreds of drawings or just creating a bunch of commands for users, I would vehemently urge you to use the C# API. It is worth the small hit in performance that will almost never be perceptible to the user.

For more information, go to this AutoDesk link, and scroll down to the training labs. I would recommend that you at least read through both ObjectARX and .NET Training labs. Once you choose what you want to use, go through all the labs for the one of your choice. You will thank yourself later as you will save countless hours of headache and frustration!

Good Luck!

Title: AutoCAD Plugin Development by Example

ContentLicense: CC BY-SA 4.0


问:
get from recursion with exception
I have recursive method:

```<code>private static int F(Tree tree)
</code>```

There is try block:

```<code>try
{
    ...
    return x;
}
catch (DivideByZeroException)
{
    Console.WriteLine("Divide Error");
    throw;
}
</code>```

My question is how to get from rucursion? Becouse if I divide by zero I catch the exception, but still get error.
Thanks.

答:
You throw the exception again in catch, if you don't catch it again, then your program will crash which is the intended behaviour in that case.

Is it the same exception that is thrown, or is it the one, you caught in catch?

Title: get from recursion with exception

Body:
I have recursive method:

private static int F(Tree tree)

There is try block:

try
{
    ...
    return x;
}
catch (DivideByZeroException)
{
    Console.WriteLine("Divide Error");
    throw;
}

My question is how to get from rucursion? Becouse if I divide by zero I catch the exception, but still get error.
Thanks.


答:
If you want the code to be able to continue after the exception, you have to wrap the individual operation that throws the error, and then write code that handles it, e.g. by setting some variable to represent an inferred value. If you have several operations, you must wrap each one. For example:</p>

```<code>double a;
double b;
try
{
    a = 1000 / 0 ;  //Some operation that computes a, but might divide by zero
}
catch (DivideByZeroException)
{
    a = Double.PositiveInfinity;  //The desired value of a when divide by zero occurs
}
try
{
    b = -1000/0;  //Some operation that computes b, but might divide by zero
}
catch (DivideByZeroException)
{
    b = Double.NegativeInfinity;  //The desired value of b when divide by zero occurs
}
</code>```

Title: get from recursion with exception

Body:
If you want the code to be able to continue after the exception, you have to wrap the individual operation that throws the error, and then write code that handles it, e.g. by setting some variable to represent an inferred value. If you have several operations, you must wrap each one. For example:

double a;
double b;
try
{
    a = 1000 / 0 ;  //Some operation that computes a, but might divide by zero
}
catch (DivideByZeroException)
{
    a = Double.PositiveInfinity;  //The desired value of a when divide by zero occurs
}
try
{
    b = -1000/0;  //Some operation that computes b, but might divide by zero
}
catch (DivideByZeroException)
{
    b = Double.NegativeInfinity;  //The desired value of b when divide by zero occurs
}


问:
How to stop submissions of commonly used passwords
I am creating a program that checks for a password's strength. I want to block the ability for someone to type a commonly used password such as 'Password1'. I was also looking into password entropy and couldn't really figure out how to incorporate that into my code. I'm new with python and have been trying my best, so please forgive me. Maybe some of you have ideas on what I can do.</p>

```<code>import re

def password():
    print ('Hello and welcome to Austin’s Password Checker!\n\nThe password must be between 6 and 12 characters\n\nConsider a capital, lowercase and number for best results!\n')

while True:
    password = input('Enter a password:')
    if 6 <= len(password) < 12:
        break
    print ('The password must be between 6 and 12 characters.\nConsider having a capital, lowercase and a number for best results!')

password_scores = {0:'Terrible', 1:'Weak', 2:'Medium', 3:'Strong'}
password_strength = dict.fromkeys(['up', 'down', 'num','spcl'], False)
if re.search(r'[A-Z]', password):
    password_strength['up'] = True
if re.search(r'[a-z]', password):
    password_strength['down'] = True
if re.search(r'[0-9]', password):
    password_strength['num'] = True
score = len([b for b in password_strength.values() if b])

print ('Password is %s' % password_scores[score])

password()
</code>```

答:
You can dump the passwords into a set (for quick lookups) and use one of the many online available dictionaries for actually frequently used passwords. (Most of them come from leaks, so it should be pretty much valid)
https://github.com/danielmiessler/SecLists/tree/master/Passwords</p>

```<code>passwords = set(line.strip() for line in open('mostUsedPasswords.txt'))

if "matrix" in passwords:
    print("This password is frequently used")
</code>```

Body:
I am creating a program that checks for a password's strength. I want to block the ability for someone to type a commonly used password such as 'Password1'. I was also looking into password entropy and couldn't really figure out how to incorporate that into my code. I'm new with python and have been trying my best, so please forgive me. Maybe some of you have ideas on what I can do.

import re

def password():
    print ('Hello and welcome to Austin’s Password Checker!\n\nThe password must be between 6 and 12 characters\n\nConsider a capital, lowercase and number for best results!\n')

while True:
    password = input('Enter a password:')
    if 6 <= len(password) < 12:
        break
    print ('The password must be between 6 and 12 characters.\nConsider having a capital, lowercase and a number for best results!')

password_scores = {0:'Terrible', 1:'Weak', 2:'Medium', 3:'Strong'}
password_strength = dict.fromkeys(['up', 'down', 'num','spcl'], False)
if re.search(r'[A-Z]', password):
    password_strength['up'] = True
if re.search(r'[a-z]', password):
    password_strength['down'] = True
if re.search(r'[0-9]', password):
    password_strength['num'] = True
score = len([b for b in password_strength.values() if b])

print ('Password is %s' % password_scores[score])

password()

Body:
You can dump the passwords into a set (for quick lookups) and use one of the many online available dictionaries for actually frequently used passwords. (Most of them come from leaks, so it should be pretty much valid)
https://github.com/danielmiessler/SecLists/tree/master/Passwords

passwords = set(line.strip() for line in open('mostUsedPasswords.txt'))

if "matrix" in passwords:
    print("This password is frequently used")


问:
Returning Value When Object Property Doesn't Exist
Running a test on my code. It should return 0 if the property passed into the function does not exist. But its not returning anything. Did I make a typo?</p>

```<code>var obj = {
  key: [1, 2, 3]
};

function getAverageOfElementsAtProperty(obj, key) {
  if (obj[key].length === 0 || Array.isArray(obj[key]) === false || obj.hasOwnProperty(key) === false) {
    return 0;
  }
  var average = 0;
  for (var i = 0; i < obj[key].length; i++) {
    average += obj[key][i];
  }
  average /= obj[key].length;
  return average;
}

console.log(getAverageOfElementsAtProperty(obj, 'notKey'));
</code>```

答:
Since obj['notKey'] does not exist, it does not return an array. Therefore you cannot do .length of undefined. I would change it to typeof to see if its defined or not.

```<code>var obj = {
  key: [1, 2, 3]
};

function getAverageOfElementsAtProperty(obj, key) {

  if (typeof obj[key] == 'undefined' || Array.isArray(obj[key]) === false || obj.hasOwnProperty(key) === false) {
    return 0;
  }

  var average = 0;
  for (var i = 0; i < obj[key].length; i++) {
    average += obj[key][i];
  }
  average /= obj[key].length;
  return average;
}

console.log(getAverageOfElementsAtProperty(obj, 'notKey'));
</code>```

Body:
Running a test on my code. It should return 0 if the property passed into the function does not exist. But its not returning anything. Did I make a typo?

var obj = {
  key: [1, 2, 3]
};

function getAverageOfElementsAtProperty(obj, key) {
  if (obj[key].length === 0 || Array.isArray(obj[key]) === false || obj.hasOwnProperty(key) === false) {
    return 0;
  }
  var average = 0;
  for (var i = 0; i < obj[key].length; i++) {
    average += obj[key][i];
  }
  average /= obj[key].length;
  return average;
}

console.log(getAverageOfElementsAtProperty(obj, 'notKey'));

Body:
Since obj['notKey'] does not exist, it does not return an array. Therefore you cannot do .length of undefined. I would change it to typeof to see if its defined or not.

var obj = {
  key: [1, 2, 3]
};

function getAverageOfElementsAtProperty(obj, key) {

  if (typeof obj[key] == 'undefined' || Array.isArray(obj[key]) === false || obj.hasOwnProperty(key) === false) {
    return 0;
  }

  var average = 0;
  for (var i = 0; i < obj[key].length; i++) {
    average += obj[key][i];
  }
  average /= obj[key].length;
  return average;
}

console.log(getAverageOfElementsAtProperty(obj, 'notKey'));


问:
How embed HTML file (exported from Plotly) to Jupiter Notebook?
I need to include this graph https://plot.ly/~ekirzhner/6/ into my Jupiter Notebook. How to proceed? Thanks</p>

答:
Click on "share" at the bottom right of the image. If you embed it as an iframe, use a code cell. You'll get an interactive graph if you copy and paste this code into the cell.

```<code>import IPython
iframe = '<iframe width="900" height="800" frameborder="0" scrolling="no" src="//plot.ly/~ekirzhner/6.embed"></iframe>'
IPython.display.HTML(iframe)
</code>```

To import a static graph using html, in a markdown cell, use the following code:

```<code>%%html

<div>
    <a href="https://plot.ly/~ekirzhner/6/" target="_blank" title="Plot 6" style="display: block; text-align: center;"><img src="https://plot.ly/~ekirzhner/6.png" alt="Plot 6" style="max-width: 100%;width: 600px;"  width="600" onerror="this.onerror=null;this.src='https://plot.ly/404.png';" /></a>
</code>```

I created a notebook file that contains a static graph from the html option plus a cell with the interactive plotly graph that you can download here

Body:
Click on "share" at the bottom right of the image. If you embed it as an iframe, use a code cell. You'll get an interactive graph if you copy and paste this code into the cell.

import IPython
iframe = '<iframe width="900" height="800" frameborder="0" scrolling="no" src="//plot.ly/~ekirzhner/6.embed"></iframe>'
IPython.display.HTML(iframe)

To import a static graph using html, in a markdown cell, use the following code:

%%html

<div>
    <a href="https://plot.ly/~ekirzhner/6/" target="_blank" title="Plot 6" style="display: block; text-align: center;"><img src="https://plot.ly/~ekirzhner/6.png" alt="Plot 6" style="max-width: 100%;width: 600px;"  width="600" onerror="this.onerror=null;this.src='https://plot.ly/404.png';" /></a>

I created a notebook file that contains a static graph from the html option plus a cell with the interactive plotly graph that you can download here


问:
Comparing two strings in C in a loop
I am writing a code to see whether or not the user's input is equivalent to an already stated string. The program loops until the input is the same as the string, using the strcmp function, but for some reason the program does not compare the strings and therefore the loop malfunctions. The code is below:</p>

```<code>int main()
{
    char passcode[3]="ZZZ";
    char input[3];
    int check;
    while(check!=0)
        {
        printf("What is the password?\n");
        gets(input);
        check=strcmp(passcode, input);
        }
    printf("You crack the pass code!");
    return 0;
}
</code>```

答:
The suggested code above does not recognize the input. It likely wont work and will stuck within the while loop.  I would suggest to make it much easier using scanf for the input and then compare the string as you did with strcmp. If input is correct then let in and break out of the while loop. Try this: </p>

```<code>#include <stdio.h>
int main()
{
  char input[3];
  printf ("\nHit the pass code!\npass code: ");
  while (input != "ZZZ") {
    scanf ("%s",&input);
    if (strcmp(input, "ZZZ") == 0){
      printf ("\nYou crack the pass code!!\n\n");
      break;
    } else {
      printf ("Wroooong!\n pass code: ");
    }
  }
  return 0;
}
</code>```

Title: Comparing two strings in C in a loop

Body:
I am writing a code to see whether or not the user's input is equivalent to an already stated string. The program loops until the input is the same as the string, using the strcmp function, but for some reason the program does not compare the strings and therefore the loop malfunctions. The code is below:

int main()
{
    char passcode[3]="ZZZ";
    char input[3];
    int check;
    while(check!=0)
        {
        printf("What is the password?\n");
        gets(input);
        check=strcmp(passcode, input);
        }
    printf("You crack the pass code!");
    return 0;
}

Body:
The suggested code above does not recognize the input. It likely wont work and will stuck within the while loop.  I would suggest to make it much easier using scanf for the input and then compare the string as you did with strcmp. If input is correct then let in and break out of the while loop. Try this:

#include <stdio.h>
int main()
{
  char input[3];
  printf ("\nHit the pass code!\npass code: ");
  while (input != "ZZZ") {
    scanf ("%s",&input);
    if (strcmp(input, "ZZZ") == 0){
      printf ("\nYou crack the pass code!!\n\n");
      break;
    } else {
      printf ("Wroooong!\n pass code: ");
    }
  }
  return 0;
}


问:
UNIX While Loop Using grep
I am trying to create a while loop that checks my data file for a particular string $username and if a duplicate of it is found in the data file, a number is added to the end of it. This is what I have and for some reason I get an error "too many arguments" for the line containing the while loop. any help would be greatly appreciated.</p>

```<code>    tput cup 3 12
    echo "Enter the first name of the user: "
    tput cup 3 47; read firstName
    tput cup 4 12; echo "Enter the last name of the user: "
    tput cup 4 45; read lastName
    username=${firstName:0:1}${lastName:0:4}
    i=0
    while [ -n $(grep -q -F "$username" capstonedata.txt) ]
    do
            let i=$i+1
            username=$username$i
    done
    userdata=${firstName}":"${lastName}":"${username}
    echo $userdata | tr [a-z] [A-Z] >> capstonedata.txt
</code>```

答:
You need to decide whether the result of your command is an empty string, not the command it self. Try

```<code>while [ -n $(grep -q -F "$username" capstonedata.txt) ]
</code>```

Edit

A common error is adding an extra dollar sign when you assign values to variables in shell script. Never use anything like

```<code>$username=...
</code>```

if you want to assign something to the variable called username. Remove the dollar sign before it. On the other hand, you need to use i=$i+1

Besides that, I don't really understand what you are trying to achieve by using username=$username[i].

The following script may address your needs or may not, depending on whether I have got your intention right.

```<code>#!/bin/bash

(cat <<EOF
$username
EOF
)|(while read line
do
        cnt=`grep "\b$line[0-9]*\b" capstonedata.txt| wc -l`
        if [ $cnt -gt 1 ]
        then
                echo $line$cnt
        else
                echo $line
        fi
done
)
</code>```

Since OP has further clarified his need, the script can be made much simpler.

```<code>cnt=`grep "\b$username[0-9]*\b" capstonedata.txt|wc -l`
if [ "$cnt" -eq "0" ]; then
    cnt=
fi
username=$username$cnt
</code>```

Explanation: "$username[0-9]*" matches the $username, with optional digits after it, "\b" matches word boundaries (but this seems to only work with egrep on some systems although it works perfectly fine on my system, you can use grep "\<$username[0-9]*\>" as a safer option) so that you don't accidentally match the line "abcd" when $username is "ab". wc -l counts the number of lines of matches, so if the username has appeared once, the result will be 1. The back-ticks are used to assign the result of a command to a variable, which is in this case $cnt. The if-clause sets $cnt to empty string if it is 0 (i.e. there's no matching in the file). The last line is just appending $cnt to the original user name. So if there is one line that matches the regex the result will be $username with a 1 appended. Precisely what you need.

Title: UNIX While Loop Using grep

Body:
I am trying to create a while loop that checks my data file for a particular string $username and if a duplicate of it is found in the data file, a number is added to the end of it. This is what I have and for some reason I get an error "too many arguments" for the line containing the while loop. any help would be greatly appreciated.

    tput cup 3 12
    echo "Enter the first name of the user: "
    tput cup 3 47; read firstName
    tput cup 4 12; echo "Enter the last name of the user: "
    tput cup 4 45; read lastName
    username=${firstName:0:1}${lastName:0:4}
    i=0
    while [ -n $(grep -q -F "$username" capstonedata.txt) ]
    do
            let i=$i+1
            username=$username$i
    done
    userdata=${firstName}":"${lastName}":"${username}
    echo $userdata | tr [a-z] [A-Z] >> capstonedata.txt

Body:
You need to decide whether the result of your command is an empty string, not the command it self. Try

while [ -n $(grep -q -F "$username" capstonedata.txt) ]

Edit

A common error is adding an extra dollar sign when you assign values to variables in shell script. Never use anything like

$username=...

if you want to assign something to the variable called username. Remove the dollar sign before it. On the other hand, you need to use i=$i+1

Besides that, I don't really understand what you are trying to achieve by using username=$username[i].

The following script may address your needs or may not, depending on whether I have got your intention right.

#!/bin/bash

(cat <<EOF
$username
EOF
)|(while read line
do
        cnt=`grep "\b$line[0-9]*\b" capstonedata.txt| wc -l`
        if [ $cnt -gt 1 ]
        then
                echo $line$cnt
        else
                echo $line
        fi
done
)

Since OP has further clarified his need, the script can be made much simpler.

cnt=`grep "\b$username[0-9]*\b" capstonedata.txt|wc -l`
if [ "$cnt" -eq "0" ]; then
    cnt=
fi
username=$username$cnt

Explanation: "$username[0-9]*" matches the $username, with optional digits after it, "\b" matches word boundaries (but this seems to only work with egrep on some systems although it works perfectly fine on my system, you can use grep "\<$username[0-9]*\>" as a safer option) so that you don't accidentally match the line "abcd" when $username is "ab". wc -l counts the number of lines of matches, so if the username has appeared once, the result will be 1. The back-ticks are used to assign the result of a command to a variable, which is in this case $cnt. The if-clause sets $cnt to empty string if it is 0 (i.e. there's no matching in the file). The last line is just appending $cnt to the original user name. So if there is one line that matches the regex the result will be $username with a 1 appended. Precisely what you need.


问:
TextureView getBitmap java.lang.IllegalStateException
I start a thread to getBitmap through TextureView，however，I get an exception：

```<code>E/AndroidRuntime: FATAL EXCEPTION: Thread-814
java.lang.IllegalStateException: Hardware acceleration can only be used with a single UI thread.
Original thread: Thread[main,5,main]
Current thread: Thread[Thread-814,5,main]
    at android.view.HardwareRenderer$GlRenderer.checkCurrent(HardwareRenderer.java:1343)
    at android.view.HardwareRenderer$GlRenderer.validate(HardwareRenderer.java:1080)
    at android.view.TextureView.getBitmap(TextureView.java:587)
    at com.example.zmc.colorfultextproject.demo2.SecondActivity.getFrame(SecondActivity.java:153)
    at com.meitu.colorfultext.ColorfulTextView$1.run(ColorfulTextView.java:131)
    at java.lang.Thread.run(Thread.java:856)
</code>```

in my code

```<code>private TextureView demo2VideoTtv;

public Bitmap getFrame() {
    //这里会造成抖动
    long start = System.currentTimeMillis();
    demo2VideoTtv.getBitmap(mFrame); // here throw exception
    Log.d("SecondActivity", "getFrame time" + (System.currentTimeMillis() - start));
    //裁剪图片
    mFrame_part = Bitmap.createBitmap(mFrame, demo2ColorfulText.getLeft(), demo2ColorfulText.getTop(), demo2ColorfulText.getWidth(), demo2ColorfulText.getHeight());
    return mFrame_part;
}
</code>```

答:
I'm not sure of the exact api threshold but on older devices TextureView.getBitmap() must be requested on the UI thread.  </p>

<p>It doesn't appear to be an issue on 21+.  Last I saw it was reproducible on api 19.  </p>

Body:
I start a thread to getBitmap through TextureView，however，I get an exception：

E/AndroidRuntime: FATAL EXCEPTION: Thread-814
java.lang.IllegalStateException: Hardware acceleration can only be used with a single UI thread.
Original thread: Thread[main,5,main]
Current thread: Thread[Thread-814,5,main]
    at android.view.HardwareRenderer$GlRenderer.checkCurrent(HardwareRenderer.java:1343)
    at android.view.HardwareRenderer$GlRenderer.validate(HardwareRenderer.java:1080)
    at android.view.TextureView.getBitmap(TextureView.java:587)
    at com.example.zmc.colorfultextproject.demo2.SecondActivity.getFrame(SecondActivity.java:153)
    at com.meitu.colorfultext.ColorfulTextView$1.run(ColorfulTextView.java:131)
    at java.lang.Thread.run(Thread.java:856)

in my code

private TextureView demo2VideoTtv;

public Bitmap getFrame() {
    //这里会造成抖动
    long start = System.currentTimeMillis();
    demo2VideoTtv.getBitmap(mFrame); // here throw exception
    Log.d("SecondActivity", "getFrame time" + (System.currentTimeMillis() - start));
    //裁剪图片
    mFrame_part = Bitmap.createBitmap(mFrame, demo2ColorfulText.getLeft(), demo2ColorfulText.getTop(), demo2ColorfulText.getWidth(), demo2ColorfulText.getHeight());
    return mFrame_part;
}

Body:
I'm not sure of the exact api threshold but on older devices TextureView.getBitmap() must be requested on the UI thread.

It doesn't appear to be an issue on 21+.  Last I saw it was reproducible on api 19.


问:
How do I simulate flip of biased coin?
In unbiased coin flip H or T occurs 50% of times.

But I want to simulate coin which gives H  with probability 'p' and T with probability '(1-p)'.

something like this:

```<code>def flip(p):
   '''this function return H with probability p'''
   # do something
   return result

>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]
</code>```

答:
```<code>import random
def flip(p):
    return (random.random() < p)
</code>```

That returns a boolean which you can then use to choose H or T (or choose between any two values) you want. You could also include the choice in the method:

```<code>def flip(p):
    if random.random() < p:
        return 'H'
    else:
        return 'T'
</code>```

but it'd be less generally useful that way.

OwnerDisplayName: david makcenzie

Title: How do I simulate flip of biased coin?

Body:
In unbiased coin flip H or T occurs 50% of times.

But I want to simulate coin which gives H  with probability 'p' and T with probability '(1-p)'.

something like this:

def flip(p):
   '''this function return H with probability p'''
   # do something
   return result

>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]

LastEditorDisplayName: Mitch Wheat

Body:
import random
def flip(p):
    return (random.random() < p)

That returns a boolean which you can then use to choose H or T (or choose between any two values) you want. You could also include the choice in the method:

def flip(p):
    if random.random() < p:
        return 'H'
    else:
        return 'T'

but it'd be less generally useful that way.

OwnerDisplayName: David


问:
How to get a ListView from a ListViewItem?
I've got a ListViewItem that is added to a ListView, but I don't know which ListView it is added to.

I would like to (through the ListViewItem) to be able to grab the ListView from the item itself.

I tried using the Parent property, but for some reason, it returns a StackPanel.

Any ideas?

答:
I've gotten this to run and work:</p>

```<code>private void Window_Loaded(object s, RoutedEventArgs args)
    {
        var collectionview = CollectionViewSource.GetDefaultView(this.listview.Items);
        collectionview.CollectionChanged += (sender, e) =>
        {
            if (e.NewItems != null && e.NewItems.Count > 0)
            {
                var added = e.NewItems[0];
                ListViewItem item = added as ListViewItem;
                ListView parent = FindParent<ListView>(item);
            }
        };

    }
    public static T FindParent<T>(FrameworkElement element) where T : FrameworkElement
    {
        FrameworkElement parent = LogicalTreeHelper.GetParent(element) as FrameworkElement;

        while (parent != null)
        {
            T correctlyTyped = parent as T;
            if (correctlyTyped != null)
                return correctlyTyped;
            else
                return FindParent<T>(parent);
        }

        return null;
    }
</code>```

Body:
I've gotten this to run and work:

private void Window_Loaded(object s, RoutedEventArgs args)
    {
        var collectionview = CollectionViewSource.GetDefaultView(this.listview.Items);
        collectionview.CollectionChanged += (sender, e) =>
        {
            if (e.NewItems != null && e.NewItems.Count > 0)
            {
                var added = e.NewItems[0];
                ListViewItem item = added as ListViewItem;
                ListView parent = FindParent<ListView>(item);
            }
        };

    }
    public static T FindParent<T>(FrameworkElement element) where T : FrameworkElement
    {
        FrameworkElement parent = LogicalTreeHelper.GetParent(element) as FrameworkElement;

        while (parent != null)
        {
            T correctlyTyped = parent as T;
            if (correctlyTyped != null)
                return correctlyTyped;
            else
                return FindParent<T>(parent);
        }

        return null;
    }


问:
FullScreen drawer with material-ui@next
How would I go about recreating a full screen drawer form the first material-ui version in the @next version?

I used to be able to do this

```<code><Drawer width={'100%'} open={this.props.eventsDrawer} className="events-drawer">
...
</Drawer>
</code>```

But now I don't see a way to do this? Would I have to use CSS to achieve this, and if so what element to I apply it to?

答:
The Responsive Drawer demo shows how you can size the drawer using classes.  Here is a stripped down version of that demo:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Drawer from 'material-ui/Drawer';

const styles = {
  drawerPaper: {
    width: '100%',
  },
};

const ResponsiveDrawer = ({ classes }) => (

    <Drawer
      type="temporary"
      classes={{
        paper: classes.drawerPaper,
      }}
    >
      ...
    </Drawer>

);

export default withStyles(styles)(ResponsiveDrawer);
```

The Drawer will flex to fill its container, so to change its size, you wrap the Drawer and apply a class to the wrapper.

In this demo, we define a class in the styles object using JSS and use the withStyles higher-order component to provide the ResponsiveDrawer component with a classes object.

withStyles will also accept a factory function, which is what you'd do if you need to reference theme variables.  This is done in the full version of this demo.

This approach is described in greater detail in Overriding with classes.

Title: FullScreen drawer with material-ui@next

Body:
How would I go about recreating a full screen drawer form the first material-ui version in the @next version?

I used to be able to do this

<Drawer width={'100%'} open={this.props.eventsDrawer} className="events-drawer">
...
</Drawer>

But now I don't see a way to do this? Would I have to use CSS to achieve this, and if so what element to I apply it to?

Body:
The Responsive Drawer demo shows how you can size the drawer using classes.  Here is a stripped down version of that demo:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Drawer from 'material-ui/Drawer';

const styles = {
  drawerPaper: {
    width: '100%',
  },
};

const ResponsiveDrawer = ({ classes }) => (
  <div>
    <Drawer
      type="temporary"
      classes={{
        paper: classes.drawerPaper,
      }}
    >
      ...
    </Drawer>
  </div>
);

export default withStyles(styles)(ResponsiveDrawer);

The Drawer will flex to fill its container, so to change its size, you wrap the Drawer and apply a class to the wrapper.

In this demo, we define a class in the styles object using JSS and use the withStyles higher-order component to provide the ResponsiveDrawer component with a classes object.

withStyles will also accept a factory function, which is what you'd do if you need to reference theme variables.  This is done in the full version of this demo.

This approach is described in greater detail in Overriding with classes.


问:
How to send authentication parameters in PUT request - Jmeter
Trying to perform a load testing using Jmeter tool however can not pass authentication.
The following curl works well

```<code>curl -u <USERNAME>:<PASSWORD> -X PUT "http://server-url/artifactory/my-repository/my/new/artifact/directory/file.txt" -T Desktop/myNewFile.txt
</code>```

I need to upload file via PUT method based on the curl sample above and can not do it because do not understand where username and password values should be placed in the HTTP Request sampler, in the parameters part, Post Body or somewhere else.

Thanks you

答:
Guessing, but you probably add the HTTP header

```<code>Authentication: basic [base64 of username:password]
</code>```

Google "HTTP Basic Authentication"

Body:
Trying to perform a load testing using Jmeter tool however can not pass authentication.
The following curl works well

curl -u <USERNAME>:<PASSWORD> -X PUT "http://server-url/artifactory/my-repository/my/new/artifact/directory/file.txt" -T Desktop/myNewFile.txt

I need to upload file via PUT method based on the curl sample above and can not do it because do not understand where username and password values should be placed in the HTTP Request sampler, in the parameters part, Post Body or somewhere else.

Thanks you

Body:
Guessing, but you probably add the HTTP header

Authentication: basic [base64 of username:password]

Google "HTTP Basic Authentication"


问:
UWP StorageFolder.GetFilesAsync() returns System.__ComObject
In UWP app I'm trying to access images from app storage folder using StorageFolder.GetFilesAsync() nethod.

```<code>    public async void GetMediaFiles()
    {

        _localMediaFolder = await GetOrCreateFolder(ApplicationData.Current.LocalFolder, "Media", ReservationId.ToString());
        IReadOnlyList<StorageFile> files = await _localMediaFolder.GetFilesAsync();

    }
</code>```

Iv'e tried to use known folder as well with the same result.

```<code>    public async void GetMediaFiles()
    {

        StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
        _tempMediaFolder = await picturesFolder.CreateFolderAsync("media", CreationCollisionOption.OpenIfExists);
        IReadOnlyList<StorageFile> storageFilesOperation = await _tempMediaFolder.GetFilesAsync();

    }
</code>```

Instead of 'IReadOnlyList' Im getting 'System.__ComObject'.
I can't cast it to 'IReadOnlyList' and don't know how to use it to get the files i need.

Iv'e tried to use known folder as well with the same result.
there is no exception int the Output indicating that the app have no access to the file or folder.
Iv'e also checked the app manifest for access for the pictures library.

How Can I Fix this?

答:
This is by design. There's no need to cast System.__ComObject to IReadOnlyList because IReadOnlyList is an interface, which means when you create a variable of this type you can assign to it an instance of any class that implements the IReadOnlyList interface, and System.__ComObject is such class. You can continue working with storageFilesOperation as usual, e.g. delete all files:

```<code>StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
var _tempMediaFolder = await picturesFolder.CreateFolderAsync("media", CreationCollisionOption.OpenIfExists);
IReadOnlyList<StorageFile> storageFilesOperation = await _tempMediaFolder.GetFilesAsync();

foreach(StorageFile f in storageFilesOperation)
{
    await f.DeleteAsync();
}
</code>```

Body:
In UWP app I'm trying to access images from app storage folder using StorageFolder.GetFilesAsync() nethod.

    public async void GetMediaFiles()
    {

        _localMediaFolder = await GetOrCreateFolder(ApplicationData.Current.LocalFolder, "Media", ReservationId.ToString());
        IReadOnlyList<StorageFile> files = await _localMediaFolder.GetFilesAsync();

    }

Iv'e tried to use known folder as well with the same result.

    public async void GetMediaFiles()
    {

        StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
        _tempMediaFolder = await picturesFolder.CreateFolderAsync("media", CreationCollisionOption.OpenIfExists);
        IReadOnlyList<StorageFile> storageFilesOperation = await _tempMediaFolder.GetFilesAsync();

    }

Instead of 'IReadOnlyList' Im getting 'System.__ComObject'.
I can't cast it to 'IReadOnlyList' and don't know how to use it to get the files i need.

Iv'e tried to use known folder as well with the same result.
there is no exception int the Output indicating that the app have no access to the file or folder.
Iv'e also checked the app manifest for access for the pictures library.

How Can I Fix this?

Body:
This is by design. There's no need to cast System.__ComObject to IReadOnlyList because IReadOnlyList is an interface, which means when you create a variable of this type you can assign to it an instance of any class that implements the IReadOnlyList interface, and System.__ComObject is such class. You can continue working with storageFilesOperation as usual, e.g. delete all files:

StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
var _tempMediaFolder = await picturesFolder.CreateFolderAsync("media", CreationCollisionOption.OpenIfExists);
IReadOnlyList<StorageFile> storageFilesOperation = await _tempMediaFolder.GetFilesAsync();

foreach(StorageFile f in storageFilesOperation)
{
    await f.DeleteAsync();
}


问:
scraping a div with confirmation popup
I am trying to scrape a file in this site.

https://data.gov.in/catalog/complete-towns-directory-indiastatedistrictsub-district-level-census-2011

I am looking to download excelsheet with complete directory of towns of TRIPURA. first one in grid list.

my code is :

```<code>import requests
import selenium

with requests.Session() as session:
    session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'}

response = session.get(URL)
soup = BeautifulSoup(response.content, 'html.parser')
soup
</code>```

And the corresponding element to get our file is given below. how to actually download that particular excel. it will direct to another window where the purpose has to be given and email address. It would be great if you could provide solution to this.

```<code><div class="view-content">
<div class="views-row views-row-1 views-row-odd views-row-first ogpl-grid-list">
<div class="views-field views-field-title"> <span class="field-content"><a href="/resources/complete-town-directory-indiastatedistrictsub-district-level-census-2011-tripura"><span class="title-content">Complete Town Directory by India/State/District/Sub-District Level, Census 2011 - TRIPURA</span></a></span> </div>
<div class="views-field views-field-field-short-name confirmation-popup-177303 download-confirmation-box file-container excel"> <div class="field-content"><a class="177303 data-extension excel" href="https://data.gov.in/resources/complete-town-directory-indiastatedistrictsub-district-level-census-2011-tripura" target="_blank" title="excel (Open in new window)">excel</a></div> </div>
<div class="views-field views-field-dms-allowed-operations-3 visual-access"> <span class="field-content">Visual Access: NA</span> </div>
<div class="views-field views-field-field-granularity"> <span class="views-label views-label-field-granularity">Granularity: </span> <div class="field-content">Decadal</div> </div>
<div class="views-field views-field-nothing-1 download-file"> <span class="field-content"><span class="download-filesize">File Size: 44.5 KB</span></span> </div>
<div class="views-field views-field-field-file-download-count"> <span class="field-content download-counts"> Download: 529</span> </div>
<div class="views-field views-field-field-reference-url"> <span class="views-label views-label-field-reference-url">Reference URL: </span> <div class="field-content"><a href="http://www.censusindia.gov.in/2011census/Listofvillagesandtowns.aspx">http://www.censusindia.gov.in/2011census...</a></div> </div>
<div class="views-field views-field-dms-allowed-operations-1 vote_request_data_api"> <span class="field-content"><a class="api-link" href="https://data.gov.in/resources/complete-town-directory-indiastatedistrictsub-district-level-census-2011-tripura/api" title="View API">Data API</a></span> </div>
<div class="views-field views-field-field-note"> <span class="views-label views-label-field-note">Note: </span> <div class="field-content ogpl-more">NA</div> </div>
<div class="views-field views-field-dms-allowed-operations confirmationpopup-177303 data-export-cont"> <span class="views-label views-label-dms-allowed-operations">EXPORT IN: </span> <span class="field-content"><ul></ul></span> </div> </div>
</code>```

答:
When you click on the excel link it opens the following page :

```<code>https://data.gov.in/node/ID/download
</code>```

It seems that the ID is the name of the first class of the link eg t.find('a')['class'][0]. Maybe there is a more concise method to get the id but it works as is using the classname

Then the page https://data.gov.in/node/ID/download redirects to the final URL (of the file).

The following is gathering all the URL in a list :

```<code>import requests
from bs4 import BeautifulSoup

URL = 'https://data.gov.in/catalog/complete-towns-directory-indiastatedistrictsub-district-level-census-2011'

src = requests.get(URL)
soup = BeautifulSoup(src.content, 'html.parser')

node_list = [
    t.find('a')['class'][0]
    for t in soup.findAll("div", { "class" : "excel" })
]

url_list = []

for url in node_list:
    node = requests.get("https://data.gov.in/node/{0}/download".format(url))
    soup = BeautifulSoup(node.content, 'html.parser')
    content = soup.find_all("meta")[1]["content"].split("=")[1]
    url_list.append(content)

print(url_list)
</code>```

Complete code that downloads the files using default filename (using this post) :

```<code>import requests
from bs4 import BeautifulSoup
import urllib2
import shutil
import urlparse
import os

def download(url, fileName=None):
    def getFileName(url,openUrl):
        if 'Content-Disposition' in openUrl.info():
            # If the response has Content-Disposition, try to get filename from it
            cd = dict(map(
                lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),
                openUrl.info()['Content-Disposition'].split(';')))
            if 'filename' in cd:
                filename = cd['filename'].strip("\"'")
                if filename: return filename
        # if no filename was found above, parse it out of the final URL.
        return os.path.basename(urlparse.urlsplit(openUrl.url)[2])

    r = urllib2.urlopen(urllib2.Request(url))
    try:
        fileName = fileName or getFileName(url,r)
        with open(fileName, 'wb') as f:
            shutil.copyfileobj(r,f)
    finally:
        r.close()

URL = 'https://data.gov.in/catalog/complete-towns-directory-indiastatedistrictsub-district-level-census-2011'

src = requests.get(URL)
soup = BeautifulSoup(src.content, 'html.parser')

node_list = [
    t.find('a')['class'][0]
    for t in soup.findAll("div", { "class" : "excel" })
]

url_list = []

for url in node_list:
    node = requests.get("https://data.gov.in/node/{0}/download".format(url))
    soup = BeautifulSoup(node.content, 'html.parser')
    content = soup.find_all("meta")[1]["content"].split("=")[1]
    url_list.append(content)
    print("download : " + content)
    download(content)
</code>```

Title: scraping a div with confirmation popup

Body:
I am trying to scrape a file in this site.

https://data.gov.in/catalog/complete-towns-directory-indiastatedistrictsub-district-level-census-2011

I am looking to download excelsheet with complete directory of towns of TRIPURA. first one in grid list.

my code is :

import requests
import selenium

with requests.Session() as session:
    session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'}

response = session.get(URL)
soup = BeautifulSoup(response.content, 'html.parser')
soup

And the corresponding element to get our file is given below. how to actually download that particular excel. it will direct to another window where the purpose has to be given and email address. It would be great if you could provide solution to this.

 Complete Town Directory by India/State/District/Sub-District Level, Census 2011 - TRIPURA

excel

 Visual Access: NA

 Granularity:
Decadal

 File Size: 44.5 KB

  Download: 529

 Reference URL:
http://www.censusindia.gov.in/2011census...

 Data API

 Note:
NA

 EXPORT IN:

Body:
When you click on the excel link it opens the following page :

https://data.gov.in/node/ID/download

It seems that the ID is the name of the first class of the link eg t.find('a')['class'][0]. Maybe there is a more concise method to get the id but it works as is using the classname

Then the page https://data.gov.in/node/ID/download redirects to the final URL (of the file).

The following is gathering all the URL in a list :

import requests
from bs4 import BeautifulSoup

URL = 'https://data.gov.in/catalog/complete-towns-directory-indiastatedistrictsub-district-level-census-2011'

src = requests.get(URL)
soup = BeautifulSoup(src.content, 'html.parser')

node_list = [
    t.find('a')['class'][0]
    for t in soup.findAll("div", { "class" : "excel" })
]

url_list = []

for url in node_list:
    node = requests.get("https://data.gov.in/node/{0}/download".format(url))
    soup = BeautifulSoup(node.content, 'html.parser')
    content = soup.find_all("meta")[1]["content"].split("=")[1]
    url_list.append(content)

print(url_list)

Complete code that downloads the files using default filename (using this post) :

import requests
from bs4 import BeautifulSoup
import urllib2
import shutil
import urlparse
import os

def download(url, fileName=None):
    def getFileName(url,openUrl):
        if 'Content-Disposition' in openUrl.info():
            # If the response has Content-Disposition, try to get filename from it
            cd = dict(map(
                lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),
                openUrl.info()['Content-Disposition'].split(';')))
            if 'filename' in cd:
                filename = cd['filename'].strip("\"'")
                if filename: return filename
        # if no filename was found above, parse it out of the final URL.
        return os.path.basename(urlparse.urlsplit(openUrl.url)[2])

    r = urllib2.urlopen(urllib2.Request(url))
    try:
        fileName = fileName or getFileName(url,r)
        with open(fileName, 'wb') as f:
            shutil.copyfileobj(r,f)
    finally:
        r.close()

URL = 'https://data.gov.in/catalog/complete-towns-directory-indiastatedistrictsub-district-level-census-2011'

src = requests.get(URL)
soup = BeautifulSoup(src.content, 'html.parser')

node_list = [
    t.find('a')['class'][0]
    for t in soup.findAll("div", { "class" : "excel" })
]

url_list = []

for url in node_list:
    node = requests.get("https://data.gov.in/node/{0}/download".format(url))
    soup = BeautifulSoup(node.content, 'html.parser')
    content = soup.find_all("meta")[1]["content"].split("=")[1]
    url_list.append(content)
    print("download : " + content)
    download(content)


问:
Add comma to output
I have created a calculator that shows the output of savings with a specific calculation. I just need the result to be formatted with commas and to be currency so it does not show every number after the decimal. For example if the outcome was:

$2500.566695969
I would only want it to show:
$2,500.56

I hope that makes sense, I tried a couple of things to get the comma in the right place but nothing worked. I am a bit newer to jQuery and this is my first attempt at a calculator like this. Any help is really appreciated. Below is my code.

```<code>function calculate() {
    var savingsVal = (jQuery('#savingsVal').val());
    var totalSavings = 0;
    var regType = (jQuery('#reg-type').val());

    if (filterValues(savingsVal)) {
        totalSavings = savingsVal * 0.15 * 3 - regType * 3;
    }

    jQuery('#totalSavings').val('$' + totalSavings);
}

function filterValues(eVal) {
    return true;
}

jQuery('.results-area').hide();

jQuery('#calculator').submit(function(e) {
    e.preventDefault();
    calculate();
    jQuery('.results-area').show("slow");
    jQuery(this).text( jQuery(this).submit().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
});
</code>```

答: You can try <code>/(\d)(?=(\d{3})+(?!\d))/g, "$1,"</code> instead of your current Regex in the replace function. </p>

Title: Add comma to output

Body:
I have created a calculator that shows the output of savings with a specific calculation. I just need the result to be formatted with commas and to be currency so it does not show every number after the decimal. For example if the outcome was:

$2500.566695969
I would only want it to show:
$2,500.56

I hope that makes sense, I tried a couple of things to get the comma in the right place but nothing worked. I am a bit newer to jQuery and this is my first attempt at a calculator like this. Any help is really appreciated. Below is my code.

function calculate() {
    var savingsVal = (jQuery('#savingsVal').val());
    var totalSavings = 0;
    var regType = (jQuery('#reg-type').val());

    if (filterValues(savingsVal)) {
        totalSavings = savingsVal * 0.15 * 3 - regType * 3;
    }

    jQuery('#totalSavings').val('$' + totalSavings);
}

function filterValues(eVal) {
    return true;
}

jQuery('.results-area').hide();

jQuery('#calculator').submit(function(e) {
    e.preventDefault();
    calculate();
    jQuery('.results-area').show("slow");
    jQuery(this).text( jQuery(this).submit().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
});

Body: You can try /(\d)(?=(\d{3})+(?!\d))/g, "$1," instead of your current Regex in the replace function.


问:
Netlogo list updated in time
I'm writing up a code in Netlogo that basically should do the following:

Amongst directed links, interact and seek out their cooperative behavior (coop_b).

Store coop_b in a list variable together with the time of the interaction (reputation_now)

Every interaction, add the reputation_now to a bigger list, reputation_h (reputation history)

Now, add a time-weight to the reputation, so that the more recently had interactions weigh more in the total reputation. I do this by dividing the encounter time of an interaction by the current time tick, then multiplying that with the coop_b to retrieve a weighted reputation for each interaction. This is stored in the list reputation_h_w (historic reputations weighted). The thing is, this list should be updated every time the members interact, so that earlier additions to the list are now updated to the new time tick. My hunch is this is where my code goes in the mist (problems depicted below the code section).

My code:

```<code>to horizontal_interact
  ask members [
    ;set random example variable for coop_b
    set coop_b random-float 5 ; coop-b stands for cooperation behavior
    if ticks > 0 [
    ask my-out-links [ ;there are directed links between all members
      set reputation_now (list [coop_b] of end2 ticks) ;list of coop_b and encounter time
      set reputation_h lput reputation_now reputation_h ; history of reputations, a list of all reputation_now recorded
      foreach reputation_h [ x ->

        let cooperative_behavior item 0 x
        let encounter_time item 1 x

        let reputation_now_w (list cooperative_behavior encounter_time (encounter_time / ticks ))

       ]
    ]
   ]
  ]

end
</code>```

If I test the content of reputation_h and reputation_h_w with 2 members, I get:

reputation_h is the coop_b variable of the member and the tick of encounter

```<code>links> show reputation_h
(link 1 0):
[[4.0900840358972825 1]
[0.8885953841506328 2]
[0.47017368072392984 3]]

(link 0 1): [[3.6805257472366164 1]
[3.6805257472366164 2]
[3.4201458793705326 3]]
</code>```

reputation_h_w (containing the member's coop_b variable, the encounter time and the encounter time divided by the ticks):

```<code>links> show reputation_h_w

(link 0 1): [[3.6805257472366164 1 1]
[3.6805257472366164 1 0.5]
[3.6805257472366164 2 1]
[3.6805257472366164 1 0.3333333333333333]
[3.6805257472366164 2 0.6666666666666666]
[3.4201458793705326 3 1]]

(link 1 0): [[4.0900840358972825 1 1]
[4.0900840358972825 1 0.5]
[0.8885953841506328 2 1]
[4.0900840358972825 1 0.3333333333333333]
[0.8885953841506328 2 0.6666666666666666]
[0.47017368072392984 3 1]]
</code>```

The problem is that reputation_h_w doesn't make sense to me - firstly there's six inputs instead of three, and secondly, the encounter time (item 1) and the encounter time/ticks (item 2) is off.

What am I doing wrong here?

答:
Not sure where you update reputation_h_w in your code, but I'm guessing that you are not resetting it to a blank list before running your foreach loop again. So, it's lput-ing the values at the end of the list, which is not blank anymore.

Example setup:

```<code>breed [ as a ]
as-own [ coop_b ]
links-own [ reputation_now reputation_history reputation_history_w]

to setup
  ca
  create-as 2 [
    set coop_b who + 1
    setxy random-pxcor random-pycor
  ]
  while [ any? as with [ not any? my-in-links ] ] [
    ask one-of as with [ not any? my-out-links ] [
      create-link-to one-of other as with [ not any? my-in-links ] [
        set reputation_now []
        set reputation_history []
      ]
    ]
  ]
  reset-ticks
end
</code>```

Note that here I will set reputation_history [] right before the foreach chunk runs:

```<code>to interact
  if ticks > 0 [
    ask links [
      set reputation_now ( list [coop_b] of end2 ticks )
      set reputation_history lput reputation_now reputation_history

      ; reset reputation history to a blank list, as you are
      ; recalculating the weighted value at each tick
      set reputation_history_w []
      foreach reputation_history [ x ->
        let behavior item 0 x
        let encounter_time item 1 x
        let fraction encounter_time / ticks
        set reputation_history_w lput (
          list behavior encounter_time fraction ) reputation_history_w
      ]
      show ( word "Current reputation: " reputation_now )
      show ( word "Reputation history: " reputation_history )
      show ( word "Weighted history rep list: " reputation_history_w )
    ]
  ]
  tick
end
</code>```

As far as why your ticks are off, I'd guess it's because you are calling tick after you run your horizontal_interact procedure. With the example above, my output looks like:

```<code>(link 0 1): "Current reputation: [2 2]"
(link 0 1): "Reputation history: [[2 1] [2 2]]"
(link 0 1): "Weighted history rep list: [[2 1 0.5] [2 2 1]]"
(link 1 0): "Current reputation: [1 2]"
(link 1 0): "Reputation history: [[1 1] [1 2]]"
(link 1 0): "Weighted history rep list: [[1 1 0.5] [1 2 1]]"
</code>```

even though the ticks read 3. If you run it with tick at the start of the procedure, that might sort out your expected output.

Title: Netlogo list updated in time

Body:
I'm writing up a code in Netlogo that basically should do the following:

Amongst directed links, interact and seek out their cooperative behavior (coop_b).

Store coop_b in a list variable together with the time of the interaction (reputation_now)

Every interaction, add the reputation_now to a bigger list, reputation_h (reputation history)

Now, add a time-weight to the reputation, so that the more recently had interactions weigh more in the total reputation. I do this by dividing the encounter time of an interaction by the current time tick, then multiplying that with the coop_b to retrieve a weighted reputation for each interaction. This is stored in the list reputation_h_w (historic reputations weighted). The thing is, this list should be updated every time the members interact, so that earlier additions to the list are now updated to the new time tick. My hunch is this is where my code goes in the mist (problems depicted below the code section).

My code:

to horizontal_interact
  ask members [
    ;set random example variable for coop_b
    set coop_b random-float 5 ; coop-b stands for cooperation behavior
    if ticks > 0 [
    ask my-out-links [ ;there are directed links between all members
      set reputation_now (list [coop_b] of end2 ticks) ;list of coop_b and encounter time
      set reputation_h lput reputation_now reputation_h ; history of reputations, a list of all reputation_now recorded
      foreach reputation_h [ x ->

        let cooperative_behavior item 0 x
        let encounter_time item 1 x

        let reputation_now_w (list cooperative_behavior encounter_time (encounter_time / ticks ))

       ]
    ]
   ]
  ]

end

If I test the content of reputation_h and reputation_h_w with 2 members, I get:

reputation_h is the coop_b variable of the member and the tick of encounter

links> show reputation_h
(link 1 0):
[[4.0900840358972825 1]
[0.8885953841506328 2]
[0.47017368072392984 3]]

(link 0 1): [[3.6805257472366164 1]
[3.6805257472366164 2]
[3.4201458793705326 3]]

reputation_h_w (containing the member's coop_b variable, the encounter time and the encounter time divided by the ticks):

links> show reputation_h_w

(link 0 1): [[3.6805257472366164 1 1]
[3.6805257472366164 1 0.5]
[3.6805257472366164 2 1]
[3.6805257472366164 1 0.3333333333333333]
[3.6805257472366164 2 0.6666666666666666]
[3.4201458793705326 3 1]]

(link 1 0): [[4.0900840358972825 1 1]
[4.0900840358972825 1 0.5]
[0.8885953841506328 2 1]
[4.0900840358972825 1 0.3333333333333333]
[0.8885953841506328 2 0.6666666666666666]
[0.47017368072392984 3 1]]

The problem is that reputation_h_w doesn't make sense to me - firstly there's six inputs instead of three, and secondly, the encounter time (item 1) and the encounter time/ticks (item 2) is off.

What am I doing wrong here?

Body:
Not sure where you update reputation_h_w in your code, but I'm guessing that you are not resetting it to a blank list before running your foreach loop again. So, it's lput-ing the values at the end of the list, which is not blank anymore.

Example setup:

breed [ as a ]
as-own [ coop_b ]
links-own [ reputation_now reputation_history reputation_history_w]

to setup
  ca
  create-as 2 [
    set coop_b who + 1
    setxy random-pxcor random-pycor
  ]
  while [ any? as with [ not any? my-in-links ] ] [
    ask one-of as with [ not any? my-out-links ] [
      create-link-to one-of other as with [ not any? my-in-links ] [
        set reputation_now []
        set reputation_history []
      ]
    ]
  ]
  reset-ticks
end

Note that here I will set reputation_history [] right before the foreach chunk runs:

to interact
  if ticks > 0 [
    ask links [
      set reputation_now ( list [coop_b] of end2 ticks )
      set reputation_history lput reputation_now reputation_history

      ; reset reputation history to a blank list, as you are
      ; recalculating the weighted value at each tick
      set reputation_history_w []
      foreach reputation_history [ x ->
        let behavior item 0 x
        let encounter_time item 1 x
        let fraction encounter_time / ticks
        set reputation_history_w lput (
          list behavior encounter_time fraction ) reputation_history_w
      ]
      show ( word "Current reputation: " reputation_now )
      show ( word "Reputation history: " reputation_history )
      show ( word "Weighted history rep list: " reputation_history_w )
    ]
  ]
  tick
end

As far as why your ticks are off, I'd guess it's because you are calling tick after you run your horizontal_interact procedure. With the example above, my output looks like:

(link 0 1): "Current reputation: [2 2]"
(link 0 1): "Reputation history: [[2 1] [2 2]]"
(link 0 1): "Weighted history rep list: [[2 1 0.5] [2 2 1]]"
(link 1 0): "Current reputation: [1 2]"
(link 1 0): "Reputation history: [[1 1] [1 2]]"
(link 1 0): "Weighted history rep list: [[1 1 0.5] [1 2 1]]"

even though the ticks read 3. If you run it with tick at the start of the procedure, that might sort out your expected output.


问:
android studio cannot resolve symbol on functions and ID's
Total noob here. Can't get the MainActivity to recognise any function or IDs. Tried a few of the simpler solutions;
- (File -> Indicate Cashes) --> (Invalidate and Restart)
- Clean project
- Rebuild project

cheers

Not working
Errors

答: Soldier, lowercase that private</p>

Body: Soldier, lowercase that private


问:
Script to downsize SYSTEM_TIME column from DATETIME2(7) to DATETIME2(3)
For all temporal tables within a database, I seek a script which generates T-SQL to downsize their SYSTEM_TIME columns from DATETIME2(7) to DATETIME2(3).

My rationale: I want to be able to update such tables from within an MS Access database when the tables are linked via an ODBC connection. Access doesn't support DATETIME2(7) for updates when linked via the ODBC driver (The field is too large). Conversely, the SQL Server Native Client driver works (supposedly, I haven't tried it); but it doesn't support Active Directory - Integrated connections. Moreover my application doesn't require the extra precision for these fields.

The generated code will be something like the following. Just curious if someone might have such a script?

```<code>CREATE TABLE [dbo].[Tasks] (
    [Id]           INT                                                IDENTITY (1, 1) NOT NULL,
    [Task]         NVARCHAR(50)                                       NOT NULL,
    [ValidFrom]    DATETIME2(7) GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
    [ValidTo]      DATETIME2 (7) GENERATED ALWAYS AS ROW END HIDDEN   NOT NULL,
    [Who]          NVARCHAR (128)                                     CONSTRAINT [DF_dbo_Tasks_Who] DEFAULT (SUSER_SNAME()) NOT NULL,
    CONSTRAINT [PK_dbo_Tasks] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_Tasks_Task] UNIQUE NONCLUSTERED ([Task] ASC),
    PERIOD FOR SYSTEM_TIME ([ValidFrom], [ValidTo])
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[History_Tasks], DATA_CONSISTENCY_CHECK=ON));
GO

INSERT INTO dbo.Tasks (Task)
VALUES (N'Task 1'), (N'Task 2'), (N'Task 3'), (N'Task 4'), (N'Task 5');
GO

UPDATE dbo.Tasks SET Task = N'Task 1.1' WHERE Id = 1;
DELETE FROM dbo.Tasks WHERE Id = 3;
INSERT INTO dbo.Tasks (Task) VALUES (N'Task 6');
GO

SELECT * FROM dbo.Tasks
SELECT * FROM dbo.History_Tasks
GO
---------------------------------------------------------------------------------------------------
ALTER TABLE dbo.Tasks SET (SYSTEM_VERSIONING = OFF);
ALTER TABLE dbo.Tasks DROP PERIOD FOR SYSTEM_TIME;
GO
ALTER TABLE dbo.Tasks ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;
ALTER TABLE dbo.Tasks ALTER COLUMN ValidTo   DATETIME2(3) NOT NULL;
DROP INDEX ix_History_Tasks ON dbo.History_Tasks;
ALTER TABLE dbo.History_Tasks ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;
ALTER TABLE dbo.History_Tasks ALTER COLUMN ValidTo DATETIME2(3) NOT NULL;
ALTER TABLE dbo.Tasks ADD PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
ALTER TABLE dbo.Tasks SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE=dbo.History_Tasks));
CREATE CLUSTERED INDEX ix_History_Tasks ON dbo.History_Tasks(ValidTo ASC, ValidFrom ASC);
GO
---------------------------------------------------------------------------------------------------
-- ... Next table ...
</code>```

答:
You can add a new column, set it to the value of the old column, delete the old column, and then rename the new one to the old name.

The following will generate the scripts for you which you then can execute.  I will caution that I don't have SQL Server in front of me so you'll want to double check my quote escaping.

```<code>SELECT 'ALTER TABLE ' + t.table_name + ' ADD new_col DateTime2(3); UPDATE TABLE ' +
        t.table_name + ' SET new_col = ' + c.column_name + '; ALTER TABLE ' +
        t.table_name + ' DROP COLUMN ' + c.column_name + '; EXEC sp_rename ''' +
        t.table_name + '.new_col'', ''' + c.column_name + ''' + , '''COLUMN''' + '; '
FROM information_schema.tables t
    INNER JOIN information_schema.columns c ON t.object_id=c.object_id
WHERE c. --pick out your temporal columns here by type or name
</code>```

For each table/column combo it will give you something like this:

```<code>ALTER TABLE myTable ADD new_col DateTime2(3);
UPDATE myTable SET new_col = oldColName;
ALTER TABLE myTable DROP COLUMN oldColName;
EXEC sp_rename 'myTable.new_col', 'oldColName', 'COLUMN';
</code>```

Body:
For all temporal tables within a database, I seek a script which generates T-SQL to downsize their SYSTEM_TIME columns from DATETIME2(7) to DATETIME2(3).

My rationale: I want to be able to update such tables from within an MS Access database when the tables are linked via an ODBC connection. Access doesn't support DATETIME2(7) for updates when linked via the ODBC driver (The field is too large). Conversely, the SQL Server Native Client driver works (supposedly, I haven't tried it); but it doesn't support Active Directory - Integrated connections. Moreover my application doesn't require the extra precision for these fields.

The generated code will be something like the following. Just curious if someone might have such a script?

CREATE TABLE [dbo].[Tasks] (
    [Id]           INT                                                IDENTITY (1, 1) NOT NULL,
    [Task]         NVARCHAR(50)                                       NOT NULL,
    [ValidFrom]    DATETIME2(7) GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
    [ValidTo]      DATETIME2 (7) GENERATED ALWAYS AS ROW END HIDDEN   NOT NULL,
    [Who]          NVARCHAR (128)                                     CONSTRAINT [DF_dbo_Tasks_Who] DEFAULT (SUSER_SNAME()) NOT NULL,
    CONSTRAINT [PK_dbo_Tasks] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [UQ_Tasks_Task] UNIQUE NONCLUSTERED ([Task] ASC),
    PERIOD FOR SYSTEM_TIME ([ValidFrom], [ValidTo])
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[History_Tasks], DATA_CONSISTENCY_CHECK=ON));
GO

INSERT INTO dbo.Tasks (Task)
VALUES (N'Task 1'), (N'Task 2'), (N'Task 3'), (N'Task 4'), (N'Task 5');
GO

UPDATE dbo.Tasks SET Task = N'Task 1.1' WHERE Id = 1;
DELETE FROM dbo.Tasks WHERE Id = 3;
INSERT INTO dbo.Tasks (Task) VALUES (N'Task 6');
GO

SELECT * FROM dbo.Tasks
SELECT * FROM dbo.History_Tasks
GO
---------------------------------------------------------------------------------------------------
ALTER TABLE dbo.Tasks SET (SYSTEM_VERSIONING = OFF);
ALTER TABLE dbo.Tasks DROP PERIOD FOR SYSTEM_TIME;
GO
ALTER TABLE dbo.Tasks ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;
ALTER TABLE dbo.Tasks ALTER COLUMN ValidTo   DATETIME2(3) NOT NULL;
DROP INDEX ix_History_Tasks ON dbo.History_Tasks;
ALTER TABLE dbo.History_Tasks ALTER COLUMN ValidFrom DATETIME2(3) NOT NULL;
ALTER TABLE dbo.History_Tasks ALTER COLUMN ValidTo DATETIME2(3) NOT NULL;
ALTER TABLE dbo.Tasks ADD PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
ALTER TABLE dbo.Tasks SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE=dbo.History_Tasks));
CREATE CLUSTERED INDEX ix_History_Tasks ON dbo.History_Tasks(ValidTo ASC, ValidFrom ASC);
GO
---------------------------------------------------------------------------------------------------
-- ... Next table ...

Body:
You can add a new column, set it to the value of the old column, delete the old column, and then rename the new one to the old name.

The following will generate the scripts for you which you then can execute.  I will caution that I don't have SQL Server in front of me so you'll want to double check my quote escaping.

SELECT 'ALTER TABLE ' + t.table_name + ' ADD new_col DateTime2(3); UPDATE TABLE ' +
        t.table_name + ' SET new_col = ' + c.column_name + '; ALTER TABLE ' +
        t.table_name + ' DROP COLUMN ' + c.column_name + '; EXEC sp_rename ''' +
        t.table_name + '.new_col'', ''' + c.column_name + ''' + , '''COLUMN''' + '; '
FROM information_schema.tables t
    INNER JOIN information_schema.columns c ON t.object_id=c.object_id
WHERE c. --pick out your temporal columns here by type or name

For each table/column combo it will give you something like this:

ALTER TABLE myTable ADD new_col DateTime2(3);
UPDATE myTable SET new_col = oldColName;
ALTER TABLE myTable DROP COLUMN oldColName;
EXEC sp_rename 'myTable.new_col', 'oldColName', 'COLUMN';


问:
Hide a range of columns using script - Google Sheets
So I have got a spreadsheet that is basically a diary of appointments containing 12 months, I have the below script contained within the spreadsheet that hides columns (to save time) the problem is that there is too much data and this takes a long time, especially the hideAll function!

I was wondering if there is a way I can change these functions to hide the columns as ranges instead of as individual columns, I haven't managed to find anything like this so far. I would need to be able to set up the menu the same and be able to hide each month individually and if possible hide all as a function also (like the existing script but in blocks not individually). This has to be ranges as I have columns in between each month that need to stay visible and not be hidden.

Please see example spreadsheet below (this is not an up to date version but the script it contains is what is used live on the real version!)

https://docs.google.com/spreadsheets/d/1sOlQEzG1D29RaY86YeR1Da--c8t94J-ZAGjv52U4dsY/edit?usp=sharing

```<code>function onOpen(){
SpreadsheetApp.getUi().createMenu('Sophie\'s Menu :)')
  .addItem('Relative validation', 'copyValidation')
  .addItem('Relative rows, absolute columns', 'copyValidationColumnsAbsolute')
  .addItem('Absolute rows, relative columns', 'copyValidationRowsAbsolute')
  .addItem('Hide All Months', 'hideAll')
  .addItem('Hide January', 'hideCols1')
  .addItem('Hide February', 'hideCols2')
  .addItem('Hide March', 'hideCols3')
  .addItem('Hide April', 'hideCols4')
  .addItem('Hide May', 'hideCols5')
  .addItem('Hide June', 'hideCols6')
  .addItem('Hide July', 'hideCols7')
  .addItem('Hide August', 'hideCols8')
  .addItem('Hide September', 'hideCols9')
  .addItem('Hide October', 'hideCols10')
  .addItem('Hide November', 'hideCols11')
  .addItem('Hide December', 'hideCols12')
  .addToUi();
}

function copyValidation(rowsAbsolute, columnsAbsolute)
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var r = ss.getActiveRange();
  var dv = r.getDataValidations();
  var dvt = dv[0][0].getCriteriaType();
  if (dvt != SpreadsheetApp.DataValidationCriteria.VALUE_IN_RANGE) return;
  var dvv = dv[0][0].getCriteriaValues();
  Logger.log(dvv);
  for (var i = 0; i < dv.length; i++)
  {
    for (var j = i ? 0 : 1; j < dv[0].length; j++)
    {

  dv[i][j] = dv[0][0].copy().withCriteria(dvt, [dvv[0].offset(rowsAbsolute ?
  0 : i, columnsAbsolute ? 0 : j), dvv[1]]).build();
    }
  }
  r.setDataValidations(dv);
}

function copyValidationRowsAbsolute()
{
  copyValidation(true, false);
}

function copyValidationColumnsAbsolute()
{
  copyValidation(false, true);
}

function hideCols1(){

showhideCols('3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33',false);
}

function hideCols2(){
  showhideCols('35,36,37,38,39,40,41,42,43,44,45,46,47,
  48,49,50,51,52,53,54,55,56,57,58,59,60,61,62',false);
}

function hideCols3(){

showhideCols('64,65,66,67,68,69,70,71,72,73,74,75,76,77,
78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94',false);
}

function hideCols4(){
  showhideCols('96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,
  111,112,113,114,115,116,117,118,119,120,121,122,123,124,125',false);
}

//Right up to hideCols12

function hideCols12(){
  showhideCols('348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,
  364,365,366,367,368,369,370,371,372,373,374,375,376,377,378',false);
}

//I even have a hideAll function that contains every single column listed above!

function showhideCols(colscsv,show){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  if(!colscsv){
    var resp=SpreadsheetApp.getUi().prompt('Enter Column Numbers separated by
commas.', SpreadsheetApp.getUi().Button.OK);
    var cA=resp.getResponseText().split(',');
  }else{
    var cA=colscsv.split(',');
  }
  for(var i=0;i<cA.length;i++){
    if(show){
      sh.showColumns(cA[i]);
    }else{
      sh.hideColumns(cA[i]);
    }
  }
}
</code>```

答:
If the indexes in the hideColsN() are static, then you only need to send the starting columnIndex and the numColumns in the range to hideColumns(columnIndex, numColumns)

```<code>function hideCols1(){
  showhideCols(3, 31, false);
}
</code>```

```<code>function showhideCols(start, amount, show){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();

  // set variables to the list of numbers from the prompt
  // may want to change it to take the startIndex and number of columns to hide/show.
  // also there was not a way listed to determine if the columns should be hidden or not.
  if(!start){
    var resp=SpreadsheetApp.getUi().prompt('Enter Column Numbers separated by commas.', SpreadsheetApp.getUi().ButtonSet.OK);
    var cA=resp.getResponseText().split(',');
    var start = cA[0];
    var amount = cA.length;
    var show = false;
  }
  // Show or hide column ranges in one call
  if(show){
    sh.showColumns(start, amount);
  }else{
    sh.hideColumns(start, amount);
  }

}
</code>```

edit: I may be overlooking it, but I didnt see your hideAll() method so that was not added to this answer

Body:
So I have got a spreadsheet that is basically a diary of appointments containing 12 months, I have the below script contained within the spreadsheet that hides columns (to save time) the problem is that there is too much data and this takes a long time, especially the hideAll function!

I was wondering if there is a way I can change these functions to hide the columns as ranges instead of as individual columns, I haven't managed to find anything like this so far. I would need to be able to set up the menu the same and be able to hide each month individually and if possible hide all as a function also (like the existing script but in blocks not individually). This has to be ranges as I have columns in between each month that need to stay visible and not be hidden.

Please see example spreadsheet below (this is not an up to date version but the script it contains is what is used live on the real version!)

https://docs.google.com/spreadsheets/d/1sOlQEzG1D29RaY86YeR1Da--c8t94J-ZAGjv52U4dsY/edit?usp=sharing

function onOpen(){
SpreadsheetApp.getUi().createMenu('Sophie\'s Menu :)')
  .addItem('Relative validation', 'copyValidation')
  .addItem('Relative rows, absolute columns', 'copyValidationColumnsAbsolute')
  .addItem('Absolute rows, relative columns', 'copyValidationRowsAbsolute')
  .addItem('Hide All Months', 'hideAll')
  .addItem('Hide January', 'hideCols1')
  .addItem('Hide February', 'hideCols2')
  .addItem('Hide March', 'hideCols3')
  .addItem('Hide April', 'hideCols4')
  .addItem('Hide May', 'hideCols5')
  .addItem('Hide June', 'hideCols6')
  .addItem('Hide July', 'hideCols7')
  .addItem('Hide August', 'hideCols8')
  .addItem('Hide September', 'hideCols9')
  .addItem('Hide October', 'hideCols10')
  .addItem('Hide November', 'hideCols11')
  .addItem('Hide December', 'hideCols12')
  .addToUi();
}

function copyValidation(rowsAbsolute, columnsAbsolute)
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var r = ss.getActiveRange();
  var dv = r.getDataValidations();
  var dvt = dv[0][0].getCriteriaType();
  if (dvt != SpreadsheetApp.DataValidationCriteria.VALUE_IN_RANGE) return;
  var dvv = dv[0][0].getCriteriaValues();
  Logger.log(dvv);
  for (var i = 0; i < dv.length; i++)
  {
    for (var j = i ? 0 : 1; j < dv[0].length; j++)
    {

  dv[i][j] = dv[0][0].copy().withCriteria(dvt, [dvv[0].offset(rowsAbsolute ?
  0 : i, columnsAbsolute ? 0 : j), dvv[1]]).build();
    }
  }
  r.setDataValidations(dv);
}

function copyValidationRowsAbsolute()
{
  copyValidation(true, false);
}

function copyValidationColumnsAbsolute()
{
  copyValidation(false, true);
}

function hideCols1(){

showhideCols('3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33',false);
}

function hideCols2(){
  showhideCols('35,36,37,38,39,40,41,42,43,44,45,46,47,
  48,49,50,51,52,53,54,55,56,57,58,59,60,61,62',false);
}

function hideCols3(){

showhideCols('64,65,66,67,68,69,70,71,72,73,74,75,76,77,
78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94',false);
}

function hideCols4(){
  showhideCols('96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,
  111,112,113,114,115,116,117,118,119,120,121,122,123,124,125',false);
}

//Right up to hideCols12

function hideCols12(){
  showhideCols('348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,
  364,365,366,367,368,369,370,371,372,373,374,375,376,377,378',false);
}

//I even have a hideAll function that contains every single column listed above!

function showhideCols(colscsv,show){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  if(!colscsv){
    var resp=SpreadsheetApp.getUi().prompt('Enter Column Numbers separated by
commas.', SpreadsheetApp.getUi().Button.OK);
    var cA=resp.getResponseText().split(',');
  }else{
    var cA=colscsv.split(',');
  }
  for(var i=0;i<cA.length;i++){
    if(show){
      sh.showColumns(cA[i]);
    }else{
      sh.hideColumns(cA[i]);
    }
  }
}

Body:
If the indexes in the hideColsN() are static, then you only need to send the starting columnIndex and the numColumns in the range to hideColumns(columnIndex, numColumns)

function hideCols1(){
  showhideCols(3, 31, false);
}

function showhideCols(start, amount, show){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();

  // set variables to the list of numbers from the prompt
  // may want to change it to take the startIndex and number of columns to hide/show.
  // also there was not a way listed to determine if the columns should be hidden or not.
  if(!start){
    var resp=SpreadsheetApp.getUi().prompt('Enter Column Numbers separated by commas.', SpreadsheetApp.getUi().ButtonSet.OK);
    var cA=resp.getResponseText().split(',');
    var start = cA[0];
    var amount = cA.length;
    var show = false;
  }
  // Show or hide column ranges in one call
  if(show){
    sh.showColumns(start, amount);
  }else{
    sh.hideColumns(start, amount);
  }

}

edit: I may be overlooking it, but I didnt see your hideAll() method so that was not added to this answer


问:
Write a Mockito test to verify Class2 method invoked in Class1 method return value
```<code>Class1 {
    private Class2 class2;
    public void f1() {
      class2.f2();
    }}
</code>```

Right now I have Class2 instance mock injected into Class1 instance.
I need to write a test to verify Class2 f2 method return value.
How do I do it?

答:
Use a combination of Mockito.spy and Whitebox to assert that the delegate reference is invoked.</p>

```<code>import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.reflection.Whitebox;

public class MockitoSpy {

    public class ClassTwo {
        public void doAThing(){}
    }

    public class ClassOne {
        private ClassTwo clazz2 = new ClassTwo();
        public void invokeClassTwo() {
            clazz2.doAThing();
        }
    }

    @Test
    public void testDelegationCall() {
        //Create the Object that will be our Spy
        ClassTwo twoRef = new ClassTwo();
        //Make the actual SPY reference
        ClassTwo spy = Mockito.spy(twoRef);
        //Configure the spy to not invoke the actual code -- that's not what we're testing.
        Mockito.doNothing().when(spy).doAThing();

        //Create the Object we want to test.
        ClassOne testInstance = new ClassOne();

        //Replace the field named 'clazz2' in the testInstance with our Spy
        Whitebox.setInternalState(testInstance, "clazz2", spy);

        //Make the call to the testInstance
        testInstance.invokeClassTwo();

        //ASSERT that the spy was called the number of times we would have expected
        Mockito.verify(spy, Mockito.times(1)).doAThing();

    }

}
</code>```

Body:
Class1 {
    private Class2 class2;
    public void f1() {
      class2.f2();
    }}

Right now I have Class2 instance mock injected into Class1 instance.
I need to write a test to verify Class2 f2 method return value.
How do I do it?

Body:
Use a combination of Mockito.spy and Whitebox to assert that the delegate reference is invoked.

import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.reflection.Whitebox;

public class MockitoSpy {

    public class ClassTwo {
        public void doAThing(){}
    }

    public class ClassOne {
        private ClassTwo clazz2 = new ClassTwo();
        public void invokeClassTwo() {
            clazz2.doAThing();
        }
    }

    @Test
    public void testDelegationCall() {
        //Create the Object that will be our Spy
        ClassTwo twoRef = new ClassTwo();
        //Make the actual SPY reference
        ClassTwo spy = Mockito.spy(twoRef);
        //Configure the spy to not invoke the actual code -- that's not what we're testing.
        Mockito.doNothing().when(spy).doAThing();

        //Create the Object we want to test.
        ClassOne testInstance = new ClassOne();

        //Replace the field named 'clazz2' in the testInstance with our Spy
        Whitebox.setInternalState(testInstance, "clazz2", spy);

        //Make the call to the testInstance
        testInstance.invokeClassTwo();

        //ASSERT that the spy was called the number of times we would have expected
        Mockito.verify(spy, Mockito.times(1)).doAThing();

    }

}


问:
Directory.GetDirectories doesn't work as I thought
```<code>public Dir(string rootDir)
    {
        Directories = new List<string>();
        RootDir = rootDir;
        foreach(string dir in Directory.GetDirectories(RootDir, @"*.mp3", SearchOption.AllDirectories))
        {
            Directories.Add(dir);
            Debug.Print(dir);
        }
        Shuffle(Directories);
    }
</code>```

With this code, I wanted to find all the .mp3 files in one folder, but it came out to make a zero element in 'Directories'. What seems to be the problem?

答:
*.mp3 are files. Use Directory.GetFiles();

If you are looking for all mp3s within folders. Do something like this (pseudo-code):

```<code>List<string> mp3s = new List<string>();
foreach(string directory in Directory.GetDirectories(_rootFolder)){
    foreach(string file in Directory.GetFiles(directory)){
        mp3s.Add(file);
    }
}
</code>```

Body:
public Dir(string rootDir)
    {
        Directories = new List<string>();
        RootDir = rootDir;
        foreach(string dir in Directory.GetDirectories(RootDir, @"*.mp3", SearchOption.AllDirectories))
        {
            Directories.Add(dir);
            Debug.Print(dir);
        }
        Shuffle(Directories);
    }

With this code, I wanted to find all the .mp3 files in one folder, but it came out to make a zero element in 'Directories'. What seems to be the problem?

Body:
*.mp3 are files. Use Directory.GetFiles();

If you are looking for all mp3s within folders. Do something like this (pseudo-code):

List<string> mp3s = new List<string>();
foreach(string directory in Directory.GetDirectories(_rootFolder)){
    foreach(string file in Directory.GetFiles(directory)){
        mp3s.Add(file);
    }
}