问:
react- native: 'adb' is not recognized as an internal or external command, operable program or batch file
Am new to react-native android app development. Please help me solve this issue.

Am not able to run my first application, am getting error as adb' is not recognized as an internal or external command, operable program or batch file.

I checked inside android sdk->platform-tools->i can see adb.exe there.

Build is successfull but getting error during run time. Below is my cmd prompt

```<code>Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
E:\ReactWorkSpace\MyFirstApp>react-native run-android
Scanning 560 folders for symlinks in E:\ReactWorkSpace\MyFirstApp\node_modules (72ms)
JS server already running.
Building and installing the app on the device (cd android && gradlew.bat installDebug)...
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library
:app:prepareComAndroidSupportRecyclerviewV72340Library
:app:prepareComAndroidSupportSupportV42340Library
:app:prepareComFacebookFbuiTextlayoutbuilderTextlayoutbuilder100Library
:app:prepareComFacebookFrescoDrawee101Library
:app:prepareComFacebookFrescoFbcore101Library
:app:prepareComFacebookFrescoFresco101Library
:app:prepareComFacebookFrescoImagepipeline101Library
:app:prepareComFacebookFrescoImagepipelineBase101Library
:app:prepareComFacebookFrescoImagepipelineOkhttp3101Library
:app:prepareComFacebookReactReactNative0434Library
:app:prepareComFacebookSoloaderSoloader010Library
:app:prepareOrgWebkitAndroidJscR174650Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:mergeDebugShaders
:app:compileDebugShaders
:app:generateDebugAssets
:app:mergeDebugAssets
:app:generateDebugResValues
:app:generateDebugResources
:app:mergeDebugResources
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:incrementalDebugJavaCompilationSafeguard
:app:compileDebugJavaWithJavac
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources
:app:transformClassesWithDexForDebug
Running dex in-process requires build tools 23.0.2.
For faster builds update this project to use the latest build tools.
:app:mergeDebugJniLibFolders
:app:transformNative_libsWithMergeJniLibsForDebug
:app:processDebugJavaRes UP-TO-DATE
:app:transformResourcesWithMergeJavaResForDebug
:app:validateSigningDebug
:app:packageDebug
:app:assembleDebug
:app:installDebug
Installing APK 'app-debug.apk' on 'A16 - 4.2.2' for app:debug
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 7 mins 4.412 secs
'adb' is not recognized as an internal or external command,
operable program or batch file.
Starting the app (D:\Android\sdk/platform-tools/adb shell am start -n com.myfirstapp/.MainActivity...
Starting: Intent { cmp=com.myfirstapp/.MainActivity }

E:\ReactWorkSpace\MyFirstApp>
</code>```

Am not using emulator, am using my own mobile device. App is launched in my device but all i see is a white blank screen. I followed all the instructions properly as mentioned in the official website.

Thank you.

答:
I encounter this problem and even if you're doing the steps correctly it will not run unless you will do this solution.

For react-native-cli, if you are running the updated version you must install a "Java 11" and if you are running old react native then try installing the "Java 8".

(note that u  will need to restart your system)

Body:
Am new to react-native android app development. Please help me solve this issue.

Am not able to run my first application, am getting error as adb' is not recognized as an internal or external command, operable program or batch file.

I checked inside android sdk->platform-tools->i can see adb.exe there.

