问:
Why is my code working fine when running in the console but not when used in the script?
When I tried the following code in my IDE and in the command prompt with python test.py, my text file was still empty afterward:

```<code>with open("test.txt", "r+") as file:
    file.write("Hello World")
</code>```

I was confused, because this worked before. So I tried the exact same code in the python console.
And voila, my text file test.txt now contained the string Hello World

When I changed the content of the text file manually and tried to read it again with the program, the output was the string I tried to write earlier to the text file.

Is there some kind of delay when trying to write and read to and from a file when using a script in comparison to using the python console?

答:
I believe the cmd is located somewhere else.

You can change the location of where you are operating in the cmd with the os module:

```<code>>>> import os
>>> os.chdir(path) # replace path with the path you want to write to a file in
>>> with open('text.txt','r+') as file:
...     file.write("Hello World")
...
>>>
</code>```

You can also find the current directory of your cmd by entering os.getcwd(). Or, you can just add the path of the place you want to write in the file to the file name:

```<code>>>> import os
>>> with open(os.path.join(path,'text.txt'),'r+') as file:
...     file.write("Hello World")
...
>>>
</code>```

Body:
When I tried the following code in my IDE and in the command prompt with python test.py, my text file was still empty afterward:

with open("test.txt", "r+") as file:
    file.write("Hello World")

I was confused, because this worked before. So I tried the exact same code in the python console.
And voila, my text file test.txt now contained the string Hello World

When I changed the content of the text file manually and tried to read it again with the program, the output was the string I tried to write earlier to the text file.

Is there some kind of delay when trying to write and read to and from a file when using a script in comparison to using the python console?

Body:
I believe the cmd is located somewhere else.

You can change the location of where you are operating in the cmd with the os module:

>>> import os
>>> os.chdir(path) # replace path with the path you want to write to a file in
>>> with open('text.txt','r+') as file:
...     file.write("Hello World")
...
>>>

You can also find the current directory of your cmd by entering os.getcwd(). Or, you can just add the path of the place you want to write in the file to the file name:

>>> import os
>>> with open(os.path.join(path,'text.txt'),'r+') as file:
...     file.write("Hello World")
...
>>>


来源: stackexchange

问:
How to split a list which contains sentences into a list with words using Python?
I have a list with sentences in Python:

```<code>list1 = ["This is the first sentence", "This is the second", "This is the third"]
</code>```

I tried using split(" "):

```<code>sth = []
for i in list1:
    sth.append(i.split(" "))
</code>```

But this way I get a 2D array, which contains regular lists from the sentences with their words, so something like this:

```<code>[["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]
</code>```

I would like the outcome to be a regular list, this way:

```<code>["This", "is", "the", "first", "sentence", "This", "is", "the", "second", "This", "is", "the", "third"]
</code>```

How can I achieve this?

答:
```<code>sth = []
for i in list1:
    sth += i.split(" ")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list with sentences in Python:

list1 = ["This is the first sentence", "This is the second", "This is the third"]

I tried using split(" "):

sth = []
for i in list1:
    sth.append(i.split(" "))

But this way I get a 2D array, which contains regular lists from the sentences with their words, so something like this:

[["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]

I would like the outcome to be a regular list, this way:

["This", "is", "the", "first", "sentence", "This", "is", "the", "second", "This", "is", "the", "third"]

How can I achieve this?


问:
How to make a global keyboard hook in C#
How can I make a global keyboard hook for an Electron.NET app in C#? I believe as long as it works in a console app it should work properly in an Electron.Net app.

I made a 'solution' for this problem, but It tends to use up a lot of CPU (7-10%). Maybe someone is somehow able to make it actually efficient if there is no other option:

```<code>using System;
using System.Runtime.InteropServices;
using System.Threading;

[DllImport("User32.dll")]
public static extern short GetAsyncKeyState(int vKey);

// Other VKey codes: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
public enum VKeys {
    LBUTTON = 0x01,     // Left mouse button
    RBUTTON = 0x02,     // Right mouse button
    KEY_0 = 0x30,       // 0 key
    KEY_1 = 0x31,       // 1 key
    KEY_2 = 0x32,       // 2 key
    KEY_3 = 0x33,       // 3 key
    KEY_4 = 0x34,       // 4 key
    KEY_5 = 0x35,       // 5 key
    KEY_6 = 0x36,       // 6 key
    KEY_7 = 0x37,       // 7 key
    KEY_8 = 0x38,       // 8 key
    KEY_9 = 0x39        // 9 key
}

public void Start()
{
    Thread HookThread = new Thread(delegate ()
    {
        var keys = Enum.GetValues(typeof(VKeys));

        while (true)
        {
            foreach (int key in keys)
            {
                var ks = GetAsyncKeyState(key);

                if (ks < 0)
                {
                    Console.WriteLine($"pressed {key}");
                    //Thread.Sleep(100);
                }

                //Thread.Sleep(1); // Even sleeping for '1ms' will delay it too much
            }
        }
    });

    HookThread.Start();
}
</code>```

A lot of things I found would only work if I was using WinForms or WPF.

Edit:

I tried this answer by hanabanashiku, and a lot of others that I found online, but all of them seemed to just lag the keyboards input and their callback functions would seem to be never called.

I decided to write the keyboard hook in C++, compile as a DLL and then reference that DLL in my C# code to hopefully make a keyboard hook that functioned properly and didn't cause any noticeable input lag, but that didn't work either.

The keyboard hook ran perfectly when run as an .exe in C++, but when I compiled it as a DLL and ran it in C# it caused the same issue as before - a lot of input lag and the callback function seemingly not being called.

Heres the code if anyone wants to try it:

KeyboardHook.cpp

```<code>#include "KeyboardHook.h"
#include <iostream>

#define __event void KeyDown(int key), KeyUp(int key);

using namespace Hooks;

void KeyDown(int key)
{
    std::cout << "KeyDown\n";
}

void KeyUp(int key)
{
    std::cout << "KeyUp\n";
}

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode == HC_ACTION)
    {
        PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;

        switch (wParam)
        {
            case WM_KEYDOWN:
            case WM_SYSKEYDOWN:
                KeyDown(p->vkCode);
                break;
            case WM_KEYUP:
            case WM_SYSKEYUP:
                KeyUp(p->vkCode);
                break;
        }
    }

    // Not processing keys so always return CallNextHookEx
    return(CallNextHookEx(NULL, nCode, wParam, lParam));
}

void KeyboardHook::Install() {
    // Install keyboard hook
    keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, 0, 0);
    std::cout << "Installed\n";
}

void KeyboardHook::Uninstall() {
    // Unhook keyboard hook
    UnhookWindowsHookEx(keyboardHook);
}
</code>```

KeyboardHook.h

```<code>#include <Windows.h>

HHOOK keyboardHook;

namespace Hooks
{
    class KeyboardHook
    {
    public:
        __declspec(dllexport) void Install();
        __declspec(dllexport) void Uninstall();
    };
}
</code>```

Program.cs

```<code>using System;
using System.Runtime.InteropServices;

namespace HelloMyNameIsSpindiNiceToMeetYou
{
    class Program
    {
        private const string hooksPath = @"C:\Path\To\Hooks.dll";

        // If EntryPoint doesn't work, yours might be different
        // https://learn.microsoft.com/en-us/dotnet/framework/interop/identifying-functions-in-dlls
        //
        // "For example, you can use dumpbin /exports Hooks.dll [...] to obtain function names."
        // you need to be in the folder with the dll for above to work in Command Prompt for VS
        [DllImport(hooksPath, EntryPoint = "?Install@KeyboardHook@Hooks@@QEAAXXZ", CallingConvention = CallingConvention.Cdecl)]
        private extern static void Install();

        static void Main(string[] args)
        {
            Install();

            // keep console app running
            while (true)
            {
                continue;
            }

            // or keep it running with this
            // Console.ReadKey();
        }
    }
}

</code>```

I am testing this stuff outside of an electron.net app now, just in a console app and things still don't work. Everything I have found just leads back to using winforms, which I cannot use.

答:
Electron has a way to create global shortcuts built-in, you just have to adapt the syntax a little to work with Electron.Net, you can search the repo to figure out function names (usually names are the same, just in PascalCase).

Registering a shortcut:

```<code>Electron.GlobalShortcut.Register("CommandOrControl+X", () =>
{
    Console.WriteLine("CommandOrControl+X pressed");
});
</code>```

Unregistering a shortcut:

```<code>// Unregister specific shortcut
Electron.GlobalShortcut.Unregister("CommandOrControl+X");

