Tag Archives: Python

import win32api; Importerror: DLL load failed: the specified program was not found

Error information

(venv) D:\pyvenv_xlwings64\venv>pip list
Package    Version
---------- -------
comtypes   1.1.7
pip        19.2.3
PyQt5      5.13.1
PyQt5-sip  4.19.19
pywin32    225
setuptools 41.2.0
wheel      0.33.6
xlwings    0.15.3

(venv) D:\pyvenv_xlwings64\venv>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import xlwings
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\pyvenv_xlwings64\venv\lib\site-packages\xlwings\__init__.py", line 42, in <module>
    from . import _xlwindows as xlplatform
  File "D:\pyvenv_xlwings64\venv\lib\site-packages\xlwings\_xlwindows.py", line 10, in <module>
    import win32api
ImportError: DLL load failed: the specified program was not found.
>>>

Cause of the problem

There is a problem with the new version 224 and 225. Just go back to version 223

(venv) D:\pyvenv_xlwings64\venv>pip install pywin32==223
Collecting pywin32==223
  Downloading https://files.pythonhosted.org/packages/9f/9d/f4b2170e8ff5d825cd4398856fee88f6c70c60bce0aa8411ed17c1e1b21f/pywin32-223-cp36-cp36m-win_amd64.whl (9.0MB)
     |████████████████████████████████| 9.0MB 218kB/s
Installing collected packages: pywin32
Successfully installed pywin32-223

(venv) D:\pyvenv_xlwings64\venv>
(venv) D:\pyvenv_xlwings64\venv>
(venv) D:\pyvenv_xlwings64\venv>
(venv) D:\pyvenv_xlwings64\venv>pip list
Package    Version
---------- -------
comtypes   1.1.7
pip        19.2.3
PyQt5      5.13.1
PyQt5-sip  4.19.19
pywin32    223
setuptools 41.2.0
wheel      0.33.6
xlwings    0.15.3

(venv) D:\pyvenv_xlwings64\venv>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import xlwings
>>> 

The solution of “importerror: DLL load failed: unable to find the specified module”

import scipy.io as scio
feat = scio.loadmat (datapath)
when I run the above program, I always report an error saying:

Unable to start the solution of “importerror: DLL load failed: unable to find the specified module”

###############################################
solution:
first, uninstall PIP universal SciPy
and then install VC + +: Visual C + + redistributable for visual studio 2015
after installing PIP install SciPy again

I just didn’t unload the VC + + installed directly by SciPy before, and I didn’t succeed all the time/

Centos7 Install virtualenv Error bash: virtualenv: command not found…

After installing python3

1. Install virtualenv with PIP3

pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple virtualenv

The above image has been installed successfully

2. Virtualenv: command not found

3. Add environment variable to solve the problem

(1) Using find/- name ‘ virtualenv.py ‘does it exist

It can be found in the figure below

(2) Add environment variable

Steps:

vim /etc/profile
# Add the following to the bottom of the file
PATH=$PATH:/usr/local/python3/bin

# is the command added to take effect
source /etc/profile

# Finally, check if the file was added successfully
echo $PATH

Example card:

(3)Reuse virtual env

# Use virtualenv to create a python3 environment with the command demo1
virtualenv --python=/usr/bin/python3 demo1
# Go to /demo1/bin under the virtual slow directory and start the virtual environment with the command
source activate

PyDev:warning: Debugger speedups using cython not foun

When debugging code in eclipse, you will always be prompted with a warning:

  

warning: Debugger speedups using cython not found. Run '"C:\Python36\python.exe" "C:\Users\shaoks\.p2\pool\plugins\org.python.pydev.core_6.3.3.201805051638\pysrc\setup_cython.py" build_ext --inplace' to build.
pydev debugger: starting (pid: 15372)

It means: there is no debugger to speed up with Python
Python is an extension module tool of python, which is mixed with Python and C language to speed up the running efficiency of Python.
The solution is also in the above prompt:
in pydev installation directory, execute the following command to compile the cython acceleration module

  

Go to C: users, hooks, P2, pool, plugins\ org.python.pydev .core_ 6.3.3.201805051638

Input command: Python setup_ cython.py build_ Ext — inplace enter, as shown in the following figure:

 

selenium.common.exceptions.WebDriverException: Message: ‘geckodriver’ executable needs to…

Using selenium webriver for the first time, webdriver.Firefox ()

Error report selenium.common.exceptions . webdriverexception: Message: ‘geckodriver’ executable needs to be in path.

Windows processing method:

1. Download geckodriver.exe :

Download address: https://github.com/mozilla/geckodriver/releases
Choose to download according to the system version (such as windows 64 bit system)

2. After downloading and decompressing, the getckodriver.exe Put it in the python installation directory. If you have checked addtopath when installing python, you don’t need to do anything. Otherwise, you need to add the python installation directory to the system variable environment variable path.

3. Run the code again
2

Other browsers have similar processing methods; download address of each browser driver