Build is successfull but getting error during run time. Below is my cmd prompt

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
E:\ReactWorkSpace\MyFirstApp>react-native run-android
Scanning 560 folders for symlinks in E:\ReactWorkSpace\MyFirstApp\node_modules (72ms)
JS server already running.
Building and installing the app on the device (cd android && gradlew.bat installDebug)...
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library
:app:prepareComAndroidSupportRecyclerviewV72340Library
:app:prepareComAndroidSupportSupportV42340Library
:app:prepareComFacebookFbuiTextlayoutbuilderTextlayoutbuilder100Library
:app:prepareComFacebookFrescoDrawee101Library
:app:prepareComFacebookFrescoFbcore101Library
:app:prepareComFacebookFrescoFresco101Library
:app:prepareComFacebookFrescoImagepipeline101Library
:app:prepareComFacebookFrescoImagepipelineBase101Library
:app:prepareComFacebookFrescoImagepipelineOkhttp3101Library
:app:prepareComFacebookReactReactNative0434Library
:app:prepareComFacebookSoloaderSoloader010Library
:app:prepareOrgWebkitAndroidJscR174650Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:mergeDebugShaders
:app:compileDebugShaders
:app:generateDebugAssets
:app:mergeDebugAssets
:app:generateDebugResValues
:app:generateDebugResources
:app:mergeDebugResources
:app:bundleDebugJsAndAssets SKIPPED
:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:incrementalDebugJavaCompilationSafeguard
:app:compileDebugJavaWithJavac
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources
:app:transformClassesWithDexForDebug
Running dex in-process requires build tools 23.0.2.
For faster builds update this project to use the latest build tools.
:app:mergeDebugJniLibFolders
:app:transformNative_libsWithMergeJniLibsForDebug
:app:processDebugJavaRes UP-TO-DATE
:app:transformResourcesWithMergeJavaResForDebug
:app:validateSigningDebug
:app:packageDebug
:app:assembleDebug
:app:installDebug
Installing APK 'app-debug.apk' on 'A16 - 4.2.2' for app:debug
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 7 mins 4.412 secs
'adb' is not recognized as an internal or external command,
operable program or batch file.
Starting the app (D:\Android\sdk/platform-tools/adb shell am start -n com.myfirstapp/.MainActivity...
Starting: Intent { cmp=com.myfirstapp/.MainActivity }

E:\ReactWorkSpace\MyFirstApp>

Am not using emulator, am using my own mobile device. App is launched in my device but all i see is a white blank screen. I followed all the instructions properly as mentioned in the official website.

Thank you.


来源: stackexchange

问:
ASP .NET Core Web Server console output not visible in VS for .NET Core 2.2
I created a .NET Core 2.2 web application project in VS 2017 and the ASP.NET Core Web Server option from the console output is not visible when the application runs with IIS Express.

By .NET Core 2.1 web application projects this option is there and it is showing the output without any problems.

答:
The simplest option is to change your currently selected debugger run option (the dropdown with the green "play" button / F5) from IIS, to the name of your project (e.g. so that "FooWebApp" shows up now in the dropdown). This way the browser will still open like it was before, but the console window will start showing as well.

On the other route with Tuvia's answer above (thanks!), it's actually Properties/launchSettings.json which stores / determines these actions. There you can also set "launchBrowser": false if wanted, or if you want to change if the console window opens, within "IIS Express" profile, manually add: "ancmHostingModel": "OutOfProcess" (or else set to InProcess).

ContentLicense: CC BY-SA 4.0


问:
Flowchart diagrams vs. UML activity diagrams
What is the practical difference between using flowchart diagrams and UML activity diagrams?
I have some thoughts, but maybe I'm missing an elephant in the room?

Flowchart diagram:

Widely used;

Easily understood by non-programmers;

Old?

UML Activity diagram:

Standardized;

Supports concurrency;

Less known syntax, but still simple enough.

For my case of ad-hoc documenting a particular block of application logic, I decided to go with the flowchart diagrams. More people in the company will be able to understand them.

答: UML in itself is used to share your understanding. Share the understanding in a standardized way. Since your case is ad hoc and the primary usage of an UML diagram is to provide an informal sketch, activity diagram can be used here. But so can flow charts as there are no parellism involved here. I have always found the following argument to be helpful. The artifct that i am producing is going to benefit whom? And can i express the flow in a self explanatory way using a flow chart. And if yes, then you should go ahead and use flow chart. But if your class diagrams, sequence etc are in UML format, it would make sense to have your activity diagrams in UML as well for consistency sake(The argument here would be, if people can understand class,sequence UML semantics, then y not activity diagrams.).</p>

ContentLicense: CC BY-SA 3.0


问:
Setting an element position according to another element (seems JS/CSS bug)
I have a div that will be set according to the hovered element position in window. At first I thought this was a JQuery bug, but after more investigating and changing to vanilla, it's still the same.

I have created a code snippet to demonstrate my problem. If you mouse enter white div from top, the position is correct and orange box cover entire white box, but if you enter it from other sides, it's incorrect by few pixel:

var inspector_rect2= document.getElementById('inspector_rect');

$(window).mouseover(function(event) {
  inspector_rect2.style.left= event.target.getBoundingClientRect().x+'px';
  inspector_rect2.style.top= event.target.getBoundingClientRect().y+'px';
  inspector_rect2.style.width= event.target.getBoundingClientRect().width+'px';
  inspector_rect2.style.height= event.target.getBoundingClientRect().height+'px';
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <meta charset="UTF-8">
</head>

<style>
  html, body  {
    height : 100%;
    margin : 0;
    width : 100%;
  }
  .MyCSS  {
    background-color : silver;
  }
  .Container  {
    height : 100%;
    margin : auto;
    width : 50%;
  }
  .Header {
    height : 5%;
    padding : 2% 0;
    width : 100%;
  }
  .MainContent {
    background-color : white;
    height : 70%;
    width: 100%;
  }
  .inspector{
    position: absolute;
    pointer-events: none;
    z-index: 999;
    background: rgba(255, 166, 0, 0.5);
  }
</style>

<body class="MyCSS">
  <div class="Container" >
    <div class="Header" ></div>
    <div class="MainContent"  ></div>
  </div>
</body>
<div id=inspector_rect class=inspector></div></code>```

答:
It seems to be caused by an interaction between requesting .getBoundingClientRect() and setting width and height.

Generally, you should just make one request, store it, then re-use as needed.

```<code>$(window).mouseover(function(event) {
  const rect = event.target.getBoundingClientRect();
  inspector_rect2.style.left= rect.x+'px';
  inspector_rect2.style.top= rect.y+'px';
  inspector_rect2.style.width= rect.width+'px';
  inspector_rect2.style.height= rect.height+'px';
});
</code>```

Body:
I have a div that will be set according to the hovered element position in window. At first I thought this was a JQuery bug, but after more investigating and changing to vanilla, it's still the same.

I have created a code snippet to demonstrate my problem. If you mouse enter white div from top, the position is correct and orange box cover entire white box, but if you enter it from other sides, it's incorrect by few pixel:

var inspector_rect2= document.getElementById('inspector_rect');

$(window).mouseover(function(event) {
  inspector_rect2.style.left= event.target.getBoundingClientRect().x+'px';
  inspector_rect2.style.top= event.target.getBoundingClientRect().y+'px';
  inspector_rect2.style.width= event.target.getBoundingClientRect().width+'px';
  inspector_rect2.style.height= event.target.getBoundingClientRect().height+'px';
});

<!DOCTYPE html>

    <title></title>
    <meta charset="UTF-8">

Body:
It seems to be caused by an interaction between requesting .getBoundingClientRect() and setting width and height.

Generally, you should just make one request, store it, then re-use as needed.

$(window).mouseover(function(event) {
  const rect = event.target.getBoundingClientRect();
  inspector_rect2.style.left= rect.x+'px';
  inspector_rect2.style.top= rect.y+'px';
  inspector_rect2.style.width= rect.width+'px';
  inspector_rect2.style.height= rect.height+'px';
});


问:
How to change the weight of a font that does not already have different weight variants?
For example, the font Secular One has only one regular variant, and I'd like to make it bold. I know it's possible in CSS for example, but I couldn't find a way to do it using Jetpack Compose. Is it even possible?</p>

答:
The behavior of fonts that lack some variants is controlled by FontSynthesis.

The default TextStyle.fontSynthesis is null, which resolved in FontSynthesis.All by default, which should synthesize all variants, including bold, so it should work out of the box.

```<code>val textStyle = TextStyle(
    fontFamily = FontFamily(
        Font(R.font.secular_one_regular)
    ),
    fontSynthesis = FontSynthesis.All
)
</code>```

Body:
The behavior of fonts that lack some variants is controlled by FontSynthesis.

The default TextStyle.fontSynthesis is null, which resolved in FontSynthesis.All by default, which should synthesize all variants, including bold, so it should work out of the box.

val textStyle = TextStyle(
    fontFamily = FontFamily(
        Font(R.font.secular_one_regular)
    ),
    fontSynthesis = FontSynthesis.All
)


问:
Remove input value on backspace keyup
I have a small canonical lottery search form comprising of 6 input fields. Currently when the user backspaces once, it will remove the value and move to the previous input field.

I need to split the above process into two steps. Therefore one backspace removes the value, the second backspace moves to previous input field and repeat.

How can I achieve this by adding to my current jquery if/else statement?

$(function() {
$("#target input").keyup(function(event) {
    if ($(this).val().length == 1) {
        $(this).nextAll('input').first().focus();
    } else if ($(this).val().length > 1) {
        var new_val = $(this).val().substring(1, 2);
        $(this).val(new_val);
        $(this).nextAll('input').first().focus();
    } else if (event.keyCode == 8) {
        if ($(this).prev('input')) {
            $(this).prev('input').focus();
        }
    }
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="target">
  <input type="number" id="keyword_1" maxlength="1" min="0" max="9" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_2" maxlength="1" min="0" max="9" name="keyword_2" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_3" maxlength="1" min="0" max="9" name="keyword_3" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_4" maxlength="1" min="0" max="9" name="keyword_4" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_5" maxlength="1" min="0" max="9" name="keyword_5" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_6" maxlength="1" min="0" max="9" name="keyword_6" style="width: 35px !important; etter-spacing: 1.5px;">
  <button class="btn btn-info" id="search-ticket" type="submit">Search</button>
</form></code>```

答:
I will do something like that:

some usefull information about key values

const
  myForm     = document.querySelector('#my-form')
, valid_Keys = [ ...'0123456789', 'Backspace', 'ArrowLeft', 'ArrowRight' ]
, ignoreKeys = [ 'ArrowUp', 'ArrowDown', 'Tab' ]
  ;
myForm.keyword_1.focus() // on page load

document.onkeydown = e =>
  {
  if ( !e.target.matches('#my-form input[type=number]')
    || ignoreKeys.includes(e.key)
    ) return

  e.preventDefault()  // disable key action (letters or what else?

  if (!valid_Keys.includes(e.key) ) return

  let cInput = +e.target.name.replace(/\D+/g, '') // get numeric value from name ( 1...6 )

  if ( e.key==='Backspace')
    if (e.target.value !== '' )    e.target.value = ''
    else                           cInput--
  else if (e.key === 'ArrowRight') cInput++
  else if (e.key === 'ArrowLeft')  cInput--
  else                             myForm[`keyword_${cInput++}`].value = e.key

  if (cInput<1) cInput = 1
  if (cInput>6) cInput = 6
  myForm[`keyword_${cInput}`].focus()
  }

myForm.onsubmit = e =>  // for testing
  {
  e.preventDefault()
  let values = Object.fromEntries( new FormData(myForm).entries() )
  console.clear()
  console.log( JSON.stringify(values))
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#my-form input[type=number] {
  width          : 35px;
  letter-spacing : 1.5px;
  }</code>```

<form id="my-form">
  <input type="number" min="0" max="9" name="keyword_1" value="">
  <input type="number" min="0" max="9" name="keyword_2" value="">
  <input type="number" min="0" max="9" name="keyword_3" value="">
  <input type="number" min="0" max="9" name="keyword_4" value="">
  <input type="number" min="0" max="9" name="keyword_5" value="">
  <input type="number" min="0" max="9" name="keyword_6" value="">
  <button class="btn btn-info" type="submit" > Search </button>
</form>```

Title: Remove input value on backspace keyup

Body:
I have a small canonical lottery search form comprising of 6 input fields. Currently when the user backspaces once, it will remove the value and move to the previous input field.

I need to split the above process into two steps. Therefore one backspace removes the value, the second backspace moves to previous input field and repeat.

How can I achieve this by adding to my current jquery if/else statement?

$(function() {
$("#target input").keyup(function(event) {
    if ($(this).val().length == 1) {
        $(this).nextAll('input').first().focus();
    } else if ($(this).val().length > 1) {
        var new_val = $(this).val().substring(1, 2);
        $(this).val(new_val);
        $(this).nextAll('input').first().focus();
    } else if (event.keyCode == 8) {
        if ($(this).prev('input')) {
            $(this).prev('input').focus();
        }
    }
});
});

<form id="target">
  <input type="number" id="keyword_1" maxlength="1" min="0" max="9" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_2" maxlength="1" min="0" max="9" name="keyword_2" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_3" maxlength="1" min="0" max="9" name="keyword_3" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_4" maxlength="1" min="0" max="9" name="keyword_4" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_5" maxlength="1" min="0" max="9" name="keyword_5" style="width: 35px !important; etter-spacing: 1.5px;">
  <input type="number" id="keyword_6" maxlength="1" min="0" max="9" name="keyword_6" style="width: 35px !important; etter-spacing: 1.5px;">
  <button class="btn btn-info" id="search-ticket" type="submit">Search</button>
</form>

Body:
I will do something like that:

some usefull information about key values

const
  myForm     = document.querySelector('#my-form')
, valid_Keys = [ ...'0123456789', 'Backspace', 'ArrowLeft', 'ArrowRight' ]
, ignoreKeys = [ 'ArrowUp', 'ArrowDown', 'Tab' ]
  ;
myForm.keyword_1.focus() // on page load

document.onkeydown = e =>
  {
  if ( !e.target.matches('#my-form input[type=number]')
    || ignoreKeys.includes(e.key)
    ) return

  e.preventDefault()  // disable key action (letters or what else?

  if (!valid_Keys.includes(e.key) ) return

  let cInput = +e.target.name.replace(/\D+/g, '') // get numeric value from name ( 1...6 )

  if ( e.key==='Backspace')
    if (e.target.value !== '' )    e.target.value = ''
    else                           cInput--
  else if (e.key === 'ArrowRight') cInput++
  else if (e.key === 'ArrowLeft')  cInput--
  else                             myForm[`keyword_${cInput++}`].value = e.key

  if (cInput<1) cInput = 1
  if (cInput>6) cInput = 6
  myForm[`keyword_${cInput}`].focus()
  }

myForm.onsubmit = e =>  // for testing
  {
  e.preventDefault()
  let values = Object.fromEntries( new FormData(myForm).entries() )
  console.clear()
  console.log( JSON.stringify(values))
  }

#my-form input[type=number] {
  width          : 35px;
  letter-spacing : 1.5px;
  }

<form id="my-form">
  <input type="number" min="0" max="9" name="keyword_1" value="">
  <input type="number" min="0" max="9" name="keyword_2" value="">
  <input type="number" min="0" max="9" name="keyword_3" value="">
  <input type="number" min="0" max="9" name="keyword_4" value="">
  <input type="number" min="0" max="9" name="keyword_5" value="">
  <input type="number" min="0" max="9" name="keyword_6" value="">
  <button class="btn btn-info" type="submit" > Search </button>
</form>


问:
AVPlayer / AVAudioPlayer - Play audio fileURL from iCloud Drive (work on simulator but not iPhone) + (OSStatus error -54.)
I'm making Audio Player.
Importing file from iCloud Drive using .fileImporter.

I get file URL that looks like this: file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/_Storage/Audio-books/%D0%91%D1%80%D0%B5%D0%BD%D0%B4%D1%8F%D1%82%D0%B8%D0%BD%D0%B0/Audiobook.mp3"

Then I pass it to audio player (tried AVPlayer and AVAudioPlayer). Both works on iOS simulator.
On the device after import I get error: The operation couldn’t be completed. (OSStatus error -54.)

I know it's possible, app called Evermusic does quite the same with on device files.

Is there permissions I need to be granted to play audio that stored on device?

How can I access Container for com~apple~CloudDocs?

Thank you very much for help, any suggestions greatly appreciated, I'm seriously stuck.
For future references repo of the project: https://github.com/yaosamo/AudioPlayer

答:
In addition to @jnpdx answer want to add some details, and my solution example.

Few core things

✅ for my app if you need to access secured audio you need to use startAccessingSecurityScopedResource()

❌ you can't simple store URL and use it later, in fact you don't store fileURL at all. You need to use what's called bookmarkData() on your URL and store it. So later you can restore URL

✅ Watch Apple pres here

Here's how I import file:

```<code>        .fileImporter(isPresented: $presentImporter, allowedContentTypes: [.mp3]) { result in
        switch result {
        case .success(let url):
            // Start accessing secured url
            let StartAccess = url.startAccessingSecurityScopedResource()
            defer {
                // Must stop accessing once stop using
                if StartAccess {
                    url.stopAccessingSecurityScopedResource()
                }
            }
            // Creating new book
            let newBook = Book(context: viewContext)
            let _ = print("---- Access Granted?", url.startAccessingSecurityScopedResource())
            // Getting bookmarkData of the URL
            let bookmarkData = try? url.bookmarkData()
            newBook.name = "\(url.lastPathComponent)"
            // Save bookmarkURL into CoreData
            newBook.urldata = bookmarkData
            // Specifiying parent item in CoreData
            newBook.origin = playlist.self
            try? viewContext.save()

        case .failure(let error):
            print(error)
        }
    }
</code>```

Player retrieving URL:

```<code>func Audioplayer(bookmarkData: Data) {

// Restore security scoped bookmark
var bookmarkDataIsStale = false
let playNow = try? URL(resolvingBookmarkData: bookmarkData, bookmarkDataIsStale: &bookmarkDataIsStale)

do {
    player = try AVAudioPlayer(contentsOf: playNow!)
    // Delegate listen when audio is finished
    player?.delegate = del
    NotificationCenter.default.addObserver(forName: NSNotification.Name("ended"), object: nil, queue: .main) { (_) in
        player?.stop()
        ended = true
        let _ = print("---- Book has ended ----")
    }
} catch let error {
    print("Player Error", error.localizedDescription)
}
player?.prepareToPlay()
player?.play()
}
</code>```

Thank you and again here's repo on git.

Body:
In addition to @jnpdx answer want to add some details, and my solution example.

Few core things

✅ for my app if you need to access secured audio you need to use startAccessingSecurityScopedResource()

❌ you can't simple store URL and use it later, in fact you don't store fileURL at all. You need to use what's called bookmarkData() on your URL and store it. So later you can restore URL

✅ Watch Apple pres here

Here's how I import file:

        .fileImporter(isPresented: $presentImporter, allowedContentTypes: [.mp3]) { result in
        switch result {
        case .success(let url):
            // Start accessing secured url
            let StartAccess = url.startAccessingSecurityScopedResource()
            defer {
                // Must stop accessing once stop using
                if StartAccess {
                    url.stopAccessingSecurityScopedResource()
                }
            }
            // Creating new book
            let newBook = Book(context: viewContext)
            let _ = print("---- Access Granted?", url.startAccessingSecurityScopedResource())
            // Getting bookmarkData of the URL
            let bookmarkData = try? url.bookmarkData()
            newBook.name = "\(url.lastPathComponent)"
            // Save bookmarkURL into CoreData
            newBook.urldata = bookmarkData
            // Specifiying parent item in CoreData
            newBook.origin = playlist.self
            try? viewContext.save()

        case .failure(let error):
            print(error)
        }
    }

Player retrieving URL:

func Audioplayer(bookmarkData: Data) {

// Restore security scoped bookmark
var bookmarkDataIsStale = false
let playNow = try? URL(resolvingBookmarkData: bookmarkData, bookmarkDataIsStale: &bookmarkDataIsStale)

do {
    player = try AVAudioPlayer(contentsOf: playNow!)
    // Delegate listen when audio is finished
    player?.delegate = del
    NotificationCenter.default.addObserver(forName: NSNotification.Name("ended"), object: nil, queue: .main) { (_) in
        player?.stop()
        ended = true
        let _ = print("---- Book has ended ----")
    }
} catch let error {
    print("Player Error", error.localizedDescription)
}
player?.prepareToPlay()
player?.play()
}

Thank you and again here's repo on git.


问:
Front end web-development: good resources
I am about to move to a job where I will be doing front end web development (mainly CSS and jQuery).

What are good resources (books, websites, blogs etc.) for learning more about those technologies in particular and anything front-end web development related (good technologies to know, user interface ideas etc.) in general?

Thank you!

ETA: Just to give some idea of where I'm holding, I have about 1.5 years of experience in web development. So I already have a pretty good grasp of CSS and know the basics of jQuery. I also know a fair amount about user interface design.

答:
www.csszengarden.com and the matching book were good resources for me with the CSS side.
You might also take a look at www.jquerymobile.com if you think the work you'll be doing might also benefit from a tablet/smartphone finger-friendly interface version.

Greg


问:
Parse a json data out from a tag
The text below is part of a string I parsed from html (pre). Since I can not place tags <> in this box I have replace the beginning and end tags as (pre) (/pre).

```<code>(pre)(b)Below are the details for server SomeServerName from NetSystem.(Data Length - 1)(/b)
[
    {
        "askId": "Value1",
        "billingCode": "99999999",
        "clusterId": null,
        "createdBy": "Mike",
        "createdFromLegacy": null,
        "createdOn": "2021-08-06T17:54:28.220Z",
        "description": "Windows 2019",
        "environment": "devops",
        "hostId": null,
        "id": "acd16582-b009-4667-aa95-5977603772sa",
        "infrastructure": {
            "apiId": "App2019_SA_1_v8-w2019_mike3_cc8f7e02-d426-423d-addb-b29bc7e163be",
            "capacityId": "ODI",
            "catalogManagementGroup": "Sales Marketing"
        },
        "legacyId": "XL143036181",
        "location": {
            "availabilityZone": "ny",
            "code": "mx31",
            "description": "uhg : mn053",
            "region": "west",
            "vendor": "apple"
        },
        "maintenance": {
            "group": "3",
            "status": "steady_state",
            "window": {
                "days": "Sunday",
                "endTime": "06:00:00.000Z",
                "startTime": "02:00:00.000Z"
            }
        },
        "name": "SomeServer",
        "network": {
            "fqdn": "SomeServer.dom.tes.contoso.com",
            "ipAddress": "xx.xx.xx.xx"
        },
        "os": {
            "description": "Microsoft windows 2019",
            "type": "windows",
            "vendor": "Microsoft",
            "version": "2019"
        },
        "owner": {
            "id": "000111111",
            "msid": "jtest"
        },
        "provision": {
            "id": "ba424e42-a925-49a5-a4b7-5dcf41b69d4e",
            "requestingApi": "mars Hub",
            "system": "vRealize"
        },
        "specs": {
            "cpuCount": 4,
            "description": "Virtual Hardware",
            "ram": 64384,
            "serialNumber": null
        },
        "status": "ACTIVE",
        "support": {
            "group": "Support group"
        },
        "tags": {
            "appTag": "minitab"
        },
        "updatedBy": "snir_agent",
        "updatedOn": "2021-08-06T17:54:31.525Z"
    }
](/pre)
</code>```

As you can see this is almost json data but I can not parse it as such because of the (b) (/b) tag that exists inside my (pre) (/pre) tag. How can I parse out this (b) tag with its content so I am left with the json data and can treat it as such enabling me to more easily select values with json functions.

答:
If your JSON always has [] brackets you can extract the content inside it and then parse it:

Python example:

import re
import json

text = 'asd[{"a": "b", "c": "d"}] pre' # your content

json_content = re.findall('\[[^\]]*\]', text)[0] # '[{"a": "b", "c": "d"}]'
result = json.loads(json_content) # [{'a': 'b', 'c': 'd'}]
```

Title: Parse a json data out from a tag

Body:
The text below is part of a string I parsed from html (pre). Since I can not place tags <> in this box I have replace the beginning and end tags as (pre) (/pre).

(pre)(b)Below are the details for server SomeServerName from NetSystem.(Data Length - 1)(/b)
[
    {
        "askId": "Value1",
        "billingCode": "99999999",
        "clusterId": null,
        "createdBy": "Mike",
        "createdFromLegacy": null,
        "createdOn": "2021-08-06T17:54:28.220Z",
        "description": "Windows 2019",
        "environment": "devops",
        "hostId": null,
        "id": "acd16582-b009-4667-aa95-5977603772sa",
        "infrastructure": {
            "apiId": "App2019_SA_1_v8-w2019_mike3_cc8f7e02-d426-423d-addb-b29bc7e163be",
            "capacityId": "ODI",
            "catalogManagementGroup": "Sales Marketing"
        },
        "legacyId": "XL143036181",
        "location": {
            "availabilityZone": "ny",
            "code": "mx31",
            "description": "uhg : mn053",
            "region": "west",
            "vendor": "apple"
        },
        "maintenance": {
            "group": "3",
            "status": "steady_state",
            "window": {
                "days": "Sunday",
                "endTime": "06:00:00.000Z",
                "startTime": "02:00:00.000Z"
            }
        },
        "name": "SomeServer",
        "network": {
            "fqdn": "SomeServer.dom.tes.contoso.com",
            "ipAddress": "xx.xx.xx.xx"
        },
        "os": {
            "description": "Microsoft windows 2019",
            "type": "windows",
            "vendor": "Microsoft",
            "version": "2019"
        },
        "owner": {
            "id": "000111111",
            "msid": "jtest"
        },
        "provision": {
            "id": "ba424e42-a925-49a5-a4b7-5dcf41b69d4e",
            "requestingApi": "mars Hub",
            "system": "vRealize"
        },
        "specs": {
            "cpuCount": 4,
            "description": "Virtual Hardware",
            "ram": 64384,
            "serialNumber": null
        },
        "status": "ACTIVE",
        "support": {
            "group": "Support group"
        },
        "tags": {
            "appTag": "minitab"
        },
        "updatedBy": "snir_agent",
        "updatedOn": "2021-08-06T17:54:31.525Z"
    }
](/pre)

As you can see this is almost json data but I can not parse it as such because of the (b) (/b) tag that exists inside my (pre) (/pre) tag. How can I parse out this (b) tag with its content so I am left with the json data and can treat it as such enabling me to more easily select values with json functions.

Body:
If your JSON always has [] brackets you can extract the content inside it and then parse it:

Python example:

import re
import json

text = '<b>asd</b>[{"a": "b", "c": "d"}] pre' # your content

json_content = re.findall('\[[^\]]*\]', text)[0] # '[{"a": "b", "c": "d"}]'
result = json.loads(json_content) # [{'a': 'b', 'c': 'd'}]


问:
How to compress pandas dataframe
Below I am showing few entries of my dataframe. My (each) dataframe has millions row.

```<code>import pandas as pd
data = [{'stamp':'12/31/2020 9:35:42 AM', 'value': 21.99, 'trigger': True},
        {'stamp':'12/31/2020 10:35:42 AM', 'value': 22.443, 'trigger': False},
        {'stamp':'12/31/2020 11:35:42 AM', 'value': 19.00, 'trigger': False},
        {'stamp':'12/31/2020 9:45:42 AM', 'value': 45.02, 'trigger': False},
        {'stamp':'12/31/2020 9:55:42 AM', 'value': 48, 'trigger': False},
        {'stamp':'12/31/2020 11:35:42 AM', 'value': 48.99, 'trigger': False}]
df = pd.DataFrame(data)
</code>```

Below is how few ways I can save:

```<code>df.to_parquet('df.parquet', compression = 'gzip')

df.to_csv('df.csv')
</code>```

I don't see much improvement in to_parquet as compared to to_csv. I wish to minimize the file size on hard drive. is there any way out?

答:
parquet gives you compression over a column when that columns (e.g.) has many continuous sequences of the same value. (See wiki for more) From your example data only trigger shows a sign of that, but the improvement may not be large because it was not the one taking up most space in the first place.

Saving integer is cheaper than saving a long string, so you may consider to change your stamp from str into timestamp value which is int, by doing this

```<code>df['stamp'] = pd.to_datetime(df['stamp']).values.astype(np.int64) // 10**9
</code>```

We divide it by 10**9 because your stamp appears to be precise to the level of second only, instead of nanosecond which is the default.

but you will need to convert it back to the readable str form the next time you read the saved data, by

```<code>df['stamp'] = pd.to_datetime(df['stamp'] * 10**9)
</code>```

Title: How to compress pandas dataframe

Body:
Below I am showing few entries of my dataframe. My (each) dataframe has millions row.

import pandas as pd
data = [{'stamp':'12/31/2020 9:35:42 AM', 'value': 21.99, 'trigger': True},
        {'stamp':'12/31/2020 10:35:42 AM', 'value': 22.443, 'trigger': False},
        {'stamp':'12/31/2020 11:35:42 AM', 'value': 19.00, 'trigger': False},
        {'stamp':'12/31/2020 9:45:42 AM', 'value': 45.02, 'trigger': False},
        {'stamp':'12/31/2020 9:55:42 AM', 'value': 48, 'trigger': False},
        {'stamp':'12/31/2020 11:35:42 AM', 'value': 48.99, 'trigger': False}]
df = pd.DataFrame(data)

Below is how few ways I can save:

df.to_parquet('df.parquet', compression = 'gzip')

df.to_csv('df.csv')

I don't see much improvement in to_parquet as compared to to_csv. I wish to minimize the file size on hard drive. is there any way out?

Body:
parquet gives you compression over a column when that columns (e.g.) has many continuous sequences of the same value. (See wiki for more) From your example data only trigger shows a sign of that, but the improvement may not be large because it was not the one taking up most space in the first place.

Saving integer is cheaper than saving a long string, so you may consider to change your stamp from str into timestamp value which is int, by doing this

df['stamp'] = pd.to_datetime(df['stamp']).values.astype(np.int64) // 10**9

We divide it by 10**9 because your stamp appears to be precise to the level of second only, instead of nanosecond which is the default.

but you will need to convert it back to the readable str form the next time you read the saved data, by

df['stamp'] = pd.to_datetime(df['stamp'] * 10**9)


问:
How to center ElevatedButton in flutter?
I imported [sliding up panel][2] from pub.dev and everything is good except for one issue. I'm looking for a way to center the 'blue circle' vertically. (in between 'red appbar' and 'buttom slider') I tried wraping the code with 'center' or using mainaxisalignment but it doesn't work. Other things I tried which I found on google just gave me an errors. Please help.
Thanks in advance

```<code>return Scaffold(
  appBar: PreferredSize(
    preferredSize: Size.fromHeight(200),
    child: AppBar(
      backgroundColor: Colors.pinkAccent,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(100))
      ),
      flexibleSpace: Container(
        alignment: Alignment.center,
        child: Text(
          'Red AppBar',
          style: TextStyle(
              color: Colors.white,
              fontSize: 50.0,
              fontWeight: FontWeight.bold
          ),
        ),
      ),
    ),
  ),
  body: SlidingUpPanel(
    renderPanelSheet: false,
    panel: _floatingPanel(),
    collapsed: _floatingCollapsed(),
    body: ElevatedButton(
      onPressed: () {},
      child: Text('Blue Circle'),
      style: ElevatedButton.styleFrom(
        shape: CircleBorder(),
        padding: EdgeInsets.all(20),
      ),
    )
  ),
);

  Widget _floatingCollapsed() {
return Container(
  decoration: BoxDecoration(
    color: Colors.blueGrey,
    borderRadius: BorderRadius.only(
        topLeft: Radius.circular(24.0), topRight: Radius.circular(24.0)),
  ),
  margin: const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),
  child: Center(
    child: Text(
      "buttom slider",
      style: TextStyle(color: Colors.white),
    ),
  ),
);
</code>```

}

```<code>  Widget _floatingPanel() {
return Container(
  decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.all(Radius.circular(24.0)),
      boxShadow: [
        BoxShadow(
          blurRadius: 20.0,
          color: Colors.grey,
        ),
      ]
  ),
  margin: const EdgeInsets.all(24.0),
  child: Center(
    child: Text("LEVEL INFO"),
  ),
);
</code>```

}

Also, what could be the best way to give margin to the 'blue circle' so it won't touch the far left and far right side of the screen?

答:
The SlidingUpPanel's body is using Stack, also getting full screen size. You can check

@override
Widget build(BuildContext context) {
  return Stack(
    alignment: widget.slideDirection == SlideDirection.UP
        ? Alignment.bottomCenter
        : Alignment.topCenter,
    children: <Widget>[
      //make the back widget take up the entire back side
      widget.body != null
          ? AnimatedBuilder(
              animation: _ac,
              builder: (context, child) {
                return Positioned(
                  top: widget.parallaxEnabled ? _getParallax() : 0.0,
                  child: child ?? SizedBox(),
                );
              },
              child: Container(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                child: widget.body,
              ),
            )
```
<p>You can play with <code>Align</code> on <code>body</code> and wrapping with <code>SizedBox</code>. You can use <code>LayoutBuilder</code> or <code>MediaQuery</code> to provide size.</p>
<pre class="lang-dart prettyprint-override"><code>body: SlidingUpPanel(
    renderPanelSheet: false,
    panel: _floatingPanel(),
    collapsed: _floatingCollapsed(),
    body: Align(
      alignment: Alignment(0.0, -.3), //play with it
      child: SizedBox(
        width: 200,
        height: 200,
        child: ElevatedButton(
</code>```

Body:
I imported [sliding up panel][2] from pub.dev and everything is good except for one issue. I'm looking for a way to center the 'blue circle' vertically. (in between 'red appbar' and 'buttom slider') I tried wraping the code with 'center' or using mainaxisalignment but it doesn't work. Other things I tried which I found on google just gave me an errors. Please help.
Thanks in advance

return Scaffold(
  appBar: PreferredSize(
    preferredSize: Size.fromHeight(200),
    child: AppBar(
      backgroundColor: Colors.pinkAccent,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(100))
      ),
      flexibleSpace: Container(
        alignment: Alignment.center,
        child: Text(
          'Red AppBar',
          style: TextStyle(
              color: Colors.white,
              fontSize: 50.0,
              fontWeight: FontWeight.bold
          ),
        ),
      ),
    ),
  ),
  body: SlidingUpPanel(
    renderPanelSheet: false,
    panel: _floatingPanel(),
    collapsed: _floatingCollapsed(),
    body: ElevatedButton(
      onPressed: () {},
      child: Text('Blue Circle'),
      style: ElevatedButton.styleFrom(
        shape: CircleBorder(),
        padding: EdgeInsets.all(20),
      ),
    )
  ),
);

  Widget _floatingCollapsed() {
return Container(
  decoration: BoxDecoration(
    color: Colors.blueGrey,
    borderRadius: BorderRadius.only(
        topLeft: Radius.circular(24.0), topRight: Radius.circular(24.0)),
  ),
  margin: const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),
  child: Center(
    child: Text(
      "buttom slider",
      style: TextStyle(color: Colors.white),
    ),
  ),
);

}

  Widget _floatingPanel() {
return Container(
  decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.all(Radius.circular(24.0)),
      boxShadow: [
        BoxShadow(
          blurRadius: 20.0,
          color: Colors.grey,
        ),
      ]
  ),
  margin: const EdgeInsets.all(24.0),
  child: Center(
    child: Text("LEVEL INFO"),
  ),
);

}

Also, what could be the best way to give margin to the 'blue circle' so it won't touch the far left and far right side of the screen?

Body:
The SlidingUpPanel's body is using Stack, also getting full screen size. You can check

@override
Widget build(BuildContext context) {
  return Stack(
    alignment: widget.slideDirection == SlideDirection.UP
        ? Alignment.bottomCenter
        : Alignment.topCenter,
    children: <Widget>[
      //make the back widget take up the entire back side
      widget.body != null
          ? AnimatedBuilder(
              animation: _ac,
              builder: (context, child) {
                return Positioned(
                  top: widget.parallaxEnabled ? _getParallax() : 0.0,
                  child: child ?? SizedBox(),
                );
              },
              child: Container(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                child: widget.body,
              ),
            )

You can play with Align on body and wrapping with SizedBox. You can use LayoutBuilder or MediaQuery to provide size.

body: SlidingUpPanel(
    renderPanelSheet: false,
    panel: _floatingPanel(),
    collapsed: _floatingCollapsed(),
    body: Align(
      alignment: Alignment(0.0, -.3), //play with it
      child: SizedBox(
        width: 200,
        height: 200,
        child: ElevatedButton(


问:
BigQuery - Grouping by date with a WHERE clause
My goal is to search for certain products, count the total per certain product, and group each by day.

Schema is like so:

line_items.sku
created_at

product1
2020-04-02T13:22:44

product2
2020-04-02T05:01:22

product2
2020-04-03T14:21:10

My query is below:

SELECT
  EXTRACT(DAY
  FROM
    CAST(`order`.created_at AS DATETIME)) AS day_extracted,
  EXTRACT(MONTH
  FROM
    CAST(`order`.created_at AS DATETIME)) AS month_extracted,
  `order`.line_items.sku AS sku
FROM
  `mydatabase`
WHERE
  `order`.line_items.sku = "product 1"
  OR `order`.line_items.sku = "product 2"
```
<p>The data is below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>row</th>
<th>day_extracted</th>
<th>month_extracted</th>
<th>sku</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>5</td>
<td>2</td>
<td>product1</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>1</td>
<td>product2</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>1</td>
<td>product1</td>
</tr>
</tbody>
</table>
</div>
<p>This is great and works, but I'm running into issues with needing to grouping the products and count <strong>per product</strong> total per day.</p>
<p>What am I doing wrong? If I add</p>
<pre class="lang-sql prettyprint-override"><code>  GROUP BY month_extracted, day_extracted
</code>```

to the query, another error comes up

```<code>SELECT list expression references `order`.line_items which is neither grouped nor aggregated at [8:3]
</code>```

Line 8 is:

 `order`.line_items.sku AS sku

答:
The order in which a general SQL query is evaluated is this

Which means the group by clause doesn't even know what is month_extracted, day_extracted. So in order to fix this, either put the whole exp EXTRACT(.. in Group by OR. Use a subquery. And also there is a rule, that anything in SELECT which is not part of  GROUP BY should be applied an AGGREGATE function. In your it is not hence an error.

select
       day_extracted,
       month_extracted,
       any_value(sku) AS sku -- i used any_value to fix it, you can use any other agg. function as per your logic
 from (
SELECT
  EXTRACT(DAY
  FROM
    CAST(`order`.created_at AS DATETIME)) AS day_extracted,
  EXTRACT(MONTH
  FROM
    CAST(`order`.created_at AS DATETIME)) AS month_extracted,
    `order`.line_items.sku as Sku

FROM
  `mydatabase`
WHERE
  `order`.line_items.sku = "product 1"
  OR `order`.line_items.sku = "product 2"
) as _table
group by day_extracted,month_extracted
```

Body:
My goal is to search for certain products, count the total per certain product, and group each by day.

Schema is like so:

line_items.sku
created_at

product1
2020-04-02T13:22:44

product2
2020-04-02T05:01:22

product2
2020-04-03T14:21:10

My query is below:

SELECT
  EXTRACT(DAY
  FROM
    CAST(`order`.created_at AS DATETIME)) AS day_extracted,
  EXTRACT(MONTH
  FROM
    CAST(`order`.created_at AS DATETIME)) AS month_extracted,
  `order`.line_items.sku AS sku
FROM
  `mydatabase`
WHERE
  `order`.line_items.sku = "product 1"
  OR `order`.line_items.sku = "product 2"

The data is below:

row
day_extracted
month_extracted
sku

1
5
2
product1

2
4
1
product2

2
4
1
product1

This is great and works, but I'm running into issues with needing to grouping the products and count per product total per day.

What am I doing wrong? If I add

  GROUP BY month_extracted, day_extracted

to the query, another error comes up

SELECT list expression references `order`.line_items which is neither grouped nor aggregated at [8:3]

Line 8 is:

 `order`.line_items.sku AS sku


问:
Test Driven Development for ASP.NET MVC 3 - Parsing XML source file
Hi would like to reach out to the community to gain insight and advice
on the approach to Test-Driven Development for the work I'm carrying out.

I am working on a ASP.NET MVC3 project that parses in a physical XML file (containing chart and table data).
First the app generates a model representation of the xml nodes.
The controller is there to carriy out the application logic,

that ultimately renders to a specific HTML view with charts and tables.

I am thinking that I will be building a model that represents the xml ie classes like dataset,header,dimension etc with
appropriate interfaces. Is this the right approach. (Please see below the sample xml)

What sort of units tests would I write?
Would I start with unit tests that access the physical XML files (probably not)?
Should I stream fragmetns of xml strings into an Xdocument? (isn't that teting .net code?)
Presuming I don't want to create concrete XDocument classes, how do I mock out the object eg

First test I want to do (I think) is to load the xml and test the end_Date is correct

I have a XMLHelper Class that loads the xml and returns a class representation of a header with property end date.

So my concrete code would look something roughly like

```<code>var dataset = XmlHelper.Load(filePathOrXmlStream);
var header=dataset.Header;

Assert.AreEqual("5/06/2011",header.EndDate);
</code>```

presume that the below XML is used for the stream or file load.

XML Source

```<code><dataset>
  <header>
    <end_date>5/06/2011</end_date>
    <dimension id="mkt" desc="market">
      <item mkt="0" desc="Company A" />
      <item mkt="1" desc="Company B" />
    </dimension>
    <dimension id="prd" desc="product">
      <item prd="0" desc="Product A " Groups_Total="Segment Totals" Total="Yes" Product="All" grp="Category" />
    </dimension>
    <dimension id="msr" desc="measure">
      <item msr="0" tag="ACTIVE_1" desc="Active Products" />
    </dimension>
    <dimension id="tim" desc="time">
      <item tim="0" tag="LAST WEEK -52" desc="06/06/10 " />
      <item tim="1" tag="LAST WEEK -26" desc="05/12/10 " />
      <item tim="2" tag="LAST WEEK 0" desc="05/06/11 " />
    </dimension>
  </header>
  <data>
    <dpGroup tim="0">
      <dp mkt="0" prd="0" msr="0" tim="0">1031</dp>
      <dp mkt="1" prd="0" msr="0" tim="0">986</dp>
    </dpGroup>
    <dpGroup tim="1">
      <dp mkt="0" prd="0" msr="0" tim="1">970</dp>
      <dp mkt="1" prd="0" msr="0" tim="1">937</dp>
    </dpGroup>
    <dpGroup tim="2">
      <dp mkt="0" prd="0" msr="0" tim="2">982</dp>
      <dp mkt="1" prd="0" msr="0" tim="2">955</dp>
    </dpGroup>
  </data>
</dataset>
</code>```

答:
I think you are approaching the problem properly. There are really 2 separate steps in your process:

1) transform the XML document into a class representation, a Model

2) render a Model to a View

The part where TDD should work well is step 2, because you are dealing with objects. You can then follow the path outlined by Taesung Shin. You can define what the interface for your object is if needed, and have a IChartModel with, say, a StartDate property, which you can then Mock, set the StartDate to whatever you want, and write assertions about what should be true of the View in that case. As Taesung said, this will help you drive your design.

The part where TDD will not work that well is in step 1. Unit tests shine when you can entirely work in memory, and by definition a file on disk does not work well in that context. What I would do then, if you thought it was worthwhile the effort, would be to have sample files, and test your XmlReader against these files, to make sure that you are reading what you should, and properly populating the inputs for step 2. These will not be "proper" unit tests, but more integration tests. I would tend to create a "happy file", with proper inputs, and possibly files for potentially malformed cases. As you encounter bugs over time, you can start adding new files. These tests wouldn't be fun to write, though.

If you are going to create that XML file in your application, you may consider having tests where you create these files and read them back, which might give you more "code control" over what is going on, as opposed to having to maintain fixed files over time, if your design evolves.

The biggest benefit you would get in separating this, in my opinion, is that by separating how you want the data to be structured and used in your MVC app, from how to get that data from an XML file, is that you will have the benefit of a separation in 2 different layers, and if you happen to either decide to pull that data from SQL, or to change the structure of your XML file over time, you will have solid decoupling between data access, and data utilization. You will have a domain model (what a chart should be), and can then plug various data sources to it.

Body:
Hi would like to reach out to the community to gain insight and advice
on the approach to Test-Driven Development for the work I'm carrying out.

I am working on a ASP.NET MVC3 project that parses in a physical XML file (containing chart and table data).
First the app generates a model representation of the xml nodes.
The controller is there to carriy out the application logic,

that ultimately renders to a specific HTML view with charts and tables.

I am thinking that I will be building a model that represents the xml ie classes like dataset,header,dimension etc with
appropriate interfaces. Is this the right approach. (Please see below the sample xml)

What sort of units tests would I write?
Would I start with unit tests that access the physical XML files (probably not)?
Should I stream fragmetns of xml strings into an Xdocument? (isn't that teting .net code?)
Presuming I don't want to create concrete XDocument classes, how do I mock out the object eg

First test I want to do (I think) is to load the xml and test the end_Date is correct

I have a XMLHelper Class that loads the xml and returns a class representation of a header with property end date.

So my concrete code would look something roughly like

var dataset = XmlHelper.Load(filePathOrXmlStream);
var header=dataset.Header;

Assert.AreEqual("5/06/2011",header.EndDate);

presume that the below XML is used for the stream or file load.

XML Source

<dataset>

    <end_date>5/06/2011</end_date>
    <dimension id="mkt" desc="market">
      <item mkt="0" desc="Company A" />
      <item mkt="1" desc="Company B" />
    </dimension>
    <dimension id="prd" desc="product">
      <item prd="0" desc="Product A " Groups_Total="Segment Totals" Total="Yes" Product="All" grp="Category" />
    </dimension>
    <dimension id="msr" desc="measure">
      <item msr="0" tag="ACTIVE_1" desc="Active Products" />
    </dimension>
    <dimension id="tim" desc="time">
      <item tim="0" tag="LAST WEEK -52" desc="06/06/10 " />
      <item tim="1" tag="LAST WEEK -26" desc="05/12/10 " />
      <item tim="2" tag="LAST WEEK 0" desc="05/06/11 " />
    </dimension>

  <data>
    <dpGroup tim="0">
      <dp mkt="0" prd="0" msr="0" tim="0">1031</dp>
      <dp mkt="1" prd="0" msr="0" tim="0">986</dp>
    </dpGroup>
    <dpGroup tim="1">
      <dp mkt="0" prd="0" msr="0" tim="1">970</dp>
      <dp mkt="1" prd="0" msr="0" tim="1">937</dp>
    </dpGroup>
    <dpGroup tim="2">
      <dp mkt="0" prd="0" msr="0" tim="2">982</dp>
      <dp mkt="1" prd="0" msr="0" tim="2">955</dp>
    </dpGroup>
  </data>
</dataset>


问:
Adding non table based DbSet causes error
I have the following DbContext in a .net5 winforms EF XAF 21.2.5  standard security application created with the wizard and it runs OK.

```<code>[TypesInfoInitializer(typeof(DXApplication42ContextInitializer))]
public class DXApplication42EFCoreDbContext : DbContext {
    public DXApplication42EFCoreDbContext(DbContextOptions<DXApplication42EFCoreDbContext> options) : base(options) {
    }
    public DbSet<ModuleInfo> ModulesInfo { get; set; }
    public DbSet<ModelDifference> ModelDifferences { get; set; }
    public DbSet<ModelDifferenceAspect> ModelDifferenceAspects { get; set; }
    public DbSet<PermissionPolicyRole> Roles { get; set; }
    public DbSet<DXApplication42.Module.BusinessObjects.ApplicationUser> Users { get; set; }
    public DbSet<DXApplication42.Module.BusinessObjects.ApplicationUserLoginInfo> UserLoginInfos { get; set; }
    public DbSet<ReportDataV2> ReportDataV2 { get; set; }

    //public DbSet<DtoNum> TempNums { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity<DXApplication42.Module.BusinessObjects.ApplicationUserLoginInfo>(b => {
            b.HasIndex(nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.LoginProviderName), nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.ProviderUserKey)).IsUnique();
        });

        //modelBuilder.Entity<DtoNum>().HasNoKey();
    }
}
public class DtoNum
{
    public int Id { get; set; }
}
</code>```

However if I uncomment the 2 commented lines I get an error

```<code>System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=DevExpress.ExpressApp.EFCore.v21.2
  StackTrace:
   at DevExpress.ExpressApp.EFCore.EFCoreTypeInfoSource.SetupKeyMembers(TypeInfo typeInfo)
   at DevExpress.ExpressApp.EFCore.EFCoreTypeInfoSource.RegisterEntity(Type type)
   at DevExpress.ExpressApp.EFCore.TypeInfoSourceHelper.InitTypeInfoSource(EFCoreObjectSpaceProvider objectSpaceProvider)
   at DevExpress.ExpressApp.EFCore.EFCoreObjectSpaceProvider..ctor(IDbContextFactory`1 dbContextFactory, ITypesInfo typesInfo)
   at DevExpress.EntityFrameworkCore.Security.SecuredEFCoreObjectSpaceProvider..ctor(ISelectDataSecurityProvider selectDataSecurityProvider, IDbContextFactory`1 dbContextFactory, ITypesInfo typesInfo)
   at DXApplication42.Win.DXApplication42WindowsFormsApplication.CreateDefaultObjectSpaceProvider(CreateCustomObjectSpaceProviderEventArgs args) in C:\Users\kirst\source\repos\DXApplication42\DXApplication42.Win\WinApplication.cs:line 34
</code>```

Shown as

Looking inside EFCoreTypeInfoSources I see

```<code>private void SetupKeyMembers(TypeInfo typeInfo) {
    IKey key = EntityTypes[typeInfo.FullName].FindPrimaryKey();
    typeInfo.KeyMember = null;
    foreach(IProperty property in key.Properties) {
        typeInfo.AddKeyMember(typeInfo.FindMember(property.Name));
    }
}
</code>```

I want to use the non table based DbSet as explained here.

I posted the code to GitHub

答: I think the problem is that not all entities have a key so FindPrimaryKey would return null causing SetupKeyMembers to fail.</p>

Body:
I have the following DbContext in a .net5 winforms EF XAF 21.2.5  standard security application created with the wizard and it runs OK.

[TypesInfoInitializer(typeof(DXApplication42ContextInitializer))]
public class DXApplication42EFCoreDbContext : DbContext {
    public DXApplication42EFCoreDbContext(DbContextOptions<DXApplication42EFCoreDbContext> options) : base(options) {
    }
    public DbSet<ModuleInfo> ModulesInfo { get; set; }
    public DbSet<ModelDifference> ModelDifferences { get; set; }
    public DbSet<ModelDifferenceAspect> ModelDifferenceAspects { get; set; }
    public DbSet<PermissionPolicyRole> Roles { get; set; }
    public DbSet<DXApplication42.Module.BusinessObjects.ApplicationUser> Users { get; set; }
    public DbSet<DXApplication42.Module.BusinessObjects.ApplicationUserLoginInfo> UserLoginInfos { get; set; }
    public DbSet<ReportDataV2> ReportDataV2 { get; set; }

    //public DbSet<DtoNum> TempNums { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity<DXApplication42.Module.BusinessObjects.ApplicationUserLoginInfo>(b => {
            b.HasIndex(nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.LoginProviderName), nameof(DevExpress.ExpressApp.Security.ISecurityUserLoginInfo.ProviderUserKey)).IsUnique();
        });

        //modelBuilder.Entity<DtoNum>().HasNoKey();
    }
}
public class DtoNum
{
    public int Id { get; set; }
}