// Unregister all shortcuts
Electron.GlobalShortcut.UnregisterAll();
</code>```

Body:
How can I make a global keyboard hook for an Electron.NET app in C#? I believe as long as it works in a console app it should work properly in an Electron.Net app.

I made a 'solution' for this problem, but It tends to use up a lot of CPU (7-10%). Maybe someone is somehow able to make it actually efficient if there is no other option:

using System;
using System.Runtime.InteropServices;
using System.Threading;

[DllImport("User32.dll")]
public static extern short GetAsyncKeyState(int vKey);

// Other VKey codes: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
public enum VKeys {
    LBUTTON = 0x01,     // Left mouse button
    RBUTTON = 0x02,     // Right mouse button
    KEY_0 = 0x30,       // 0 key
    KEY_1 = 0x31,       // 1 key
    KEY_2 = 0x32,       // 2 key
    KEY_3 = 0x33,       // 3 key
    KEY_4 = 0x34,       // 4 key
    KEY_5 = 0x35,       // 5 key
    KEY_6 = 0x36,       // 6 key
    KEY_7 = 0x37,       // 7 key
    KEY_8 = 0x38,       // 8 key
    KEY_9 = 0x39        // 9 key
}

public void Start()
{
    Thread HookThread = new Thread(delegate ()
    {
        var keys = Enum.GetValues(typeof(VKeys));

        while (true)
        {
            foreach (int key in keys)
            {
                var ks = GetAsyncKeyState(key);

                if (ks < 0)
                {
                    Console.WriteLine($"pressed {key}");
                    //Thread.Sleep(100);
                }

                //Thread.Sleep(1); // Even sleeping for '1ms' will delay it too much
            }
        }
    });

    HookThread.Start();
}

A lot of things I found would only work if I was using WinForms or WPF.

Edit:

I tried this answer by hanabanashiku, and a lot of others that I found online, but all of them seemed to just lag the keyboards input and their callback functions would seem to be never called.

I decided to write the keyboard hook in C++, compile as a DLL and then reference that DLL in my C# code to hopefully make a keyboard hook that functioned properly and didn't cause any noticeable input lag, but that didn't work either.

The keyboard hook ran perfectly when run as an .exe in C++, but when I compiled it as a DLL and ran it in C# it caused the same issue as before - a lot of input lag and the callback function seemingly not being called.

Heres the code if anyone wants to try it:

KeyboardHook.cpp

#include "KeyboardHook.h"
#include <iostream>

#define __event void KeyDown(int key), KeyUp(int key);

using namespace Hooks;

void KeyDown(int key)
{
    std::cout << "KeyDown\n";
}

void KeyUp(int key)
{
    std::cout << "KeyUp\n";
}

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode == HC_ACTION)
    {
        PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;

        switch (wParam)
        {
            case WM_KEYDOWN:
            case WM_SYSKEYDOWN:
                KeyDown(p->vkCode);
                break;
            case WM_KEYUP:
            case WM_SYSKEYUP:
                KeyUp(p->vkCode);
                break;
        }
    }

    // Not processing keys so always return CallNextHookEx
    return(CallNextHookEx(NULL, nCode, wParam, lParam));
}

void KeyboardHook::Install() {
    // Install keyboard hook
    keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, 0, 0);
    std::cout << "Installed\n";
}

void KeyboardHook::Uninstall() {
    // Unhook keyboard hook
    UnhookWindowsHookEx(keyboardHook);
}

KeyboardHook.h

#include <Windows.h>

HHOOK keyboardHook;

namespace Hooks
{
    class KeyboardHook
    {
    public:
        __declspec(dllexport) void Install();
        __declspec(dllexport) void Uninstall();
    };
}

Program.cs

using System;
using System.Runtime.InteropServices;

namespace HelloMyNameIsSpindiNiceToMeetYou
{
    class Program
    {
        private const string hooksPath = @"C:\Path\To\Hooks.dll";

        // If EntryPoint doesn't work, yours might be different
        // https://learn.microsoft.com/en-us/dotnet/framework/interop/identifying-functions-in-dlls
        //
        // "For example, you can use dumpbin /exports Hooks.dll [...] to obtain function names."
        // you need to be in the folder with the dll for above to work in Command Prompt for VS
        [DllImport(hooksPath, EntryPoint = "?Install@KeyboardHook@Hooks@@QEAAXXZ", CallingConvention = CallingConvention.Cdecl)]
        private extern static void Install();

        static void Main(string[] args)
        {
            Install();

            // keep console app running
            while (true)
            {
                continue;
            }

            // or keep it running with this
            // Console.ReadKey();
        }
    }
}

I am testing this stuff outside of an electron.net app now, just in a console app and things still don't work. Everything I have found just leads back to using winforms, which I cannot use.

Body:
Electron has a way to create global shortcuts built-in, you just have to adapt the syntax a little to work with Electron.Net, you can search the repo to figure out function names (usually names are the same, just in PascalCase).

Registering a shortcut:

Electron.GlobalShortcut.Register("CommandOrControl+X", () =>
{
    Console.WriteLine("CommandOrControl+X pressed");
});

Unregistering a shortcut:

// Unregister specific shortcut
Electron.GlobalShortcut.Unregister("CommandOrControl+X");

// Unregister all shortcuts
Electron.GlobalShortcut.UnregisterAll();


答:
This should do it:</p>

```<code>' '.join(l).split()
</code>```

Title: How to split a list which contains sentences into a list with words using Python?

Body:
This should do it:

' '.join(l).split()


问:
Getting error on while importing webdriver in pycharm"No matching distribution found for webdriver"
Getting error while importing webdriver in pycharm

"No matching distribution found for webdriver"

Using Pip version 20.0.2, Selenium version – 3.141.0, OS –windows &  Python 3.7

Problem mentioned here in image.

Tried cmd pip install webdriver and tried pip3 install webdriver still getting error.

I can run my script through IDLE but not through pycharm .

答:
You can install selenium in pycharm:</p>

```<code>Pycharm -> Perform (Cntrl + Alt + S) -> Select Project Interpreter -> Click on (+) icon -> Search for Selenium -> Select and Install Package -> Apply -> Ok
</code>```

Body:
You can install selenium in pycharm:

Pycharm -> Perform (Cntrl + Alt + S) -> Select Project Interpreter -> Click on (+) icon -> Search for Selenium -> Select and Install Package -> Apply -> Ok


问:
C# Hooking a vmtable
As a side-project for learning more about c#'s native side, i wanted to hook a virtual method in a virtual method table.

I successfully can call the function, but changing the pointer to the virtual method to my own method crashs when the function is called.

I made a small c++ application for this learning purpose and here is it

#include <iostream>
#include <conio.h>
using namespace std;

class Class
{
 public:
 virtual void Function ( ) = 0;
 virtual void Function2 ( ) = 0;
 virtual void Function3 ( ) = 0;
};

class ClassI : Class
{
 public:
 void Function ( )
 {
  cout << "Function1" << endl;
 }

 void Function2 ( )
 {
  cout << "Function2" << endl;
 }

 void Function3 ( )
 {
  cout << "Function3" << endl;
 }

};

int main ( )
{
 ClassI* a = new ClassI ( );
 int aaaa = 10;

 int* aaa = &aaaa;

 cout << "AddressOfClass: " << &a << endl;
 getch ( );

 a->Function ( );

 getch ( );
 delete a;
 return 0;
}```
</div>
</div>
</p>

<p>I get a instance of the Class pointer and output it and wait for input.</p>

<p>After input i run the function i want to hook.</p>

<p>Now in my c# side, i created a dll and the dll is in the process'es memory space through clr injection.</p>

<p>I verified the injection works with a bunch of ways.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> public class EntryPoint
    {
        #region Delegates
        private delegate void orgFunction();
        private static orgFunction oFunction;
        #endregion

        public static void Hooked()
        {
            Console.WriteLine("HookedFunction");
            oFunction();
        }

        [DllExport("DllMain",CallingConvention.Cdecl)]
        public static void DllMain()
        {

            unsafe
            {
                Delegate Hook = new Action(Hooked);
                IntPtr* vtable = (IntPtr*)*(IntPtr*)0x00F3FE10;
                oFunction = Marshal.GetDelegateForFunctionPointer<orgFunction>(*(IntPtr*)vtable[0]);
                uint OldProtection;
                MUtil.MEMORY_BASIC_INFORMATION mbi;
                MUtil.VirtualQuery((IntPtr)vtable, out mbi, (IntPtr)sizeof(MUtil.MEMORY_BASIC_INFORMATION));
                MUtil.VirtualProtect(mbi.BaseAddress, (uint)mbi.RegionSize, 0x04, out OldProtection);
                vtable[0] = Marshal.GetFunctionPointerForDelegate(Hook);
                MUtil.VirtualProtect(mbi.BaseAddress, (uint)mbi.RegionSize, OldProtection, out OldProtection);
            }
        }
    }</code>```

That is what i am doing at the c# side.

after getting the oFunction, for test i did call it and removed the other code and it worked.

but hooking it everything is fine but when in the c++ program i send a input and it runs the function we hooked, the app crashes.

I also update the address each time i run the c++ program so ye.

        [StructLayout(LayoutKind.Sequential)]
        public struct MEMORY_BASIC_INFORMATION
        {
            public IntPtr BaseAddress;
            public IntPtr AllocationBase;
            public uint AllocationProtect;
            public IntPtr RegionSize;
            public uint State;
            public uint Protect;
            public uint Type;
        }

        [DllImport("kernel32.dll")]
        public static extern UIntPtr VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, IntPtr dwLength);

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool VirtualProtect(IntPtr address, uint size, uint newProtect, out uint oldProtect);```
</div>
</div>
</p>

<hr>

<h2>Edit:</h2>

<p>I decided to make a simple little test, i changed oFunction to vmtable[2]</p>

```oFunction = Marshal.GetDelegateForFunctionPointer<orgFunction>(*(IntPtr*) vtable[1]  );
```

That code above crashed me and i was quite surpired, this brings me the idea that getting the address of ClassI instance might give as the address of the first function instead of the vmtable which i don't think is the case.

-

Thanks for reading this, have a good day/night.

Best regards.

答:
To do a vmtable hook all you do is overwrite the function pointer inside the vtable with a new one, to do that you just use VirtualProtect() to get write permissions if necessary and then use WriteProcessMemory() to overwrite it.

You need to manually reverse the vtable and manually overwrite it using WriteProcessMemory().

Get the address of the vtable

Add vTableIndex*4 or vTableIndex*8 (depending on x86 vs x64)

Overwrite this address with WriteProcessMemory

ContentLicense: CC BY-SA 3.0

Title: C# Hooking a vmtable

Body:
As a side-project for learning more about c#'s native side, i wanted to hook a virtual method in a virtual method table.

I successfully can call the function, but changing the pointer to the virtual method to my own method crashs when the function is called.

I made a small c++ application for this learning purpose and here is it

#include <iostream>
#include <conio.h>
using namespace std;

class Class
{
 public:
 virtual void Function ( ) = 0;
 virtual void Function2 ( ) = 0;
 virtual void Function3 ( ) = 0;
};

class ClassI : Class
{
 public:
 void Function ( )
 {
  cout << "Function1" << endl;
 }

 void Function2 ( )
 {
  cout << "Function2" << endl;
 }

 void Function3 ( )
 {
  cout << "Function3" << endl;
 }

};

int main ( )
{
 ClassI* a = new ClassI ( );
 int aaaa = 10;

 int* aaa = &aaaa;

 cout << "AddressOfClass: " << &a << endl;
 getch ( );

 a->Function ( );

 getch ( );
 delete a;
 return 0;
}