https://www.seleniumhq.org/about/platforms.jsp#browsers

firefox: https://github.com/mozilla/geckodriver/releases/

chrome: https://code.google.com/p/chromedriver/downloads/list

ie: http://selenium-release.storage.googleapis.com/index.html

Weighted cross entropy loss function: tf.nn.weighted_cross_entropy_with_logits

tf.nn.weighted_cross_entropy_with_logits Function

tf.nn.weighted_cross_entropy_with_logits(
  targets,
  logits,
  pos_weight,
  name=None
)

Defined in: tensorflow/Python/OPS/NN_ impl.py 。

The weighted cross entropy was calculated.

0 Similar to sigmoid?Cross?Entropy?With?Logits () , except POS?U weight It allows people to weigh recall rate and accuracy by weighting up or down the cost of positive error relative to negative error.

0 Generally, the cross entropy cost is defined as:

targets * -log(sigmoid(logits)) +
  (1 - targets) * -log(1 - sigmoid(logits))

Value POS?U weights &> 1 The false negative count is reduced and the recall rate is increased. Instead, set POS?U weights & lt; 1 It can reduce false positive count and improve accuracy. You can see from the following It is introduced as the multiplication coefficient of the positive target term in the loss expression

targets * -log(sigmoid(logits)) * pos_weight +
  (1 - targets) * -log(1 - sigmoid(logits))

For simplicity, let x = Logits, z = targets, q = POS?U weight . The losses are:

 qz * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
= qz * -log(1/(1 + exp(-x))) + (1 - z) * -log(exp(-x)/(1 + exp(-x)))
= qz * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))
= qz * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))
= (1 - z) * x + (qz + 1 - z) * log(1 + exp(-x))
= (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x))

Set L = (1 + (Q – 1) * z) to ensure stability and avoid overflow

(1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0))

Logits and targets must have the same type and shape.

Parameters:

Targets: a tensor with the same type and shape as Logits.

Logits: a tensor of type float32 or float64.

pos_ Weight: the coefficient used in the positive sample.

Name: the name of the operation (optional).

Return:

Tensors with the same shape as Logits with component weighted logic loss.

Possible exceptions:

Valueerror: if Logits and targets do not have the same shape.

[leetcode] 280. Wiggle sort

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] &>= nums[2] <= nums[3]….

For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

To give an array without sorting, reorder it to nums [0] & lt; = nums [1] &> = nums [2] & lt; = nums [3].

Solution: traverse the array, if it is an odd position and its value is larger than the next, then exchange its value, if it is an even position and its value is smaller than the next, then exchange its value. The time complexity is O (n). Note that the difference between the index and the actual position is 1, so the parity is opposite.

Java:

public class Solution {
    public void wiggleSort(int[] nums) {
        if (nums == null || nums.length < 2) return;
        for (int i = 1; i < nums.length; i++) {
            if ((i % 2 == 0 && nums[i] &> nums[i - 1]) || (i % 2 == 1 && nums[i] < nums[i - 1])) {
                int tmp = nums[i];
                nums[i] = nums[i - 1];
                nums[i - 1] = tmp;
            } 
        }
    }
}  

Java:

public class Solution {
    public void wiggleSort(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        for (int i = 1; i < nums.length; i++) {
            if (i % 2 == 1) {
                if (nums[i] < nums[i - 1]) {
                    swap(nums, i);
                } 
            } else {
                if (nums[i] &> nums[i - 1]) {
                    swap(nums, i);
                }
            }
        }
    }
    
    private void swap(int[] nums, int i) {
        int tmp = nums[i - 1];
        nums[i - 1] = nums[i];
        nums[i] = tmp;
    }
}  

Python:

# Time:  O(n)
# Space: O(1)
class Solution(object):
    def wiggleSort(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        for i in xrange(1, len(nums)):
            if ((i % 2) and nums[i - 1] &> nums[i]) or \
                (not (i % 2) and nums[i - 1] < nums[i]):
                # Swap unordered elements.
                nums[i - 1], nums[i] = nums[i], nums[i - 1]

C++:

// Time:  O(n)
// Space: O(1)
class Solution {
public:
    void wiggleSort(vector<int&>& nums) {
        for (int i = 1; i < nums.size(); ++i) {
            if (((i % 2) && nums[i] < nums[i - 1]) ||
                (!(i % 2) && nums[i] &> nums[i - 1])) {
                // Swap unordered elements.
                swap(nums[i], nums[i - 1]);
            }
        }
    }
}; 

C++:

// Time Complexity O(nlgn)
class Solution {
public:
    void wiggleSort(vector<int&> &nums) {
        sort(nums.begin(), nums.end());
        if (nums.size() <= 2) return;
        for (int i = 2; i < nums.size(); i += 2) {
            swap(nums[i], nums[i - 1]);
        }
    }
};

C++:

// Time Complexity O(n)
class Solution {
public:
    void wiggleSort(vector<int&> &nums) {
        if (nums.size() <= 1) return;
        for (int i = 1; i < nums.size(); ++i) {
            if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] &> nums[i - 1])) {
                swap(nums[i], nums[i - 1]);
            }
        }
    }
};