However if I uncomment the 2 commented lines I get an error

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=DevExpress.ExpressApp.EFCore.v21.2
  StackTrace:
   at DevExpress.ExpressApp.EFCore.EFCoreTypeInfoSource.SetupKeyMembers(TypeInfo typeInfo)
   at DevExpress.ExpressApp.EFCore.EFCoreTypeInfoSource.RegisterEntity(Type type)
   at DevExpress.ExpressApp.EFCore.TypeInfoSourceHelper.InitTypeInfoSource(EFCoreObjectSpaceProvider objectSpaceProvider)
   at DevExpress.ExpressApp.EFCore.EFCoreObjectSpaceProvider..ctor(IDbContextFactory`1 dbContextFactory, ITypesInfo typesInfo)
   at DevExpress.EntityFrameworkCore.Security.SecuredEFCoreObjectSpaceProvider..ctor(ISelectDataSecurityProvider selectDataSecurityProvider, IDbContextFactory`1 dbContextFactory, ITypesInfo typesInfo)
   at DXApplication42.Win.DXApplication42WindowsFormsApplication.CreateDefaultObjectSpaceProvider(CreateCustomObjectSpaceProviderEventArgs args) in C:\Users\kirst\source\repos\DXApplication42\DXApplication42.Win\WinApplication.cs:line 34