I get a instance of the Class pointer and output it and wait for input.

After input i run the function i want to hook.

Now in my c# side, i created a dll and the dll is in the process'es memory space through clr injection.

I verified the injection works with a bunch of ways.

 public class EntryPoint
    {
        #region Delegates
        private delegate void orgFunction();
        private static orgFunction oFunction;
        #endregion

        public static void Hooked()
        {
            Console.WriteLine("HookedFunction");
            oFunction();
        }

        [DllExport("DllMain",CallingConvention.Cdecl)]
        public static void DllMain()
        {

            unsafe
            {
                Delegate Hook = new Action(Hooked);
                IntPtr* vtable = (IntPtr*)*(IntPtr*)0x00F3FE10;
                oFunction = Marshal.GetDelegateForFunctionPointer<orgFunction>(*(IntPtr*)vtable[0]);
                uint OldProtection;
                MUtil.MEMORY_BASIC_INFORMATION mbi;
                MUtil.VirtualQuery((IntPtr)vtable, out mbi, (IntPtr)sizeof(MUtil.MEMORY_BASIC_INFORMATION));
                MUtil.VirtualProtect(mbi.BaseAddress, (uint)mbi.RegionSize, 0x04, out OldProtection);
                vtable[0] = Marshal.GetFunctionPointerForDelegate(Hook);
                MUtil.VirtualProtect(mbi.BaseAddress, (uint)mbi.RegionSize, OldProtection, out OldProtection);
            }
        }
    }

That is what i am doing at the c# side.

after getting the oFunction, for test i did call it and removed the other code and it worked.

but hooking it everything is fine but when in the c++ program i send a input and it runs the function we hooked, the app crashes.

I also update the address each time i run the c++ program so ye.

        [StructLayout(LayoutKind.Sequential)]
        public struct MEMORY_BASIC_INFORMATION
        {
            public IntPtr BaseAddress;
            public IntPtr AllocationBase;
            public uint AllocationProtect;
            public IntPtr RegionSize;
            public uint State;
            public uint Protect;
            public uint Type;
        }

        [DllImport("kernel32.dll")]
        public static extern UIntPtr VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, IntPtr dwLength);

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool VirtualProtect(IntPtr address, uint size, uint newProtect, out uint oldProtect);

Edit:

I decided to make a simple little test, i changed oFunction to vmtable[2]

oFunction = Marshal.GetDelegateForFunctionPointer<orgFunction>(*(IntPtr*) vtable[1]  );

That code above crashed me and i was quite surpired, this brings me the idea that getting the address of ClassI instance might give as the address of the first function instead of the vmtable which i don't think is the case.

-

Thanks for reading this, have a good day/night.

Best regards.


答:
You can use chain </p>

```<code>from itertools import chain
list(chain(*[["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]))
</code>```

Body:
You can use chain

from itertools import chain
list(chain(*[["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]))


问:
Converting Strings in Excel to Dates
We imported a bunch of data into cells.  But when you click on the cell, their is an apostrophe before the data, so it thinks its a string. By removing the apostrophe, the data gets recognized as dates. How do I avoid doing this by hand?</p>

答:
Use a column beside the dates column.

Add a formula like this one:

```<code>=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))
</code>```

it will vary depending on your date format, copy this formula for all rows.

Then copy the results, and do a paste special where you paste values.

You now have a column with dates.

Title: Converting Strings in Excel to Dates

Body:
Use a column beside the dates column.

Add a formula like this one:

=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))

it will vary depending on your date format, copy this formula for all rows.

Then copy the results, and do a paste special where you paste values.

You now have a column with dates.


问:
How to typify a nested object?
How to typify a nested object?

enter image description here

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ UA: {}; RU: {}; }'.
  No index signature with a parameter of type 'string' was found on type '{ UA: {}; RU: {}; }'.  TS7053

```<code>interface IState {
  showInfo: any,
  priceVariantIndex: any,
  loaded: any,
  imgLoaded: any,
  imgUrl: any,
  selectedCutlery: any,
  product: any,
}

  state = {
    showInfo: false,
    priceVariantIndex: 0,
    loaded: false,
    imgLoaded: false,
    imgUrl: '',
    selectedCutlery: '',
    product: {
      productTranslations: {
        UA: {},
        RU: {}
      }
    }
  }

      <Link to={linkObject}>
        {this.props.language &&
        this.state.product.productTranslations[`${this.props.language}`]
          .name != undefined
          ? this.state.product.productTranslations[
              `${this.props.language}` // err
            ].name
          : product.name}
      </Link>
</code>```

答:
The conflict here is between the type of language in props, which is a string and the type of productTranslations which is type { UA: {}, RU: {} }.

If you don't want to explicitly type of language to the specific letter-codes that you are using to represent languages, you can update your product type in the IState interface to

product: { productTranslations: { [language: string]: any } };

Which now says that this.state.product has a productTranslations property which is a mapping of string to any.

As an aside, I'd highly recommend eliminating all of those any types, or at least change them to unknown so that you don't run into issues that TypeScript could definitely have caught for you.

Title: How to typify a nested object?

Body:
How to typify a nested object?

enter image description here

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ UA: {}; RU: {}; }'.
  No index signature with a parameter of type 'string' was found on type '{ UA: {}; RU: {}; }'.  TS7053

interface IState {
  showInfo: any,
  priceVariantIndex: any,
  loaded: any,
  imgLoaded: any,
  imgUrl: any,
  selectedCutlery: any,
  product: any,
}

  state = {
    showInfo: false,
    priceVariantIndex: 0,
    loaded: false,
    imgLoaded: false,
    imgUrl: '',
    selectedCutlery: '',
    product: {
      productTranslations: {
        UA: {},
        RU: {}
      }
    }
  }

      <Link to={linkObject}>
        {this.props.language &&
        this.state.product.productTranslations[`${this.props.language}`]
          .name != undefined
          ? this.state.product.productTranslations[
              `${this.props.language}` // err
            ].name
          : product.name}
      </Link>


问:
Issues when trying to space XMLHttpRequest() API calls every 5 seconds with setTimeout()
I am working on the initial data pull for a project. It will be cached and further requests will be much less.  I am attempting to space out my API requests every 5 seconds to avoid overloading the server and hitting the rate limit per their rules.  It does not seem that my setTimeout() function is actually working as desired. I logged time stamps to see and all iterations seem to be happening at the exact same time.  I think this somehow due to the asynchronous nature of javascript, but I'm not sure how to remedy it.  Any help would be greatly appreciated.

Code Excerpt:

```<code>var leagues;
function getLeagues(){

    var reqURL = "url";
    var data = new XMLHttpRequest();
    data.open("GET", reqURL);
    data.responseType = "text";
    data.send();

    // parse data on load
    data.onload = function() {
        // League IDs
        leagues = JSON.parse(data.response)

        for (i = 0; i < 5; i++) {
            delay(i); // iterate every 5 secs
        }
    };
}

function delay(i) {
  setTimeout(() => {
    var d = new Date();
    console.log(d.getSeconds())
  }, 5000);
}
</code>```

答:
setTimeout is a browser API that will guarantees not an exact delay time to execute after but a minimum time to execute a function so it's not related to js.

setTimeout cause the browser to set a timer after x milliseconds, when finished the function you pass will be in the event queue, but it won't necessarily execute, if event queue was completely empty, you are lucky and the function get executed immediately after 5 seconds, otherwise the function have to wait in queue until each function get executed before so we have (5 seconds + some times until the function get in the head of the queue then get executed).

calling setTimeout five times in sequence (using a for loop) with the same time delay will add the same function 5 consequent times in the event queue, all will be executed at the same time because of the same time delay used for all of them. so a solution would be to use different delay time for each function.

I'll suggest the solution for the same problem, because I faced it alot

Callback based solution

repeat(processingRequest, 5, 5000);

function processingRequest(){
  console.log('Making request at', new Date().getTime());
}

function repeat(func, howManyTimes, milliSecondsInterval){

  if(howManyTimes > 0)
    delay(() => {
      func();
      howManyTimes--;
      repeat(func, howManyTimes, milliSecondsInterval);
    }, milliSecondsInterval);
}

function delay(func, milliSeconds){
  setTimeout(func, milliSeconds);
}
```

<hr>

<p>Promise based solution(more preferred)</p>

<pre class="lang-js prettyprint-override"><code>

repeat(processingRequest, 5, 5000);

function processingRequest(){
  console.log('Making request at', new Date().getTime());
}

function repeat(func, howManyTimes, milliSeconds){
  delay(milliSeconds)
  .then(() => {

    func();
    howManyTimes--;

    if(howManyTimes > 0)
      repeat(func, howManyTimes, milliSeconds);
  });
}

function delay(milliSeconds){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, milliSeconds);
  });
}
</code>```

using a library like rxjs(providing a repeat and delay) will make things even more simple

https://rxjs-dev.firebaseapp.com/api/operators/repeat

https://rxjs-dev.firebaseapp.com/api/operators/delay

even though not every application need rxjs, but we have to say it give the programmer a great power over clean sync or async operations

[References]

For further knowledge about Browser API & Event queue

Cool talk from Philip Roberts

https://youtu.be/8aGhZQkoFbQ?t=1165

from THE BEST great js resource I've found

https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch1.md

Body:
I am working on the initial data pull for a project. It will be cached and further requests will be much less.  I am attempting to space out my API requests every 5 seconds to avoid overloading the server and hitting the rate limit per their rules.  It does not seem that my setTimeout() function is actually working as desired. I logged time stamps to see and all iterations seem to be happening at the exact same time.  I think this somehow due to the asynchronous nature of javascript, but I'm not sure how to remedy it.  Any help would be greatly appreciated.

Code Excerpt:

var leagues;
function getLeagues(){

    var reqURL = "url";
    var data = new XMLHttpRequest();
    data.open("GET", reqURL);
    data.responseType = "text";
    data.send();

    // parse data on load
    data.onload = function() {
        // League IDs
        leagues = JSON.parse(data.response)

        for (i = 0; i < 5; i++) {
            delay(i); // iterate every 5 secs
        }
    };
}