>>

Similar theme:

[LeetCode] Wiggle Sort II free action II

All LeetCode Questions List Total

[LeetCode] 291. Word Pattern II

Given apatternand a stringstr, find ifstrfollows the same pattern.

Herefollowmeans a full match, such that there is a bijection between a letter inpatternand anon-emptysubstring instr.

Examples:

pattern ="abab", str ="redblueredblue"should return true.

pattern ="aaaa", str ="asdasdasdasd"should return true.

pattern ="aabb", str ="xyzabcxzyabc"should return false.

Notes:
You may assume bothpatternandstrcontains only lowercase letters.

290. Word pattern is an extension of word pattern. The difference is that there are no spaces in the word string, so we can’t split the words directly by spaces.

You can use the backtracking method to judge each case, use the hash table to establish the mapping between pattern characters and words, and use the variables p and R to record the position of the current recursive pattern characters and word strings. In the recursive function, if P and R are equal to the length of the pattern string and single word string respectively, it means that the matching is completed successfully, and return to ture. Otherwise, if a If the match is reached and the other one is not, it means that the match failed and returns false.

Solution: backtracking

Python:

# Time:  O(n * C(n - 1, c - 1)), n is length of str, c is unique count of pattern,
#                                there are H(n - c, c - 1) = C(n - 1, c - 1) possible splits of string,
#                                and each one costs O(n) to check if it matches the word pattern.
# Space: O(n + c)

class Solution(object):
    def wordPatternMatch(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        w2p, p2w = {}, {}
        return self.match(pattern, str, 0, 0, w2p, p2w)


    def match(self, pattern, str, i, j, w2p, p2w):
        is_match = False
        if i == len(pattern) and j == len(str):
            is_match = True
        elif i < len(pattern) and j < len(str):
            p = pattern[i]
            if p in p2w:
                w = p2w[p]
                if w == str[j:j+len(w)]:  # Match pattern.
                    is_match = self.match(pattern, str, i + 1, j + len(w), w2p, p2w)
                # Else return false.
            else:
                for k in xrange(j, len(str)):  # Try any possible word
                    w = str[j:k+1]
                    if w not in w2p:
                        # Build mapping. Space: O(n + c)
                        w2p[w], p2w[p] = p, w;
                        is_match = self.match(pattern, str, i + 1, k + 1, w2p, p2w)
                        w2p.pop(w), p2w.pop(p);
                    if is_match:
                        break
        return is_match  

C++:

class Solution {
public:
    bool wordPatternMatch(string pattern, string str) {
        unordered_map<char, string> m;
        return helper(pattern, 0, str, 0, m);
    }
    bool helper(string pattern, int p, string str, int r, unordered_map<char, string&> &m) {
        if (p == pattern.size() && r == str.size()) return true;
        if (p == pattern.size() || r == str.size()) return false;
        char c = pattern[p];
        for (int i = r; i < str.size(); ++i) {
            string t = str.substr(r, i - r + 1);
            if (m.count(c) && m[c] == t) {
                if (helper(pattern, p + 1, str, i + 1, m)) return true;
            } else if (!m.count(c)) {
                bool b = false;
                for (auto it : m) {
                    if (it.second == t) b = true;
                } 
                if (!b) {
                    m[c] = t;
                    if (helper(pattern, p + 1, str, i + 1, m)) return true;
                    m.erase(c);
                }
            }
        }
        return false;
    }
};  

C++:

class Solution {
public:
    bool wordPatternMatch(string pattern, string str) {
        unordered_map<char, string> m;
        set<string> s;
        return helper(pattern, 0, str, 0, m, s);
    }
    bool helper(string pattern, int p, string str, int r, unordered_map<char, string> &m, set<string&> &s) {
        if (p == pattern.size() && r == str.size()) return true;
        if (p == pattern.size() || r == str.size()) return false;
        char c = pattern[p];
        for (int i = r; i < str.size(); ++i) {
            string t = str.substr(r, i - r + 1);
            if (m.count(c) && m[c] == t) {
                if (helper(pattern, p + 1, str, i + 1, m, s)) return true;
            } else if (!m.count(c)) {
                if (s.count(t)) continue;
                m[c] = t;
                s.insert(t);
                if (helper(pattern, p + 1, str, i + 1, m, s)) return true;
                m.erase(c);
                s.erase(t);
            }
        }
        return false;
    }
};

Python skills — XPath helper in Chrome browser

It is used when XPath crawls the web structure. After installation, the shortcut key calls the left Ctrl + Shift + X to start

Installation process:

1. Open Chrome browser and expand the program. Search for XPath helper to download and install (if you need a ladder, because this is a goolge store APP)

With this display, the installation is successful

2. Click Details and check stealth mode