Shown as

Looking inside EFCoreTypeInfoSources I see

private void SetupKeyMembers(TypeInfo typeInfo) {
    IKey key = EntityTypes[typeInfo.FullName].FindPrimaryKey();
    typeInfo.KeyMember = null;
    foreach(IProperty property in key.Properties) {
        typeInfo.AddKeyMember(typeInfo.FindMember(property.Name));
    }
}

I want to use the non table based DbSet as explained here.

I posted the code to GitHub


问:
Ansible try different variables until the command was executed successfully
I would like to backup MySQL by Ansible.The MySQL password will be encrypted by ansible vault. My question is our company has 5 different passwords for Mysql.
Is that possible to let Ansible try the password until mysqldump command was executed successfully (if password-2 works then stop trying password-3,4,5)

```<code>- name: Backup MySQL database in all VM
  hosts: mysql-group
  vars_files:
    - /my_ansible_vault_secret
  remote_user: ansible
  become: true

  tasks:
  - name: Run mysqldump in the VM
    ansible.builtin.shell:
      cmd: mysqldump -u root -p{{ password-1 }} --all-databases > mybackup.sql

#### Vault File ###

cat /my_ansible_vault_secret

password-1: password-1
password-2: password-2
password-3: password-3
password-4: password-4
password-5: password-5
</code>```