function delay(i) {
  setTimeout(() => {
    var d = new Date();
    console.log(d.getSeconds())
  }, 5000);
}

Body:
setTimeout is a browser API that will guarantees not an exact delay time to execute after but a minimum time to execute a function so it's not related to js.

setTimeout cause the browser to set a timer after x milliseconds, when finished the function you pass will be in the event queue, but it won't necessarily execute, if event queue was completely empty, you are lucky and the function get executed immediately after 5 seconds, otherwise the function have to wait in queue until each function get executed before so we have (5 seconds + some times until the function get in the head of the queue then get executed).

calling setTimeout five times in sequence (using a for loop) with the same time delay will add the same function 5 consequent times in the event queue, all will be executed at the same time because of the same time delay used for all of them. so a solution would be to use different delay time for each function.

I'll suggest the solution for the same problem, because I faced it alot

Callback based solution

repeat(processingRequest, 5, 5000);

function processingRequest(){
  console.log('Making request at', new Date().getTime());
}

function repeat(func, howManyTimes, milliSecondsInterval){

  if(howManyTimes > 0)
    delay(() => {
      func();
      howManyTimes--;
      repeat(func, howManyTimes, milliSecondsInterval);
    }, milliSecondsInterval);
}

function delay(func, milliSeconds){
  setTimeout(func, milliSeconds);
}

Promise based solution(more preferred)

repeat(processingRequest, 5, 5000);

function processingRequest(){
  console.log('Making request at', new Date().getTime());
}

function repeat(func, howManyTimes, milliSeconds){
  delay(milliSeconds)
  .then(() => {

    func();
    howManyTimes--;

    if(howManyTimes > 0)
      repeat(func, howManyTimes, milliSeconds);
  });
}

function delay(milliSeconds){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, milliSeconds);
  });
}

using a library like rxjs(providing a repeat and delay) will make things even more simple

https://rxjs-dev.firebaseapp.com/api/operators/repeat

https://rxjs-dev.firebaseapp.com/api/operators/delay

even though not every application need rxjs, but we have to say it give the programmer a great power over clean sync or async operations

[References]

For further knowledge about Browser API & Event queue

Cool talk from Philip Roberts

https://youtu.be/8aGhZQkoFbQ?t=1165

from THE BEST great js resource I've found

https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch1.md


问:
Angular js (1.4) Using Ternary operator inside ng-repeat to show different html?
```<code><tr ng-repeat="(field, value) in vm.params track by $index">
  <td>{{::field}}</td>
  <td  hkey="{{field}}">  {{value.include('http')?<a href ="{{value}}">{{value}}</a>:{{value}} }}</td>

</tr>
</code>```

In the above Angular view I wanted the value field to check if the value contains string 'http', if so wrap an anchor tag around it so its clickable else show regular text value.

Its not working out right , here its what its showing,

how to do this properly?.

i attempted to do it from the controller  like this

```<code>      vm.params["Source Link"]?vm.params["Source Link"] = '<a href='+vm.params['Source Link']+'>link</a>':""
</code>```

But data is displaying in string form not html, i see it with anchor tag and everything.

vm.params looks something like this

    {
    Provider Name: "MARIO BLOUNT",
    Provider State: "WV",
    Provider City: "BRIDGEPORT",
    Action Date: "06/03/2014",
    Provider Source: "HEALTH CARE FRAUD FILE",
    Provider Type: "PHARMACIST",
    Action Description: "CHARGED BY INDICTMENT WITH CONSPIRACY TO ILLEGALLY
    PRESCRIBE AND DISTRIBUTE OXYCODONE",
    Clinic Name: "BEST CARE PHARMACY; MARIO DAVID BLOUNT RPH",
    Source Link: "https://www.dea.gov/press-releases/201",
    }```

答:
the ternary operator isn't gona work for template like this, it'll have to look like this...

```<code><td ng-if="value.includes('http')" hkey="{{field}}"> <a href ="{{value}}">{{value}}</a></td>
<td ng-if="!value.includes('http')" hkey="{{field}}">{{value}}</td>
</code>```

but be careful as this is not great for change detection since you'll run that includes check 2xN params on every change detection cycle.

if you can reliably do like:

```<code>ng-if="field === 'Source Link'"
</code>```

instead, that would perform better, or you're at least better off using value.startsWith('http')

Body:
  {{::field}}
    {{value.include('http')?{{value}}:{{value}} }}

In the above Angular view I wanted the value field to check if the value contains string 'http', if so wrap an anchor tag around it so its clickable else show regular text value.

Its not working out right , here its what its showing,

how to do this properly?.

i attempted to do it from the controller  like this

      vm.params["Source Link"]?vm.params["Source Link"] = 'link':""

But data is displaying in string form not html, i see it with anchor tag and everything.

vm.params looks something like this

    {
    Provider Name: "MARIO BLOUNT",
    Provider State: "WV",
    Provider City: "BRIDGEPORT",
    Action Date: "06/03/2014",
    Provider Source: "HEALTH CARE FRAUD FILE",
    Provider Type: "PHARMACIST",
    Action Description: "CHARGED BY INDICTMENT WITH CONSPIRACY TO ILLEGALLY
    PRESCRIBE AND DISTRIBUTE OXYCODONE",
    Clinic Name: "BEST CARE PHARMACY; MARIO DAVID BLOUNT RPH",
    Source Link: "https://www.dea.gov/press-releases/201",
    }

Body:
the ternary operator isn't gona work for template like this, it'll have to look like this...

<td ng-if="value.includes('http')" hkey="{{field}}"> <a href ="{{value}}">{{value}}</a></td>
<td ng-if="!value.includes('http')" hkey="{{field}}">{{value}}</td>

but be careful as this is not great for change detection since you'll run that includes check 2xN params on every change detection cycle.

if you can reliably do like:

ng-if="field === 'Source Link'"

instead, that would perform better, or you're at least better off using value.startsWith('http')


问:
Renaming columns of many dfs with the elements of a list
I have 5 dataframes called control1,control2,control3,control4,control5. I'm renaming their columns. But i want to rename the column named 10 (integer name) with the elements in files for each one.
Something like this:

```<code>    control1.rename(columns={10:'02042020.txt'}, inplace=True)
    control2.rename(columns={10:'05032020.txt'}, inplace=True)
    #...... etc etc
</code>```

This is my code:

```<code>        lista_controles=[control1,control2,control3,control4,control5]
        files=['02042020.txt','05032020.txt','12032020.txt','19032020.txt','26032020.txt']
        for df in lista_controles:
            df.rename(columns={2:'NOMBRE_ESTACION'}, inplace=True)
            for i in files
               df.rename(columns={10:f'{i}'}, inplace=True)
</code>```

But is only renaming with the first element of the list (02042020.txt). How can i solve this? Thanks..

答:
This is because when df.rename(columns={10:f'{i}'}, inplace=True) first runs, it changes the name "10" to "02042020.txt". At the second iteration, there is no any column named "10" anymore, so it does nothing, because it just has been changed to "02042020.txt".

You could try:

for i, df in enumerate(lista_controles):
    df.rename(columns={2:'NOMBRE_ESTACION'}, inplace=True)
    df.rename(columns={10:files[i]}, inplace=True)
```

To make this work, make sure you have equal number of elements in lista_controles and files though. If there are not, there are other ways to do it.

Body:
I have 5 dataframes called control1,control2,control3,control4,control5. I'm renaming their columns. But i want to rename the column named 10 (integer name) with the elements in files for each one.
Something like this:

    control1.rename(columns={10:'02042020.txt'}, inplace=True)
    control2.rename(columns={10:'05032020.txt'}, inplace=True)
    #...... etc etc

This is my code:

        lista_controles=[control1,control2,control3,control4,control5]
        files=['02042020.txt','05032020.txt','12032020.txt','19032020.txt','26032020.txt']
        for df in lista_controles:
            df.rename(columns={2:'NOMBRE_ESTACION'}, inplace=True)
            for i in files
               df.rename(columns={10:f'{i}'}, inplace=True)

But is only renaming with the first element of the list (02042020.txt). How can i solve this? Thanks..

Body:
This is because when df.rename(columns={10:f'{i}'}, inplace=True) first runs, it changes the name "10" to "02042020.txt". At the second iteration, there is no any column named "10" anymore, so it does nothing, because it just has been changed to "02042020.txt".

You could try:

for i, df in enumerate(lista_controles):
    df.rename(columns={2:'NOMBRE_ESTACION'}, inplace=True)
    df.rename(columns={10:files[i]}, inplace=True)

To make this work, make sure you have equal number of elements in lista_controles and files though. If there are not, there are other ways to do it.


答:
With list comprehension its a single line of code</p>

```<code>list1 = [["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]

print( [item for subl in list1 for item in subl] )
OUT: ['This', 'is', 'the', 'first', 'sentence', 'This', 'is', 'the', 'second', 'This', 'is', 'the', 'third']
</code>```

Body:
With list comprehension its a single line of code