I am very new to Ansible, any help is appreciated!

答: The real question here is not if you can, but if you should. And the obvious answer is no. This is a great way to lock yourself out of your MySQL accounts though.</p>

Body:
I would like to backup MySQL by Ansible.The MySQL password will be encrypted by ansible vault. My question is our company has 5 different passwords for Mysql.
Is that possible to let Ansible try the password until mysqldump command was executed successfully (if password-2 works then stop trying password-3,4,5)

- name: Backup MySQL database in all VM
  hosts: mysql-group
  vars_files:
    - /my_ansible_vault_secret
  remote_user: ansible
  become: true

  tasks:
  - name: Run mysqldump in the VM
    ansible.builtin.shell:
      cmd: mysqldump -u root -p{{ password-1 }} --all-databases > mybackup.sql

#### Vault File ###

cat /my_ansible_vault_secret

password-1: password-1
password-2: password-2
password-3: password-3
password-4: password-4
password-5: password-5

I am very new to Ansible, any help is appreciated!


问:
Connecting tables of two or more databases with each other in android studio
I just wanted to know if there is any way to connect two tables of two different databases under one project.
I have the databases as follow

First database

```<code>private String CREATE_USER_TABLE = "CREATE TABLE  "+ TABLE_USER + "(" +
        COLUMN_USER_ID +" INTEGER PRIMARY KEY AUTOINCREMENT , " + COLUMN_USER_MOBILE + " TEXT," +
        COLUMN_USER_EMAIL + " TEXT, "
        + COLUMN_USER_MOTHERNAME + " TEXT, " + COLUMN_USER_FATHERNAME + " TEXT, " +
        COLUMN_USER_PASSWORD + " TEXT, " + COLUMN_USER_CONFIRM_PASSWORD + " TEXT " + ")";
</code>```

Second database

```<code>        private String CREATE_BABY_TABLE = "CREATE TABLE "+ TABLE_BABY + "(" +
        COLUMN_BABY_ID + " INTEGER  PRIMARY KEY AUTOINCREMENT , " + COLUMN_BABY_NAME + " TEXT, "
        + COLUMN_BABY_DATE + " TEXT, " + COLUMN_BABY_GENDER + " TEXT, " + COLUMN_BABY_AGE +
          " TEXT " + ")";
</code>```

答:
Yes, application can has connect to different databases. (By clear sqlite or any db library, like Room)
But your question contains two tables but not two databases. You must just put them to one database.</p>

Body:
I just wanted to know if there is any way to connect two tables of two different databases under one project.
I have the databases as follow

First database

private String CREATE_USER_TABLE = "CREATE TABLE  "+ TABLE_USER + "(" +
        COLUMN_USER_ID +" INTEGER PRIMARY KEY AUTOINCREMENT , " + COLUMN_USER_MOBILE + " TEXT," +
        COLUMN_USER_EMAIL + " TEXT, "
        + COLUMN_USER_MOTHERNAME + " TEXT, " + COLUMN_USER_FATHERNAME + " TEXT, " +
        COLUMN_USER_PASSWORD + " TEXT, " + COLUMN_USER_CONFIRM_PASSWORD + " TEXT " + ")";