list1 = [["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]

print( [item for subl in list1 for item in subl] )
OUT: ['This', 'is', 'the', 'first', 'sentence', 'This', 'is', 'the', 'second', 'This', 'is', 'the', 'third']


问:
How to call different tables in an "if and else" part of the same database in iPhone?
I have a database. It has two tables in it. I want to call one table in an if condition.  How do I call the second table in the else part if the if conditions fail?

This is the code I used:

```<code>{
    NSArray *Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *DocumentsDirectory = [Paths objectAtIndex:0];
    NSString *Path = [DocumentsDirectory stringByAppendingPathComponent:@"StoreList.sqlite"];

    // Open the database from the users filessytem.
    if (sqlite3_open([Path UTF8String], &database) == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access
        //*********const char *sqlStatement = "select * from Store where Zipcode ='%@'",inputTxt ;

        NSString *sqlStatement = [NSString stringWithFormat:@"select * from Store where Zipcode ='%@' or Address = '%@' or CityName = '%@'",inputTxt, inputTxt, inputTxt];
        NSLog(@" Query in if :%@",sqlStatement);
        sqlite3_stmt *compiledStatement;

        if (sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) {

            // Loop through the results and add them to the feeds array.

            if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Read the data from the result row

                NSString *latValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                NSLog(@"Latitude:%@",latValue);
                NSString *longValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                NSLog(@"Longitude:%@",longValue);
                //currentLocationLbl.text=[NSString stringWithFormat:@" %@ , %@" ,latValue,longValue];

                // delegate.latitudeVal=latValue;
                // delegate.longitudeVal=longValue;
                txtChangeLocation.text = @"";
                isFromChangeLoc=TRUE;

                //self.tabBarController.selectedIndex=3;
            }
            else {
                NSLog(@"ELSE PART");

                // Open the database from the user's filessytem.
                if (sqlite3_open([Path UTF8String], &database) == SQLITE_OK) {
                    // Setup the SQL Statement and compile it for faster access
                    //*********const char *sqlStatement = "select * from Store where Zipcode ='%@'",inputTxt ;

                    NSString *sqlStatement = [NSString stringWithFormat:@"select * from zipcodes where zip ='35004'"];
                    NSLog(@" Query in if :%@",sqlStatement);
                    sqlite3_stmt *compiledStatement;

                    if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) {
                        // Loop through the results and add them to the feeds array

                        if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                            // Read the data from the result row

                            NSString *latValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                            NSLog(@"Latitude:%@",latValue);
                            NSString *longValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                            NSLog(@"Longitude:%@",longValue);
                            //currentLocationLbl.text=[NSString stringWithFormat:@" %@ , %@" ,latValue,longValue];

                            // delegate.latitudeVal=latValue;
                            // delegate.longitudeVal=longValue;
                            txtChangeLocation.text = @"";
                            isFromChangeLoc=TRUE;
                        }
                    }
                }
            }
            sqlite3_finalize(compiledStatement);
            sqlite3_close(database);
        }
    }
</code>```

I'm getting the input from the text box. When I give the correct value, which is there in the database, it is working fine, the fetch of the data is correct. If I give the wrong data in the textbox it's not working fine - the else condition fails.

How can this issue be fixed?

答:
When going on else you open the same database again, that's not needed (and might cause some problems as well, haven't tried it). Use a BOOL when running the first (select) statement and set it to YES or NO if it fails or not. After you finish with the first statement check the BOOL value and if ==NO run the second statement.

```<code>    ...
BOOL success = NO;
NSString *sqlStatement = [NSString stringWithFormat:@"select * from Store where Zipcode '%@' or Address = '%@' or CityName = '%@'",inputTxt, inputTxt, inputTxt];
NSLog(@" Query in if :%@",sqlStatement);
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK){
    if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
        // Read the data from the result row

        NSString *latValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
        NSLog(@"Latitude:%@",latValue);
        NSString *longValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
        NSLog(@"Longitude:%@",longValue);
        //currentLocationLbl.text=[NSString stringWithFormat:@" %@ , %@" ,latValue,longValue];

    //  delegate.latitudeVal=latValue;
    //  delegate.longitudeVal=longValue;
        txtChangeLocation.text = @"";
        isFromChangeLoc=TRUE;

        //self.tabBarController.selectedIndex=3;
        success=YES;
    }
}
sqlite3_finalize(compiledStatement);

if(success){
    //do the else from your code
    NSString *sqlStatement = [NSString stringWithFormat:@"select * from zipcodes where zip ='35004'"];
    NSLog(@" Query in if :%@",sqlStatement);

    if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK){
         // Loop through the results and add them to the feeds array

         if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
         // Read the data from the result row

              NSString *latValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
              NSLog(@"Latitude:%@",latValue);
              NSString *longValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
              NSLog(@"Longitude:%@",longValue);
              //currentLocationLbl.text=[NSString stringWithFormat:@" %@ , %@" ,latValue,longValue];

            // delegate.latitudeVal=latValue;
            // delegate.longitudeVal=longValue;
               txtChangeLocation.text = @"";
               isFromChangeLoc=TRUE;
        }
    }
    sqlite3_finalize(compiledStatement);
}
</code>```

I haven't run it, so it might contain some bugs.

Body:
I have a database. It has two tables in it. I want to call one table in an if condition.  How do I call the second table in the else part if the if conditions fail?

This is the code I used:

{
    NSArray *Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *DocumentsDirectory = [Paths objectAtIndex:0];
    NSString *Path = [DocumentsDirectory stringByAppendingPathComponent:@"StoreList.sqlite"];

    // Open the database from the users filessytem.
    if (sqlite3_open([Path UTF8String], &database) == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access
        //*********const char *sqlStatement = "select * from Store where Zipcode ='%@'",inputTxt ;

        NSString *sqlStatement = [NSString stringWithFormat:@"select * from Store where Zipcode ='%@' or Address = '%@' or CityName = '%@'",inputTxt, inputTxt, inputTxt];
        NSLog(@" Query in if :%@",sqlStatement);
        sqlite3_stmt *compiledStatement;

        if (sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) {

            // Loop through the results and add them to the feeds array.

            if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Read the data from the result row

                NSString *latValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                NSLog(@"Latitude:%@",latValue);
                NSString *longValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                NSLog(@"Longitude:%@",longValue);
                //currentLocationLbl.text=[NSString stringWithFormat:@" %@ , %@" ,latValue,longValue];

                // delegate.latitudeVal=latValue;
                // delegate.longitudeVal=longValue;
                txtChangeLocation.text = @"";
                isFromChangeLoc=TRUE;

                //self.tabBarController.selectedIndex=3;
            }
            else {
                NSLog(@"ELSE PART");

                // Open the database from the user's filessytem.
                if (sqlite3_open([Path UTF8String], &database) == SQLITE_OK) {
                    // Setup the SQL Statement and compile it for faster access
                    //*********const char *sqlStatement = "select * from Store where Zipcode ='%@'",inputTxt ;

                    NSString *sqlStatement = [NSString stringWithFormat:@"select * from zipcodes where zip ='35004'"];
                    NSLog(@" Query in if :%@",sqlStatement);
                    sqlite3_stmt *compiledStatement;

                    if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK) {
                        // Loop through the results and add them to the feeds array

                        if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                            // Read the data from the result row

                            NSString *latValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                            NSLog(@"Latitude:%@",latValue);
                            NSString *longValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                            NSLog(@"Longitude:%@",longValue);
                            //currentLocationLbl.text=[NSString stringWithFormat:@" %@ , %@" ,latValue,longValue];

                            // delegate.latitudeVal=latValue;
                            // delegate.longitudeVal=longValue;
                            txtChangeLocation.text = @"";
                            isFromChangeLoc=TRUE;
                        }
                    }
                }
            }
            sqlite3_finalize(compiledStatement);
            sqlite3_close(database);
        }
    }

I'm getting the input from the text box. When I give the correct value, which is there in the database, it is working fine, the fetch of the data is correct. If I give the wrong data in the textbox it's not working fine - the else condition fails.

How can this issue be fixed?

Body:
When going on else you open the same database again, that's not needed (and might cause some problems as well, haven't tried it). Use a BOOL when running the first (select) statement and set it to YES or NO if it fails or not. After you finish with the first statement check the BOOL value and if ==NO run the second statement.

    ...
BOOL success = NO;
NSString *sqlStatement = [NSString stringWithFormat:@"select * from Store where Zipcode '%@' or Address = '%@' or CityName = '%@'",inputTxt, inputTxt, inputTxt];
NSLog(@" Query in if :%@",sqlStatement);
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK){
    if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
        // Read the data from the result row

        NSString *latValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
        NSLog(@"Latitude:%@",latValue);
        NSString *longValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
        NSLog(@"Longitude:%@",longValue);
        //currentLocationLbl.text=[NSString stringWithFormat:@" %@ , %@" ,latValue,longValue];

    //  delegate.latitudeVal=latValue;
    //  delegate.longitudeVal=longValue;
        txtChangeLocation.text = @"";
        isFromChangeLoc=TRUE;

        //self.tabBarController.selectedIndex=3;
        success=YES;
    }
}
sqlite3_finalize(compiledStatement);

if(success){
    //do the else from your code
    NSString *sqlStatement = [NSString stringWithFormat:@"select * from zipcodes where zip ='35004'"];
    NSLog(@" Query in if :%@",sqlStatement);

    if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK){
         // Loop through the results and add them to the feeds array

         if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
         // Read the data from the result row

              NSString *latValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
              NSLog(@"Latitude:%@",latValue);
              NSString *longValue = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
              NSLog(@"Longitude:%@",longValue);
              //currentLocationLbl.text=[NSString stringWithFormat:@" %@ , %@" ,latValue,longValue];

            // delegate.latitudeVal=latValue;
            // delegate.longitudeVal=longValue;
               txtChangeLocation.text = @"";
               isFromChangeLoc=TRUE;
        }
    }
    sqlite3_finalize(compiledStatement);
}

I haven't run it, so it might contain some bugs.


问:
Delay on the capture of an image with React Native Camera / Expo Camera, set 'processing message'?
I have a huge delay in my app from when a user takes a photo to when android processes the image.

The issue of delay in Expo with android camera has been answered here: Delay on the capture of an image - React Native Camera / Expo Camera.

I am trying to see if, as well as see skipProcessing on takePictureAsync, is there a way to set a callback for on processing? I would like to let the user know something is happening, or they may try to take another photo (the camera stays open until the image has been processed, which is not ideal).

Here is my code:

```<code>export default class CameraComponent extends Component{
  constructor(props) {
    super(props)
  }

  render() {
    <Camera
      ref={(ref) => {
        this.camera = ref;
      }}
      type={Camera.Constants.Type.back}
    >
      <TouchableOpacity
        onPress={this.takePicture}
      >
        <View>
          <FontAwesome
            name="camera"
          />
        </View>
      </TouchableOpacity>
    </Camera>;
  }

  takePicture = async () => {
    const photo = await this.camera.takePictureAsync({
      skipProcessing: true,
    });

    this.props.navigation.navigate("CameraConfirm", {
      img_url: photo.img_url,
      img_base64: photo.img_base64,
    });
  }
}

</code>```