Second database

        private String CREATE_BABY_TABLE = "CREATE TABLE "+ TABLE_BABY + "(" +
        COLUMN_BABY_ID + " INTEGER  PRIMARY KEY AUTOINCREMENT , " + COLUMN_BABY_NAME + " TEXT, "
        + COLUMN_BABY_DATE + " TEXT, " + COLUMN_BABY_GENDER + " TEXT, " + COLUMN_BABY_AGE +
          " TEXT " + ")";


问:
How to detect click on mapbox-gl-geocoder results (suggestions)?
When I type in and get a dropdown with suggestions (suggestions-wrapper) - is it possible to get the click event on an item in the dropdown list? Thanks.</p>

答:
You can subscribe to the result event:

```<code>geocoder.on('result', result => console.log(result));
</code>```

Body:
You can subscribe to the result event:

geocoder.on('result', result => console.log(result));


问:
Order DataList and trim last 4 characters
Trying to order a list of files that are sitting in a folder. I am able to display the files just fine and the links work but cannot order them by the file name while removing the last 4 characters (.xlsx). It's ordered by the first 2 digits and I need to remove the last 4 characters ".xls" from the end of the file name. The list of files are:
01-07-2022.xlsx
12-03-2021.xlsx
11-05-2021.xlsx
etc.

I need them in that order and removing the .xlsx as it shows that name on the page. Right now it displays incorrectly below as:

12-04-2020.xlsx
12-03-2021.xlsx
11-07-2020.xlsx
11-05-2021.xlsx
10-01-2020.xlsx

just reading the first 2 digits for 12, 11, 10...etc. and then it shows a mix of the years.

My code to remove the characters and display in order.
Design View:

```<code>
                                        <div id="pccommlist" runat="server" visible="true">
                                            <asp:DataList ID="PCDataList" runat="server" RepeatColumns="1" BorderWidth="0" CellPadding="3" ForeColor="#2ba6cb"
                                                Width="100%">
                                                <FooterStyle BackColor="#ffffff" />
                                                <ItemTemplate>
                                                    <asp:ImageButton Width="16px" ID="excelimage" runat="server" BorderStyle="None" ImageUrl='../imagessecure/icons/lists/excel.png' Height="16px" />
                                                     Precinct as of <asp:Label ID="lblDate" runat="server" />
                                            <asp:HyperLink runat="server" NavigateUrl='<%#"pcredirect.aspx?name=" + DataBinder.Eval(Container.DataItem, "Name").ToString()%>' ID="pcLink" Target="_blank"
                                                Text='<%# DataBinder.Eval(Container.DataItem, "Name").ToString() %>'>
                                            </asp:HyperLink>
                                                </ItemTemplate>
                                                <FooterStyle BackColor="White" ForeColor="#2ba6cb" />
                                                <ItemStyle BorderColor="White" BorderStyle="None" BorderWidth="0" HorizontalAlign="Center"
                                                    VerticalAlign="Bottom" BackColor="White" ForeColor="#2ba6cb" />
                                            </asp:DataList>
                                        </div>
</code>```

Code Behind. Was trying to order it by creation time which was ideal and then tried full name as you see the commented out code above the FullName line.

```<code>    private void GetXLS()
    {

        DirectoryInfo dir = new DirectoryInfo(MapPath("~/pcselect2022/"));
        //FileInfo[] fileArray = dir.GetFiles("*.xlsx").OrderByDescending(p => p.CreationTimeUtc).ToArray(); //pull ONLY the xlsx files
        FileInfo[] fileArray = dir.GetFiles("*.xlsx").OrderByDescending(p => p.FullName).ToArray(); //pull ONLY the xlsx files
        char[] trimChars = { '.', 'x', 'l', 's' };
        string fileName = fileArray.ToString().TrimEnd(trimChars);

        //decide if we need to make controls visible
        pccommlist.Visible = fileArray.Length > 0;
        PCDataList.DataSource = fileArray;
        PCDataList.DataBind();
    }
</code>```

答:
I would probably use a grid, say with markup like this:

```<code>     <div style="width:20%;padding:25px">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="table" >
            <Columns>
                <asp:BoundField DataField="FileName" HeaderText="FileName"        />
                <asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:ImageButton ID="cmdExcel" runat="server" Height="48px" Width="48px"
                            ImageUrl="~/Content/excel.png"
                            PostBackUrl ='<%# Eval("URL") %>'  />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
</code>```

And then your code to load could be this:

```<code>   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("FileDate", typeof(DateTime));
        dt.Columns.Add("FileName", typeof(string));
        dt.Columns.Add("URL", typeof(string));

        DirectoryInfo MyDir = new DirectoryInfo(MapPath("~/pcselect2022/"));
        FileInfo[] MyFiles = MyDir.GetFiles("*.xlsx");
        foreach (FileInfo OneFile in MyFiles)
        {
            DataRow OneRow = dt.NewRow();
            OneRow["FileName"] = Path.GetFileNameWithoutExtension(OneFile.Name);
            OneRow["URL"] = @"pcredirect.aspx?name=" + OneFile.Name;
            OneRow["FileDate"] = DateTime.ParseExact(OneRow["FileName"].ToString(),
                                 "MM-dd-yyyy", CultureInfo.InvariantCulture);
            dt.Rows.Add(OneRow);
        }

        // order table by FileName (DATE type)
        dt.DefaultView.Sort = "FileDate";

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
</code>```

And now you get this:

So, you can put the file create date, or file name without extension into the above list. And we can convert the file format to a date, and then it will sort correctly as per above code. So, create a table, and then you can sort by default view, or whatever.

Also, note how we pulled out the URL expression - might as well add the extra junk to that URL in place of a more complex expression in the markup.

Edit: - date format was wrong

Note the date format as original posted was wrong, I used "mm", and you need to use "MM". Hence this:

```<code> OneRow["FileDate"] = DateTime.ParseExact(OneRow["FileName"].ToString(),
                     "MM-dd-yyyy", CultureInfo.InvariantCulture);
</code>```

("mm" needs to be MM).

Body:
Trying to order a list of files that are sitting in a folder. I am able to display the files just fine and the links work but cannot order them by the file name while removing the last 4 characters (.xlsx). It's ordered by the first 2 digits and I need to remove the last 4 characters ".xls" from the end of the file name. The list of files are:
01-07-2022.xlsx
12-03-2021.xlsx
11-05-2021.xlsx
etc.

I need them in that order and removing the .xlsx as it shows that name on the page. Right now it displays incorrectly below as:

12-04-2020.xlsx
12-03-2021.xlsx
11-07-2020.xlsx
11-05-2021.xlsx
10-01-2020.xlsx

just reading the first 2 digits for 12, 11, 10...etc. and then it shows a mix of the years.

My code to remove the characters and display in order.
Design View:

                                            <asp:DataList ID="PCDataList" runat="server" RepeatColumns="1" BorderWidth="0" CellPadding="3" ForeColor="#2ba6cb"
                                                Width="100%">
                                                <FooterStyle BackColor="#ffffff" />
                                                <ItemTemplate>
                                                    <asp:ImageButton Width="16px" ID="excelimage" runat="server" BorderStyle="None" ImageUrl='../imagessecure/icons/lists/excel.png' Height="16px" />
                                                     Precinct as of <asp:Label ID="lblDate" runat="server" />
                                            <asp:HyperLink runat="server" NavigateUrl='<%#"pcredirect.aspx?name=" + DataBinder.Eval(Container.DataItem, "Name").ToString()%>' ID="pcLink" Target="_blank"
                                                Text='<%# DataBinder.Eval(Container.DataItem, "Name").ToString() %>'>
                                            </asp:HyperLink>
                                                </ItemTemplate>
                                                <FooterStyle BackColor="White" ForeColor="#2ba6cb" />
                                                <ItemStyle BorderColor="White" BorderStyle="None" BorderWidth="0" HorizontalAlign="Center"
                                                    VerticalAlign="Bottom" BackColor="White" ForeColor="#2ba6cb" />
                                            </asp:DataList>

Code Behind. Was trying to order it by creation time which was ideal and then tried full name as you see the commented out code above the FullName line.

    private void GetXLS()
    {

        DirectoryInfo dir = new DirectoryInfo(MapPath("~/pcselect2022/"));
        //FileInfo[] fileArray = dir.GetFiles("*.xlsx").OrderByDescending(p => p.CreationTimeUtc).ToArray(); //pull ONLY the xlsx files
        FileInfo[] fileArray = dir.GetFiles("*.xlsx").OrderByDescending(p => p.FullName).ToArray(); //pull ONLY the xlsx files
        char[] trimChars = { '.', 'x', 'l', 's' };
        string fileName = fileArray.ToString().TrimEnd(trimChars);

        //decide if we need to make controls visible
        pccommlist.Visible = fileArray.Length > 0;
        PCDataList.DataSource = fileArray;
        PCDataList.DataBind();
    }

Body:
I would probably use a grid, say with markup like this:

     <div style="width:20%;padding:25px">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="table" >
            <Columns>
                <asp:BoundField DataField="FileName" HeaderText="FileName"        />
                <asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:ImageButton ID="cmdExcel" runat="server" Height="48px" Width="48px"
                            ImageUrl="~/Content/excel.png"
                            PostBackUrl ='<%# Eval("URL") %>'  />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>

And then your code to load could be this:

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("FileDate", typeof(DateTime));
        dt.Columns.Add("FileName", typeof(string));
        dt.Columns.Add("URL", typeof(string));

        DirectoryInfo MyDir = new DirectoryInfo(MapPath("~/pcselect2022/"));
        FileInfo[] MyFiles = MyDir.GetFiles("*.xlsx");
        foreach (FileInfo OneFile in MyFiles)
        {
            DataRow OneRow = dt.NewRow();
            OneRow["FileName"] = Path.GetFileNameWithoutExtension(OneFile.Name);
            OneRow["URL"] = @"pcredirect.aspx?name=" + OneFile.Name;
            OneRow["FileDate"] = DateTime.ParseExact(OneRow["FileName"].ToString(),
                                 "MM-dd-yyyy", CultureInfo.InvariantCulture);
            dt.Rows.Add(OneRow);
        }

        // order table by FileName (DATE type)
        dt.DefaultView.Sort = "FileDate";

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