I can't see anything in the docs, is there maybe a way around in React Native? I tried setting state, but that still happens after takePictureAsync so has no effect.

答:
I found one workaround which uses camera2API and onPictureSaved. The docs say there could be issues with camera2API, although I did not see anything weird going on (as yet).

The code now looks like this:

```<code>export default class CameraComponent extends Component{
  constructor(props) {
    super(props)

    this.state = {
      is_photo_taken: false,
    };
  }

  render() {
    <Camera
      ref={(ref) => {
        this.camera = ref;
      }}
      type={Camera.Constants.Type.back}
      // add styling to show/hide camera:
      style={{
        display: this.state.is_photo_taken ? "none" : null,
      }}
      useCamera2Api={true} // add this line
    >
      <TouchableOpacity
        onPress={this.takePicture}
      >
        <View>
          <FontAwesome
            name="camera"
          />
        </View>
      </TouchableOpacity>
    </Camera>;

    // add loading element with conditional show/hide:
    <Text
      style={{
        display: !this.state.is_photo_taken ? "none" : null,
      }}
    >
      Loading image...
    </Text>
  }

  takePicture = async () => {
    const photo = await this.camera.takePictureAsync({
      onPictureSaved: this.setState({ is_photo_taken: true }), // add this line
      // remove skipProcessing
    });

    this.props.navigation.navigate("CameraConfirm", {
      img_url: photo.img_url,
      img_base64: photo.img_base64,
    });
  }
}
</code>```

Also, since onPictureSaved is now being used, it means that skipProcesssing can now be omitted, if not needed.

I used show/hide instead of ternaries or && around the entire block to avoid losing the camera element from the page. If the camera element were to be lost as soon as a photo was taken, then it could not continue and process the image.

I hope this helps someone.

Body:
I have a huge delay in my app from when a user takes a photo to when android processes the image.

The issue of delay in Expo with android camera has been answered here: Delay on the capture of an image - React Native Camera / Expo Camera.

I am trying to see if, as well as see skipProcessing on takePictureAsync, is there a way to set a callback for on processing? I would like to let the user know something is happening, or they may try to take another photo (the camera stays open until the image has been processed, which is not ideal).

Here is my code:

export default class CameraComponent extends Component{
  constructor(props) {
    super(props)
  }

  render() {
    <Camera
      ref={(ref) => {
        this.camera = ref;
      }}
      type={Camera.Constants.Type.back}
    >
      <TouchableOpacity
        onPress={this.takePicture}
      >
        <View>
          <FontAwesome
            name="camera"
          />
        </View>
      </TouchableOpacity>
    </Camera>;
  }

  takePicture = async () => {
    const photo = await this.camera.takePictureAsync({
      skipProcessing: true,
    });

    this.props.navigation.navigate("CameraConfirm", {
      img_url: photo.img_url,
      img_base64: photo.img_base64,
    });
  }
}

I can't see anything in the docs, is there maybe a way around in React Native? I tried setting state, but that still happens after takePictureAsync so has no effect.

Body:
I found one workaround which uses camera2API and onPictureSaved. The docs say there could be issues with camera2API, although I did not see anything weird going on (as yet).

The code now looks like this:

export default class CameraComponent extends Component{
  constructor(props) {
    super(props)

    this.state = {
      is_photo_taken: false,
    };
  }

  render() {
    <Camera
      ref={(ref) => {
        this.camera = ref;
      }}
      type={Camera.Constants.Type.back}
      // add styling to show/hide camera:
      style={{
        display: this.state.is_photo_taken ? "none" : null,
      }}
      useCamera2Api={true} // add this line
    >
      <TouchableOpacity
        onPress={this.takePicture}
      >
        <View>
          <FontAwesome
            name="camera"
          />
        </View>
      </TouchableOpacity>
    </Camera>;

    // add loading element with conditional show/hide:
    <Text
      style={{
        display: !this.state.is_photo_taken ? "none" : null,
      }}
    >
      Loading image...
    </Text>
  }

  takePicture = async () => {
    const photo = await this.camera.takePictureAsync({
      onPictureSaved: this.setState({ is_photo_taken: true }), // add this line
      // remove skipProcessing
    });

    this.props.navigation.navigate("CameraConfirm", {
      img_url: photo.img_url,
      img_base64: photo.img_base64,
    });
  }
}

Also, since onPictureSaved is now being used, it means that skipProcesssing can now be omitted, if not needed.

I used show/hide instead of ternaries or && around the entire block to avoid losing the camera element from the page. If the camera element were to be lost as soon as a photo was taken, then it could not continue and process the image.

I hope this helps someone.


问:
Why are there two values for single corner radius in GradientDrawable.setCornerRadii for?
From android docs, the GradientDrawable.setCornerRadii (float[] radii)
 method:

Specifies radii for each of the 4 corners. For each corner, the array
  contains 2 values

Why are there 2 values for each corner? What is the meaning of two values for a single corner?

答: One value is for the X_radius the other for the Y_Radius.  If they are equal you'll get an even radius.  If they are different it will be distorted in one dimension or the other (look more like a logarithmic curve for example).</p>


问:
Lotusscript MIME Email
I modified a code that I found to send MIME HTML mails with attachments.
It works when the mail is open in gmail, but in Apple Mail or Lotus Notes there isn't any attachment in the body.
The plaintext part does not arrive either, but what interests me are the attachments.

Here is my code:

```<code>    Set MailDoc     = New NotesDocument( mailbox )
    session.convertMIME = False
    Dim body As NotesMIMEEntity
    Dim mimeHeader As NotesMIMEHeader
    Dim mimeEntity As NotesMIMEEntity
    Dim stream As NotesStream
</code>```

Set body = mailDoc.CreateMIMEEntity

```<code>    Set mimeHeader = body.CreateHeader({MIME-Version})
    Call mimeHeader.SetHeaderVal("1.0")
    Set mimeHeader = body.CreateHeader("Content-Type")
    Call mimeHeader.SetHeaderValAndParams({multipart/alternative;boundary="=NextPart_="})

    ' create another MIME part for the attachment. (repeat as needed)
    If (docEval.HasItem("$File")) Then
        Dim AttachmentsField As NotesRichTextItem
        Set AttachmentsField = docEval.GetFirstItem( "fc_adjunto" )
        If IsArray(AttachmentsField.EmbeddedObjects) Then ' Isarray validates for attachments ignoring embedded text
            ForAll att In AttachmentsField.EmbeddedObjects
                If att.Type = EMBED_ATTACHMENT Then
                    Call errorLog.LogAction("Inicio attch: " + att.Name())
                    Set mimeEntity = body.CreateChildEntity( )
                    Set mimeHeader = mimeEntity.CreateHeader("Content-Disposition")
                    aliasFilename = CStr(att.Name())
                    Call mimeHeader.SetHeaderValAndParams(|attachment; filename=| & aliasFilename)
                    Set stream = session.CreateStream
                    attachFilename = AttachToFile(session, docEval, CStr(att.Name()))  'Call o.ExtractFile(Attachfoldername & "\" & o.Name())
                    Call errorLog.LogAction("Inicio attch name: " + attachFilename)
                    stream.Open attachFileName, "binary"
                    Call mimeEntity.SetContentFromBytes(stream, "application/octet-stream", ENC_IDENTITY_BINARY)
                    mimeEntity.EncodeContent(ENC_BASE64)
                    Kill attachFilename
                End If
            End ForAll
        End If
    End If

    'Send the plain text part first (this never work for me!!)
    Set mimeEntity = body.createChildEntity()
    Set stream = session.createStream()
    Call WritePlainText(stream)
    Call mimeEntity.setContentFromText(stream, {text/plain;charset="iso-8859-1"}, ENC_IDENTITY_8BIT)

    'Send the HTML part.
    Call stream.Truncate()

    'Send the HTML part.
    Set mimeEntity = body.createChildEntity()
    Call WriteHTML(stream, elHtml)
    Call mimeEntity.setContentFromText(stream, {text/html;charset="iso-8859-1"},ENC_IDENTITY_8BIT)
    'Close the stream and Send it
    Call stream.Truncate()
    Call stream.Close()

    Call maildoc.Closemimeentities(True)

    Call MailDoc.ReplaceItemValue("EncryptOnSend"   , True )
    Call MailDoc.ReplaceItemValue("PostedDate"      , Now )
    Call MailDoc.ReplaceItemValue("From"            , Remitente )
    Call MailDoc.ReplaceItemValue("SendFrom"        , Remitente )
    Call MailDoc.ReplaceItemValue("Principal"       , Remitente )
    Call MailDoc.ReplaceItemValue( "SendTo"         , sendTo )
    Call MailDoc.ReplaceItemValue( "CopyTo"         , copyTo )
    Call MailDoc.ReplaceItemValue( "BlindCopyTo"    , bccTo )
    Call MailDoc.ReplaceItemValue( "Subject"        , Subject )
    Call MailDoc.save( True , False ) 'Send it
    session.convertMIME = True
</code>```

Any idea what could I miss?
Thanks

答:
The order I used was:

multipart/mixed
   multipart/alternative
     text/plain
     text/HTML
     application/octet-stream
     application/octet-stream (etc...)
Thanks @Richard

First I've changed

```<code>SetHeaderValAndParams({multipart/alternative;boundary="=NextPart_="})
</code>```

To:

```<code>SetHeaderValAndParams({multipart/mixed;boundary="=NextPart_="})
</code>```

Then the plain text:

```<code>setContentFromText(stream, {text/plain}, ENC_NONE)
</code>```

Then the html:

```<code>setContentFromText(stream, {text/html;charset="iso-8859-1"}, ENC_NONE)
</code>```

Finally:

Repeat as needed... (attachments)

```<code>stream.Open attachFileName, "binary" (attachFileName full path)
mc.SetContentFromBytes(stream, "application/octet-stream", ENC_IDENTITY_BINARY)
</code>```

Title: Lotusscript MIME Email

Body:
I modified a code that I found to send MIME HTML mails with attachments.
It works when the mail is open in gmail, but in Apple Mail or Lotus Notes there isn't any attachment in the body.
The plaintext part does not arrive either, but what interests me are the attachments.

Here is my code:

    Set MailDoc     = New NotesDocument( mailbox )
    session.convertMIME = False
    Dim body As NotesMIMEEntity
    Dim mimeHeader As NotesMIMEHeader
    Dim mimeEntity As NotesMIMEEntity
    Dim stream As NotesStream

Set body = mailDoc.CreateMIMEEntity

    Set mimeHeader = body.CreateHeader({MIME-Version})
    Call mimeHeader.SetHeaderVal("1.0")
    Set mimeHeader = body.CreateHeader("Content-Type")
    Call mimeHeader.SetHeaderValAndParams({multipart/alternative;boundary="=NextPart_="})

    ' create another MIME part for the attachment. (repeat as needed)
    If (docEval.HasItem("$File")) Then
        Dim AttachmentsField As NotesRichTextItem
        Set AttachmentsField = docEval.GetFirstItem( "fc_adjunto" )
        If IsArray(AttachmentsField.EmbeddedObjects) Then ' Isarray validates for attachments ignoring embedded text
            ForAll att In AttachmentsField.EmbeddedObjects
                If att.Type = EMBED_ATTACHMENT Then
                    Call errorLog.LogAction("Inicio attch: " + att.Name())
                    Set mimeEntity = body.CreateChildEntity( )
                    Set mimeHeader = mimeEntity.CreateHeader("Content-Disposition")
                    aliasFilename = CStr(att.Name())
                    Call mimeHeader.SetHeaderValAndParams(|attachment; filename=| & aliasFilename)
                    Set stream = session.CreateStream
                    attachFilename = AttachToFile(session, docEval, CStr(att.Name()))  'Call o.ExtractFile(Attachfoldername & "\" & o.Name())
                    Call errorLog.LogAction("Inicio attch name: " + attachFilename)
                    stream.Open attachFileName, "binary"
                    Call mimeEntity.SetContentFromBytes(stream, "application/octet-stream", ENC_IDENTITY_BINARY)
                    mimeEntity.EncodeContent(ENC_BASE64)
                    Kill attachFilename
                End If
            End ForAll
        End If
    End If

    'Send the plain text part first (this never work for me!!)
    Set mimeEntity = body.createChildEntity()
    Set stream = session.createStream()
    Call WritePlainText(stream)
    Call mimeEntity.setContentFromText(stream, {text/plain;charset="iso-8859-1"}, ENC_IDENTITY_8BIT)

    'Send the HTML part.
    Call stream.Truncate()

    'Send the HTML part.
    Set mimeEntity = body.createChildEntity()
    Call WriteHTML(stream, elHtml)
    Call mimeEntity.setContentFromText(stream, {text/html;charset="iso-8859-1"},ENC_IDENTITY_8BIT)
    'Close the stream and Send it
    Call stream.Truncate()
    Call stream.Close()

    Call maildoc.Closemimeentities(True)

    Call MailDoc.ReplaceItemValue("EncryptOnSend"   , True )
    Call MailDoc.ReplaceItemValue("PostedDate"      , Now )
    Call MailDoc.ReplaceItemValue("From"            , Remitente )
    Call MailDoc.ReplaceItemValue("SendFrom"        , Remitente )
    Call MailDoc.ReplaceItemValue("Principal"       , Remitente )
    Call MailDoc.ReplaceItemValue( "SendTo"         , sendTo )
    Call MailDoc.ReplaceItemValue( "CopyTo"         , copyTo )
    Call MailDoc.ReplaceItemValue( "BlindCopyTo"    , bccTo )
    Call MailDoc.ReplaceItemValue( "Subject"        , Subject )
    Call MailDoc.save( True , False ) 'Send it
    session.convertMIME = True

Any idea what could I miss?
Thanks

Body:
The order I used was:

multipart/mixed
   multipart/alternative
     text/plain
     text/HTML
     application/octet-stream
     application/octet-stream (etc...)
Thanks @Richard

First I've changed

SetHeaderValAndParams({multipart/alternative;boundary="=NextPart_="})

To:

SetHeaderValAndParams({multipart/mixed;boundary="=NextPart_="})

Then the plain text:

setContentFromText(stream, {text/plain}, ENC_NONE)

Then the html:

setContentFromText(stream, {text/html;charset="iso-8859-1"}, ENC_NONE)

Finally:

Repeat as needed... (attachments)

stream.Open attachFileName, "binary" (attachFileName full path)
mc.SetContentFromBytes(stream, "application/octet-stream", ENC_IDENTITY_BINARY)


问:
Reveal input to the left not the right
I have code that shows and reveals an input box to the right of the search icon. I'm looking to have it slide open so the input is on the left side. However, my attempts just make matters worse.

Your assistance is appreciated.

Below is the working example that shows the input box revealing to the right side.

var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click",function(){
    document.querySelector('.search-slide').classList.toggle("active");
   document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click",function(){
   document.querySelector('.search-slide').classList.toggle("active");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}
.search {
  min-width: 18.9375em;
}
.search input[type=submit] {
  vertical-align: middle;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search input[type=submit]:hover {
  opacity: .5;
}
.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}
.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition:width 0.3s ease;
}

.search-slide.active{width:15.5625em}

.search-close {
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search-close:hover {
  opacity: .5;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>

<input type="submit" value="" class="search-btn fa ib-m">

<input type="search" placeholder="Enter your search" class="ib-m">

```
</div>
</div>
</p>

<p>Below is my broken attempt to do what my ultimate goal is:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click",function(){
    document.querySelector('.search-slide').classList.toggle("active");
   document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click",function(){
   document.querySelector('.search-slide').classList.toggle("active");
});</code>```

input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}
.search {
  min-width: 18.9375em;
}
.search input[type=submit] {
  vertical-align: middle;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search input[type=submit]:hover {
  opacity: .5;
}
.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}
.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition:width 0.3s ease;
}

.search-slide.active{width:15.5625em}