And now you get this:

So, you can put the file create date, or file name without extension into the above list. And we can convert the file format to a date, and then it will sort correctly as per above code. So, create a table, and then you can sort by default view, or whatever.

Also, note how we pulled out the URL expression - might as well add the extra junk to that URL in place of a more complex expression in the markup.

Edit: - date format was wrong

Note the date format as original posted was wrong, I used "mm", and you need to use "MM". Hence this:

 OneRow["FileDate"] = DateTime.ParseExact(OneRow["FileName"].ToString(),
                     "MM-dd-yyyy", CultureInfo.InvariantCulture);

("mm" needs to be MM).


问:
How to make a fill parent+wrap_content (in that order) Android
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

```<code> LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1
</code>```

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

```<code><RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>
</code>```

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

```<code><RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>
</code>```

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance

答: remove the android:layout_alignParentBottom="true" from the textview and add this to your root relativelayout tag android:layout_centerInParent="true"

Body:
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

 LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

<RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

<RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance


问:
R update a tibble using data from a second tibble as row and column
I have an empty tibble full of NA's with the rows and columns, respectively named for id numbers and all the dates in a period of time.  For example, this code:

```<code>tbl <- tibble(PERSONAL_ID = c("A", "B", "C", "D"))
dates = as.character((seq(as.Date("2016-01-01"), as.Date("2016-01-05"), by="days")))
tbl[dates] <- NA
tbl <- column_to_rownames(tbl, var = "PERSONAL_ID")
</code>```

I have a second tibble that contains columns matching up one ID number with one date, as in this example:

```<code>enrollments <- tibble(ID = c("D", "B", "C", "D"),
                      date = c("2016-01-01", "2016-01-03", "2016-01-05", "2016-01-02"))
</code>```

What I would like to do is add "1" to the row and column of the first tibble (tbl) corresponding to the ID and date listed in the second tibble (enrollments).  For the example code above, the desired output would be:

```<code>  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A       <NA>       <NA>       <NA>        <NA>      <NA>
B       <NA>       <NA>          1        <NA>      <NA>
C       <NA>       <NA>       <NA>        <NA>         1
D          1          1       <NA>        <NA>      <NA>
</code>```

Thank you!

答:
Here's a tidyverse approach.

First change your tbl from a wide format to a long format so that it matches the format of enrollments.

Create a Count column in enrollments, and every row would be Count = 1.

Then left_join the transformed tbl with enrollments using ID and date as the joining field.

Finally, transform the long format back to a wide format and set rownames.

```<code>library(tidyverse)

left_join(tbl %>% rownames_to_column(var = "ID") %>%
            pivot_longer(-ID, names_to = "date", values_to = "Count") %>%
            select(-Count),
          enrollments %>% mutate(Count = 1),
          by = c("ID", "date")) %>%
  pivot_wider(names_from = "date", values_from = "Count") %>%
  column_to_rownames(var = "ID")
</code>```

Output

```<code> 2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A         NA         NA         NA         NA         NA
B         NA         NA          1         NA         NA
C         NA         NA         NA         NA          1
D          1          1         NA         NA         NA
</code>```

Your dataset as reference

```<code>tbl
  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A         NA         NA         NA         NA         NA
B         NA         NA         NA         NA         NA
C         NA         NA         NA         NA         NA
D         NA         NA         NA         NA         NA
</code>```
```<code>enrollments
# A tibble: 4 x 2
  ID    date
  <chr> <chr>
1 D     2016-01-01
2 B     2016-01-03
3 C     2016-01-05
4 D     2016-01-02
</code>```

Body:
I have an empty tibble full of NA's with the rows and columns, respectively named for id numbers and all the dates in a period of time.  For example, this code:

tbl <- tibble(PERSONAL_ID = c("A", "B", "C", "D"))
dates = as.character((seq(as.Date("2016-01-01"), as.Date("2016-01-05"), by="days")))
tbl[dates] <- NA
tbl <- column_to_rownames(tbl, var = "PERSONAL_ID")

I have a second tibble that contains columns matching up one ID number with one date, as in this example:

enrollments <- tibble(ID = c("D", "B", "C", "D"),
                      date = c("2016-01-01", "2016-01-03", "2016-01-05", "2016-01-02"))

What I would like to do is add "1" to the row and column of the first tibble (tbl) corresponding to the ID and date listed in the second tibble (enrollments).  For the example code above, the desired output would be:

  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A       <NA>       <NA>       <NA>        <NA>      <NA>
B       <NA>       <NA>          1        <NA>      <NA>
C       <NA>       <NA>       <NA>        <NA>         1
D          1          1       <NA>        <NA>      <NA>

Thank you!

Body:
Here's a tidyverse approach.

First change your tbl from a wide format to a long format so that it matches the format of enrollments.

Create a Count column in enrollments, and every row would be Count = 1.

Then left_join the transformed tbl with enrollments using ID and date as the joining field.

Finally, transform the long format back to a wide format and set rownames.

library(tidyverse)

left_join(tbl %>% rownames_to_column(var = "ID") %>%
            pivot_longer(-ID, names_to = "date", values_to = "Count") %>%
            select(-Count),
          enrollments %>% mutate(Count = 1),
          by = c("ID", "date")) %>%
  pivot_wider(names_from = "date", values_from = "Count") %>%
  column_to_rownames(var = "ID")

Output

 2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A         NA         NA         NA         NA         NA
B         NA         NA          1         NA         NA
C         NA         NA         NA         NA          1
D          1          1         NA         NA         NA

Your dataset as reference

tbl
  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A         NA         NA         NA         NA         NA
B         NA         NA         NA         NA         NA
C         NA         NA         NA         NA         NA
D         NA         NA         NA         NA         NA

enrollments
# A tibble: 4 x 2
  ID    date
  <chr> <chr>
1 D     2016-01-01
2 B     2016-01-03
3 C     2016-01-05
4 D     2016-01-02


问:
Cannot find name 'it' in Jest TypeScript
I try to create an intial setup for Jest in React + TypeScript. I have completed the initial setup and try to check whether the test runs.
When I run the test using the command npm test, I am getting the following error:

```<code>Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
</code>```

I have installed the types for Jest as well as removed the types in tsconfig.json, but still I am getting the same error.

```<code>{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "plugins": [{ "name": "typescript-tslint-plugin" }],
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "pretty": true,
    "baseUrl": "src",
    "types": ["jest"],
    "typeRoots": ["./src/types"],
    "suppressImplicitAnyIndexErrors": true
  },
  "include": ["src", "node_modules/@types/jest"],
  "exclude": ["node_modules"]
}
`

</code>```

Package.json

```<code>
    "jest": {
        "transform": {
          ".(ts|tsx)": "ts-jest"
        },
        "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
        "moduleFileExtensions": [
          "ts",
          "tsx",
          "js"
        ]
      },
      "devDependencies": {
        "@babel/plugin-proposal-export-default-from": "^7.2.0",
        "@types/enzyme": "^3.9.3",
        "@types/jest": "^24.0.14",
        "enzyme": "^3.10.0",
        "gh-pages": "^1.2.0",
        "husky": "^2.2.0",
        "jest": "^24.8.0",
        "node-sass": "^4.11.0",
        "prettier": "^1.17.0",
        "react-scripts": "2.1.8",
        "react-test-renderer": "^16.8.6",
        "stylelint": "^9.3.0",
        "stylelint-config-recommended-scss": "^3.2.0",
        "stylelint-config-standard": "^18.2.0",
        "stylelint-order": "^0.8.1",
        "stylelint-scss": "^3.1.3",
        "ts-jest": "^24.0.2",
        "tslint": "^5.16.0",
        "tslint-config-prettier": "^1.18.0",
        "tslint-plugin-prettier": "^2.0.1",
        "tslint-react": "^4.0.0",
        "tslint-react-hooks": "^2.1.0"
      }

</code>```

答: None of the above solutions worked for me. Not even importing '@types/jest' which was throwing error while doing npm test to import 'jest' instead. The only solution for me is import { describe, it, beforeEach } from '@jest/globals' to test files</p>

Body:
I try to create an intial setup for Jest in React + TypeScript. I have completed the initial setup and try to check whether the test runs.
When I run the test using the command npm test, I am getting the following error:

Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.

I have installed the types for Jest as well as removed the types in tsconfig.json, but still I am getting the same error.

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "plugins": [{ "name": "typescript-tslint-plugin" }],
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "pretty": true,
    "baseUrl": "src",
    "types": ["jest"],
    "typeRoots": ["./src/types"],
    "suppressImplicitAnyIndexErrors": true
  },
  "include": ["src", "node_modules/@types/jest"],
  "exclude": ["node_modules"]
}
`

Package.json

    "jest": {
        "transform": {
          ".(ts|tsx)": "ts-jest"
        },
        "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
        "moduleFileExtensions": [
          "ts",
          "tsx",
          "js"
        ]
      },
      "devDependencies": {
        "@babel/plugin-proposal-export-default-from": "^7.2.0",
        "@types/enzyme": "^3.9.3",
        "@types/jest": "^24.0.14",
        "enzyme": "^3.10.0",
        "gh-pages": "^1.2.0",
        "husky": "^2.2.0",
        "jest": "^24.8.0",
        "node-sass": "^4.11.0",
        "prettier": "^1.17.0",
        "react-scripts": "2.1.8",
        "react-test-renderer": "^16.8.6",
        "stylelint": "^9.3.0",
        "stylelint-config-recommended-scss": "^3.2.0",
        "stylelint-config-standard": "^18.2.0",
        "stylelint-order": "^0.8.1",
        "stylelint-scss": "^3.1.3",
        "ts-jest": "^24.0.2",
        "tslint": "^5.16.0",
        "tslint-config-prettier": "^1.18.0",
        "tslint-plugin-prettier": "^2.0.1",
        "tslint-react": "^4.0.0",
        "tslint-react-hooks": "^2.1.0"
      }