.search-close {
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search-close:hover {
  opacity: .5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>
<div class="search">
<input type="search" placeholder="Enter your search" class="ib-m"><div class="search-slide ib-m">
<input type="submit" value="" class="search-btn fa ib-m"><div class="search-close ib-m"><i class="fa fa-times"></i></div>
</div></div></code>```

答:
Not sure if this is what you are looking for, but here it is:

let search_btn = document.querySelector('.search-btn');
let search_div = document.querySelector('.search-div');
let search_input = document.querySelector('input[type=search]');
let search_close = document.querySelector('.search-close');
search_btn.addEventListener("click", function() {
  search_div.classList.add('show');
})

search_close.addEventListener("click", function() {
  search_div.classList.remove('show');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}

.search {
  min-width: 18.9375em;
}

.search input[type=submit] {
  vertical-align: top;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
}

.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}

.search-close {
  display: inline;
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
}

.search-content {
  width: 16rem;
}

.search-div {
  display: inline-block;
  width: 0;
  height: 0;
  overflow: auto;
  transition: width 500ms ease-in-out;
}

.show {
  width: 16rem;
  height: auto;
  overflow: auto;
  transition: width 1000ms ease-in-out;
}</code>```

      <input type="search" placeholder="Enter your search" class="ib-m">

  <input type="submit" value="" class="search-btn fa ib-m">

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />```

Title: Reveal input to the left not the right

Body:
I have code that shows and reveals an input box to the right of the search icon. I'm looking to have it slide open so the input is on the left side. However, my attempts just make matters worse.

Your assistance is appreciated.

Below is the working example that shows the input box revealing to the right side.

var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click",function(){
    document.querySelector('.search-slide').classList.toggle("active");
   document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click",function(){
   document.querySelector('.search-slide').classList.toggle("active");
});

input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}
.search {
  min-width: 18.9375em;
}
.search input[type=submit] {
  vertical-align: middle;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search input[type=submit]:hover {
  opacity: .5;
}
.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}
.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition:width 0.3s ease;
}

.search-slide.active{width:15.5625em}

.search-close {
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search-close:hover {
  opacity: .5;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>

<input type="submit" value="" class="search-btn fa ib-m">

<input type="search" placeholder="Enter your search" class="ib-m">

Below is my broken attempt to do what my ultimate goal is:

var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click",function(){
    document.querySelector('.search-slide').classList.toggle("active");
   document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click",function(){
   document.querySelector('.search-slide').classList.toggle("active");
});

input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}
.search {
  min-width: 18.9375em;
}
.search input[type=submit] {
  vertical-align: middle;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search input[type=submit]:hover {
  opacity: .5;
}
.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}
.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition:width 0.3s ease;
}

.search-slide.active{width:15.5625em}

.search-close {
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search-close:hover {
  opacity: .5;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>

<input type="search" placeholder="Enter your search" class="ib-m">

<input type="submit" value="" class="search-btn fa ib-m">

Body:
Not sure if this is what you are looking for, but here it is:

let search_btn = document.querySelector('.search-btn');
let search_div = document.querySelector('.search-div');
let search_input = document.querySelector('input[type=search]');
let search_close = document.querySelector('.search-close');
search_btn.addEventListener("click", function() {
  search_div.classList.add('show');
})

search_close.addEventListener("click", function() {
  search_div.classList.remove('show');
});

input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}

.search {
  min-width: 18.9375em;
}

.search input[type=submit] {
  vertical-align: top;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
}

.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}

.search-close {
  display: inline;
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
}

.search-content {
  width: 16rem;
}

.search-div {
  display: inline-block;
  width: 0;
  height: 0;
  overflow: auto;
  transition: width 500ms ease-in-out;
}

.show {
  width: 16rem;
  height: auto;
  overflow: auto;
  transition: width 1000ms ease-in-out;
}

<div class="search">
  <div class="search-div">
    <div class="search-content">
      <input type="search" placeholder="Enter your search" class="ib-m">
      <div class="search-close ib-m"><i class="fa fa-times"></i></div>
    </div>
  </div>
  <input type="submit" value="&#xf002;" class="search-btn fa ib-m">
</div>

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />


问:
Why isn't the link between CSS and HTML working?
I'm using flask on atom editor to create a website. In the link I'm referring to the right path where the CSS file is placed, and still when I try loading the page I get it without CSS. I tried changing paths several times it still wouldn't work. After inspecting the web page I noticed an Error 404 file not found referring the CSS file, any ideas? Below is the code:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Flask App</title>
    <link rel="stylesheet"  href="/app4/css/main.css">
  </head>
  <body>
    <header>
      <div class="container">
        <h1 class="logo">Ardit's web app </h1>
        <strong><nav>
          <ul class="menu">
            <li><a href="{{ url_for('home') }}" > Home</a></li>
            <li><a href="{{ url_for('about') }}" > About</a></li>
          </ul>
        </nav></strong>
      </div>
    </header>
    <div class ="container">
      {%block content%}
      {%endblock%}
    </div>
  </body>
  </html>
</code>```

答:
I failed to mention before that I'm using flask to create the website, and that I'm rendering an html template, sorry about that.
The problem was solved after creating a static folder and placed the CSS file inside, after that in the link using the url_for function worked.
I replaced: href="/app4/css/main.css
with: href="{{url_for('static', filename='css/main.css')}}"
and that did the trick. Thanks for the help.</p>

Body:
I'm using flask on atom editor to create a website. In the link I'm referring to the right path where the CSS file is placed, and still when I try loading the page I get it without CSS. I tried changing paths several times it still wouldn't work. After inspecting the web page I noticed an Error 404 file not found referring the CSS file, any ideas? Below is the code:

<!DOCTYPE html>

    <title>Flask App</title>
    <link rel="stylesheet"  href="/app4/css/main.css">

Ardit's web app

 Home

 About

      {%block content%}
      {%endblock%}


问:
Correct setting of Python home and sys.prefix in an embedded environment
Current situation

I embedded Python into my C++ application. The application is installed into the common Application locations on Windows, macOS (C:\Program Files, /Applications/, ...) which require admin privileges to make modifications to these directories. My application also ships with its own Python installation. Here is an example for the packaging structure:

```<code>C:\Program Files\Foo\foo.exe
C:\Program Files\Foo\Lib
C:\Program Files\Foo\DLLs
C:\Program Files\Foo\python.exe
</code>```

The program also sets up an additional user-specific directory, which doesn't require any permissions and which is in sys.path:

```<code>C:\Users\username\AppData\Roaming\Foo\python\libs
</code>```

Problem

During initialization I call PySet_Path, Py_SetPythonHome and I set sys.prefix to Program Files\Foo (as required by the documentation)

If the user installs pip or a module through pip it ends up in this application directory which would requires elevated permissions rights of course. But there is pip install something --user to find a user friendly installation directory (which is the AppData dir in my case).

My question is, which values and combinations should I set to make use of --user? Is it recommended to set the Python home to the AppData directory, and sys.prefix to the Program Files directory?

Because, that would mean the user could use --user to control where certain files are installed to

```<code>C:\Program Files\Foo\python.exe -m pip install xyz --user
would go into the user directory

C:\Program Files\Foo\python.exe -m pip install xyz
would go into the Program Files directory
</code>```

Is this recommended, or am I overseeing any side-effects here?

答:
As you have mentioned that the embedded system ships with its own python environment, thus it is not recommended to use pip to install libraries outside the environment.

That being said,

C:\Program Files\Foo\python.exe -m pip install xyz --user

The above command shall affect the system-wide behaviour of the Python environment for the user, which may lead to unexpected behaviour of the application as well as the Operating System. Also, this installation would mean that the installed application shall behave in a certain way for each user which may or may not be the same.

However,

C:\Program Files\Foo\python.exe -m pip install xyz

using this installation method helps in delivering similar behaviour of the application among users which is subjective as, if anything goes bad for one user, the application stops performing for all the users.

Body:
Current situation

I embedded Python into my C++ application. The application is installed into the common Application locations on Windows, macOS (C:\Program Files, /Applications/, ...) which require admin privileges to make modifications to these directories. My application also ships with its own Python installation. Here is an example for the packaging structure:

C:\Program Files\Foo\foo.exe
C:\Program Files\Foo\Lib
C:\Program Files\Foo\DLLs
C:\Program Files\Foo\python.exe

The program also sets up an additional user-specific directory, which doesn't require any permissions and which is in sys.path:

C:\Users\username\AppData\Roaming\Foo\python\libs

Problem

During initialization I call PySet_Path, Py_SetPythonHome and I set sys.prefix to Program Files\Foo (as required by the documentation)

If the user installs pip or a module through pip it ends up in this application directory which would requires elevated permissions rights of course. But there is pip install something --user to find a user friendly installation directory (which is the AppData dir in my case).

My question is, which values and combinations should I set to make use of --user? Is it recommended to set the Python home to the AppData directory, and sys.prefix to the Program Files directory?

Because, that would mean the user could use --user to control where certain files are installed to

C:\Program Files\Foo\python.exe -m pip install xyz --user
would go into the user directory

C:\Program Files\Foo\python.exe -m pip install xyz
would go into the Program Files directory

Is this recommended, or am I overseeing any side-effects here?


问:
How to force Encryption with valid certificate for SQL server connections?
I configured ForceEncryption to yes and selected the certificate on SQL server.
 It's still allowing the connections from clients that are not passing the valid certificate and clients that are not using encryption.
 What's the point of ForcingEncryption on server if client side configuration can manipulate it ?
How do I configure the SQL server to reject those clients ?

答:
There are too many unknowns here, starting with SQL Server version, the kind of certificate used, the operating system version, TLS version settings in the registry etc. etc.

Please be sure to read the following thoroughly. The feature does work. Just follow the docs. https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/enable-encrypted-connections-to-the-database-engine?view=sql-server-ver15


问:
Function return map with 0 elements in Typescript/Angular
I am new to Angular and working on a sample app, which accepts a property file as input from html, process the files and stores the values in a map using typescript. I am able to store the value in the map but not able to access the map from another component.

File-reader-component.ts

```<code>export class FileReaderComponent {
    static readFileAsMap(file: File): Map<string, string> {
        let map :Map<string, string>= new Map<string, string>();

        let fileReader = new FileReader();
        fileReader.onloadend = (e) => {
            // By lines
            let lines = fileReader.result.toString().split('\n');
            for(let line = 0; line < lines.length; line++){
                if(lines[line].startsWith('#') ||
                    lines[line].startsWith('//') ||
                    ! lines[line].includes('=') ) {
                    // invalid line - ignoring it
                    continue;
                }
                let lineArr = lines[line].split('=');
                let key = lineArr[0].trim();
                let value = lineArr[1].trim();

                map.set(key, value);
                // not checking duplicate keys to let override the config
            }
        };

        fileReader.readAsText(file);
        console.log(map);
        return map;
    }
}
</code>```

In the above file, console.log(map) works fine. But when we call this method in another component(as below) it returns map with 0 elements.

```<code>let config: Map<string, string> = FileReaderComponent.readFileAsMap(configFile);
</code>```

答:
Well first of all, the reason it returns map with 0 elements is because onloadend is called asynchronously. readAsText is itself an asynchronous thing, and when it's done it will call onloadend. There's no real guarantee (in fact it's almost certain not to happen) that it will call it before the return gets executed.

You need to handle this asynchronicity, say via a promise.

Now for the puzzler which is that console.log is non trivial, well that's the browser playing a bit of a trick on you. It console.logs a reference, by the time you look at that reference in the terminal, it has been populated, and the browser 'helpfully' shows it as populated.

To see what I mean, paste this into your terminal

```<code>function f() {
    const x = {};
    console.log(x);
    setTimeout(() => {x[1] = 2})
}
</code>```

and invoke f(), logically you would expect to see {}. But the browser plays its tricks and you see { 1: 2 }

Body:
I am new to Angular and working on a sample app, which accepts a property file as input from html, process the files and stores the values in a map using typescript. I am able to store the value in the map but not able to access the map from another component.

File-reader-component.ts

export class FileReaderComponent {
    static readFileAsMap(file: File): Map<string, string> {
        let map :Map<string, string>= new Map<string, string>();

        let fileReader = new FileReader();
        fileReader.onloadend = (e) => {
            // By lines
            let lines = fileReader.result.toString().split('\n');
            for(let line = 0; line < lines.length; line++){
                if(lines[line].startsWith('#') ||
                    lines[line].startsWith('//') ||
                    ! lines[line].includes('=') ) {
                    // invalid line - ignoring it
                    continue;
                }
                let lineArr = lines[line].split('=');
                let key = lineArr[0].trim();
                let value = lineArr[1].trim();

                map.set(key, value);
                // not checking duplicate keys to let override the config
            }
        };

        fileReader.readAsText(file);
        console.log(map);
        return map;
    }
}

In the above file, console.log(map) works fine. But when we call this method in another component(as below) it returns map with 0 elements.

let config: Map<string, string> = FileReaderComponent.readFileAsMap(configFile);

Body:
Well first of all, the reason it returns map with 0 elements is because onloadend is called asynchronously. readAsText is itself an asynchronous thing, and when it's done it will call onloadend. There's no real guarantee (in fact it's almost certain not to happen) that it will call it before the return gets executed.

You need to handle this asynchronicity, say via a promise.

Now for the puzzler which is that console.log is non trivial, well that's the browser playing a bit of a trick on you. It console.logs a reference, by the time you look at that reference in the terminal, it has been populated, and the browser 'helpfully' shows it as populated.

To see what I mean, paste this into your terminal

function f() {
    const x = {};
    console.log(x);
    setTimeout(() => {x[1] = 2})
}

and invoke f(), logically you would expect to see {}. But the browser plays its tricks and you see { 1: 2 }