text:
Q: Django - Rating on Multiple Criteria: Model Formset? I have a content that I'd like to rate on multiple criteria.
Imagine this kind of model:
class Content(models.Model):
  name = models.CharField(max_length=50)

class Criteria(models.Model):
  name = models.CharField(max_length=50)
  content = models.ForeignKey(Content)

class ContRate(models.Model):
  user = models.ForeignKey(User, help_text="Who rated ?")
  crit = models.ForeignKey(Criteria)
  rate = models.DecimalField()

The user has a page displaying the content.
From this page, he can also rate the content on the criterias set

Question are:
Do you suggest to use a Model Formset for this purpose ?
Or should I do a simple Ajax form to post the ratings ?
Any why should I do this ?

A: I would use a model formset for this kind of problem although you are not going to use my_formset.is_valid() nor my_formset.save() but because it ease the forms construction in the view and the render in the template.
No need to worry with the form prefixes etc.
Your Ajax call on the onclick event (fired by a click on a star) should call a view with the ContRate pk (if present) and the rate as parameters.
The view will instanciate a ContRateForm (the same used in your previous modelformset_factory) whith those parameters, use the usual mechanisms of ModelForm validation and database insert/update and finally render a json response.


text:
Q: Check if it is possible to reach a number by making jumps of given length? Given a starting position k and two jump sizes d1 and d2, our task is to find the minimum number of jumps needed to reach x if it is possible.
Input : k = 10, d1 = 4, d2 = 6 and x = 8
Output : 2
1st step 10 + d1 = 14
2nd step 14 - d2 = 8

Input : k = 10, d1 = 4, d2 = 6 and x = 9
Output : -1
-1 indicates it is not possible to reach x.

My code for above problem by recursion is :
from itertools import product

def position(k, d1, d2, p, count):
    count += 1
    arr = [[k], ['+', '-'], [d1, d2]]
    x = list(product(*arr))
    for i in range(len(x)):
        if x[i][1] == '+':
            x[i] = x[i][0] + x[i][2]
        else:
            x[i] = x[i][0] - x[i][2]

        if x[i] == p:
            return count

    for i in range(2):
        position(x[i], d1, d2, p, count)

if __name__ == "__main__":
    y = [int(i) for i in input().split()]
    k = y[0]
    d1 = y[1]
    d2 = y[2]
    p = y[3]
    print(position(k, d1, d2, p, 0))

For input: 10 4 6 8
x = [(10,'+',4), (10,'+',6), (10,'-',4), (10,'-',6)]

After that, x = [14,16,6,4]. And count = 1. Checking if each element of x equal to 8. Now the x is recalled for 1st argument of position() as 14 & 16 like:
For 14:
x = [(14,'+',4), (14,'+',6), (14,'-',4), (14,'-',6)]

then, x = [18,20,10,8] now count become 2 and 8 is found at 4th index.
But the problem is that my code misses the recursion of 14 4 6 8 and None is printed on the console. Also, I'm not able to figure out how to return -1 if it is not possible to reach x from my position().

A: You can formulate this as an integer linear program and then solve it using a tool like PuLP or Pyomo.
The idea is that you need to select nonnegative integers up1, down1, up2 and down2 such that up1*d1 - down1*d1 + up2*d2 - down2*d2 == p. Further, you want to select values for these variables that minimize the total number of steps up1 + down1 + up2 + down2.
Here's an example using PuLP (based loosely on this tutorial):
from pulp import *

def position(k, d1, d2, p):
    prob = LpProblem("Minimum Steps", LpMinimize)

    # define decision variables (values to be chosen by solver)
    up1 = LpVariable('up1', lowBound=0, cat='Integer')
    down1 = LpVariable('down1', lowBound=0, cat='Integer')
    up2 = LpVariable('up2', lowBound=0, cat='Integer')
    down2 = LpVariable('down2', lowBound=0, cat='Integer')

    # define objective function (expression to minimize)
    num_steps = up1 + down1 + up2 + down2
    prob += num_steps

    # define main constraint (rule to enforce)
    prob += (k + up1*d1 - down1*d1 + up2*d2 - down2*d2 == p)

    # solve with a time limit, because otherwise CBC may search forever
    prob.solve(PULP_CBC_CMD(maxSeconds=2))

    # if you have CPLEX installed, it can detect infeasibility immediately
    # prob.solve(CPLEX_CMD())

    status = LpStatus[prob.status]
    solution = [str(k)]
    if status == 'Optimal':
        # report steps
        steps = [
            (1, up1, 'd1'), (-1, down1, 'd1'),
            (1, up2, 'd2'), (-1, down2, 'd2')
        ]
        for (sign, v, step) in steps:
            if v.varValue > 0:
                solution.append('-' if sign < 0 else '+')
                solution.append('{} * {}'.format(int(v.varValue), step))
        solution.extend(['=', str(p)])
        print(' '.join(solution))
        return int(num_steps.value())
    elif status in {'Infeasible', 'Not Solved', 'Undefined'}:
        # infeasible or timed out (probably infeasible)
        return -1
    else:
        raise RuntimeError("Problem status was {}".format(status))

print(position(10, 4, 6, 8))
# 10 + 1 * d1 - 1 * d2 = 8
# 2
print(position(10, 4, 6, 9))
# -1
print(position(10, 171, 53, 8))
# 10 - 9 * d1 + 29 * d2 = 8
# 38
print(position(10, 3, 4, 1000000001))
# 10 + 1 * d1 + 250000000 * d2 = 1000000001
# 250000001

Integer linear program solvers use a branch-and-bound technique. They first find the best solution with fractional values for the variables (number of steps), then successively divide the allowed region into smaller sections with integer edges, and eventually stop when they find the best solution at an edge.
For small values of k, d1, d2 and p, this should find a solution very quickly (as should a brute-force recursive solution). But for infeasible problems, the naive approach can go on forever (as does a brute-force recursive solution). The commercial solvers (e.g., CPLEX or Gurobi) can identify this infeasibility and quickly return, but the open-source solvers (CBC or GLPK) may run for a very long time or forever (I waited a few minutes and gave up).
I resolved this problem here by using a time limit on the solver and assuming the problem was infeasible if no solution was found before the limit. You could do something similar in your recursive approach, e.g., set a limit on the number of steps to take. Even if you need thousands or millions of steps, the linear programming approach tends to do OK (see last example), because it homes in close to the right solution quickly and then refines to get an exact match.  I would guess that the recursive approach will take too long in this case. But you may be able to devise cases where the linear programming approach fails to find a solution within the time limit, even if a solution exists.
... After further checking, I've found that the CBC solver does not perform well when the problem is numerically ill-defined or requires a lot of branches. For example, this times out, even though an answer is possible: position(10, 100000, 100001, 10000000). And this reports an invalid answer: position(10, 10000000, 10000001, 10000000) (it's happy to use the almost-true answer 10 + 1 * d2 = 10000000). On the other hand, these cases may also be very hard to solve via a brute-force method. So maybe thinking deeper into the nature of the problem will help. (I'll try to do that later, but I've already been nerd-sniped for too long today!)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wifi Connection up and down Kubuntu 13.04 Currently I am using an ethernet cable.
The problem is that my wifi connection is up and down, sometimes it works sometimes it doesn't.  I get a list of networks to choose from and instead of connecting, the wpa2 password box for my wireless router keeps popping up.
I am running Kubuntu 13.04 on my ASUS X501A, I am assuming there is a problem with my driver, but I just cannot seem to pinpoint issue. I'm sorry if this is posted elsewhere any help with my issue would be much appreciated other than this I love the new release.

A: You need to rest you router, then try to turn on your wifi to get the signal. "A message will indicate if you are connected or not"; then if you need repository driver for your wifi installed in your unit, you better update it for better performance.


text: Q: Wifi keeps dropping on MacBook Pro with Ubuntu 15.10 For some reason the wifi drops periodically every 15 or so minutes. I have the Broadcom BCM4360 and using the driver installed from bcmwl-kernel source.


text:
Q: How to implement custom fonts to a custom keyboard to use on other apps? I am coding in Swift 5.0. I want to create an app where users can download custom fonts and use them in any app. I am using a keyboard extension to do that.
Here is my code
class KeyboardViewController: UIInputViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    let button = createButton(title: "A")
    self.view.addSubview(button)
}

func createButton(title: String) -> UIButton {
    let button = UIButton(type: .system)
    button.frame = CGRect(x: 0,y: 0,width: 20,height: 20)
    button.setTitle(title, for: .normal)
    button.sizeToFit()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.titleLabel?.font = UIFont(name: "Montague.ttf", size: 15)
    button.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
    button.setTitleColor(UIColor.darkGray, for: .normal)
    button.addTarget(self, action: #selector(didTapButton(sender:)), for: .touchUpInside)

    return button
}

@objc func didTapButton(sender: AnyObject) {
     let button = sender as! UIButton
     button.titleLabel?.font = UIFont(name: "Montague.ttf", size: 15)
     let title = button.title(for: .normal)
     textDocumentProxy.insertText(title!)
}

Here is the output.result
So my question is how to make a keyboard button appearance and output in the font I want?

A: You can customize your button's title font using the titleLabel attribute of button.
button.titleLabel?.font = UIFont(name: "YourCustomFont", size: 10.0)

You can't change font on the output as app developers decide what fonts they want to use in their app AFAIK.
Edit: Well I didn't know what you meant by setting the output, for more info about the app you linked to please read this SO post:
How to Insert NSAttributedString using custom keyboard extension?
tl;dr: You can't set a custom font, those apps use unicodes and if you choose to, you should too.


text:
Q: How can I search a subset of a tree efficiently in mongo? I have data in a Mongo database collection where each document has the id of a parent. If I want to search all documents that have a particular document (I'll refer to it as P) in its ancestry (ie P is it's parent, grandparent, great grandparent, etc), what are my options to do that efficiently, and what are those options strengths and weaknesses?
I can think of the following:

*

*Store the whole ancestry in each document, so you can search for documents who's ancestry list contains P.

*

*Strengths:

*

*constant time look up

*Weaknesses:

*

*If a parent is changed, the corresponding update is O(n), where n is the number of descendants of the document who's parent changed

*Some storage overhead, O(a) where a is the average depth of a document

*When searching, first build a list of the ids of P's child documents, then grandchild documents, etc. Then search all documents with those ids

*

*Strengths:

*

*No change is needed to the storage structure, no additional space overhead

*Weaknesses:

*

*Building up the list of ids is an O(n) operation, where n is the number of documents descendant from P

*Searching by possibly hundreds of ids might not be efficient

Anyone know other techniques?

A: To normalize or not to normalize; I believe thats the NoSQL underbelly that often gets people turning back to SQL /RDBMS. I prefer not to normalize in order to provide near-real-time indexed simple queries with basic backend and frontend code. Heres some pseudocode in a related question that shows the complex code needed when normalizing. Its hard to emulate joins and relationships in NoSQL.
Granted NoSQL does open up a bonafide rats nest of issues like your "If a parent is changed, the corresponding update is O(n), where n is the number of descendants of the document who's parent changed" I call those 'relational maintenance scripts'. But I find you can run those on a scheduled (crontab) basis during off-hours. One might also strongly consider safe tables/collections and build volatile or working tables. See this question regarding OLAP tables. There you can have your relationships in nice neat tables and then create those ugly fast collections.
Its a matter of determining whether NoSQL is really for you. Even on a personal level, do you prefer faster, scalable and messy -- or slower, unscalable and neat/organized. The tradeoffs resembling the classic fast, good and cheap triangle. Basically, NoSQL is fast and cheap; SQL is good. NoSQL's good is scalability; while SQL's fast is actually respectable.


text:
Q: C programming socket sendto network is unreachable I'm trying to send a UDP packet to an address contained in argv[1] that can be either IPv4, IPv6, or a hostname. The UDP packet sends successfully when the address is IPv4, but when I use the hostname or the IPv6 address, sendto() throws errno 101 "sendto: Network is unreachable". Why is the network unreachable only when I do not use an IPv4? I'm running ubuntu 14.04 if that helps at all.
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#include <netdb.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[]) {
    int sockfd, ret;
    struct addrinfo ai_hints;
    struct addrinfo *ai_results;

    /* create an IPv6 UDP socket */
    sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        perror("socket");
        return 1;
    }

    /* find UDP IPv6 addresses from command line arg */
    memset(&ai_hints, 0, sizeof(ai_hints));
    ai_hints.ai_family = AF_INET6;
    ai_hints.ai_socktype = SOCK_DGRAM;
    ai_hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG; /* defaults */

    ret = getaddrinfo(argv[1], "12345", &ai_hints, &ai_results);
    if (ret != 0) {
        fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(ret));
        return 1;
    }

    ret = sendto(
        sockfd, "Hello World", 11, 0,
        ai_results->ai_addr, ai_results->ai_addrlen
    );
    if (ret == -1) {
        printf("errno: %i\n",errno);
        perror("sendto");
        return 1;
    }
}


text:
Q: React Native - fetch method post to Laravel return exception MethodNotAllowedHttpException I am trying to make a post request with fetch in React Native to Laravel api and it returns this error to me.
{'message':"",'exception':Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException","file":....

Api.js (React Native):
'use strict';

var baseUrl = 'http://dot.test.192.168.1.125.xip.io/api/';

export default {

    //token = Bearer OxtHDFRWuCxWpIK9omt30fG2RivWeFtAY8VWOzlPcYh9WvX6P8Jq7OrFU4hh
    post: function(url, data, token) {
        let opt = {
            method: 'post',
            body: JSON.stringify(data),
            headers: new Headers({
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                //'Content-Type': 'application/x-www-form-urlencoded'
            })
        };

        return fetch(baseUrl + url, opt);
    }

};

Laravel -
api.php
Route::namespace('Api')->middleware('auth:api')->group(function () {
   Route::post('expert/{id}/feedback', 'FeedbackController@ask');
});

feedbackController.php
<?php

namespace App\Http\Controllers\Api;

use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\RequestFeedback;
use App\Http\Requests\Feedback\PostFeedbackAnswer;
use App\Services\FeedbackService;
use App\Http\Controllers\Controller;

class FeedbackController extends Controller
{
    private $feedbackService;

    public function __construct(FeedbackService $feedbackService)
    {
        $this->feedbackService = $feedbackService;
    }

    public function ask(RequestFeedback $request, $expertId)
    {
        $feedback = $this->feedbackService->ask($request->only('text', 'project_id'), $expertId);

        return $feedback;
    }

}

I change VerifyCsrfToken with
protected $except = [
   'api' => '*',
   '/api/*'
];

I do not understand why it does not work...
I do not publish more code that does not let me send the question.

A: Change POST to GET.
var baseUrl = 'http://dot.test.192.168.1.125.xip.io/api/';

export default {

    //token = Bearer OxtHDFRWuCxWpIK9omt30fG2RivWeFtAY8VWOzlPcYh9WvX6P8Jq7OrFU4hh
    post: function(url, data, token) {
        let opt = {
            method: 'GET',
            body: JSON.stringify(data),
            headers: new Headers({
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                //'Content-Type': 'application/x-www-form-urlencoded'
            })
        };

        return fetch(baseUrl + url, opt);
    }

};


text:
Q: How do I determine what size of hard drive my computer will support? I'm looking for a new hard drive for my machine, because I'm running out of space on the old one.  I'm hoping to get the largest drive possible, because that way I don't have to buy another one for a while.
The difficulty is, I don't know how to find out what the motherboard supports in terms of sizes.  Unless I'm missing something obvious, the spec sheet (this page in my case, though I was also wondering more generally) only tells me how many slots it has rather than what drive capacity it is willing to read.
How can I find out?

A: To keep things simplest and most compatable and problem free, add any SATA drive of up-to 2Terrabytes to the Intel sata ports on the board, and configure and format for basic disks (not dynamic) with standard MBR type formatting methods.  A single primary partition, and any logical partitions in the extended space you want.
Like Akira said it will work with anything out there, keeping it under 2T just makes it simpler in the XP and Win7 systems.
Going further into suggestions, but to complicate it : If you keep both drives in the system. What I like to do is Clone the smaller drive over to the larger drive, have a "system primary first partition" on both drives, the old one as the backup. Then from the motherboard Boot menu , you can hop back to an older yet operational system anytime if the other system fails completly.  The older drives system partition can be re-cloned to update it again and again (backup).
If the new drive fails (unlikely) or the system in the new drive is crippled or damaged (likely), this cloned backup can be returned. increasing OS survivability many times over :-)


text:
Q: How to realize a RW lock with multithreading gRPC? I am trying to write a simple multi-threading server-client stock trading Python program with gRPC and concurrent.future.ThreadPoolExecutor
The server will run a specific number of threads, performs Lookup() and Trade() request sent from clients. The server will maintain a list. That means Lookup() should set read lock, and Trade() should set write lock.
However, it seems that the documentation of gRPC doesn't mention anything about RW lock. Is ThreadPoolExecutor thred-safe?
Any suggestion is appreciated!

A: A threadPoolExecutor with a max_workers greater than 1 requires that your only submit functions that reference thread-safe shared state only. For instance, you should not mutate a global variable from multiple jobs submitted to the thread pool, thus you must protect this with some kind of synchronization primitive.
# /!\ Not thread-safe

from concurrent.futures import ThreadPoolExecutor

def mutate_value():
  global some_value
  some_value += 1

some_value = 0

with ThreadPoolExecutor(max_workers=2) as e:
  e.submit(mutate_value)
  e.submit(mutate_value)

# Thread-safe

from concurrent.futures import ThreadPoolExecutor
from threading import Lock

lock = Lock()

def mutate_value():
  global some_value

  with lock:
    some_value += 1

some_value = 0

with ThreadPoolExecutor(max_workers=2) as e:
  e.submit(mutate_value)
  e.submit(mutate_value)


text:
Q: Count lines of code in directory using Python I have a project whose lines of code I want to count. Is it possible to count all the lines of code in the file directory containing the project by using Python?

A: Here's a function I wrote to count all lines of code in a python package and print an informative output. It will count all lines in all .py
import os

def countlines(start, lines=0, header=True, begin_start=None):
    if header:
        print('{:>10} |{:>10} | {:<20}'.format('ADDED', 'TOTAL', 'FILE'))
        print('{:->11}|{:->11}|{:->20}'.format('', '', ''))

    for thing in os.listdir(start):
        thing = os.path.join(start, thing)
        if os.path.isfile(thing):
            if thing.endswith('.py'):
                with open(thing, 'r') as f:
                    newlines = f.readlines()
                    newlines = len(newlines)
                    lines += newlines

                    if begin_start is not None:
                        reldir_of_thing = '.' + thing.replace(begin_start, '')
                    else:
                        reldir_of_thing = '.' + thing.replace(start, '')

                    print('{:>10} |{:>10} | {:<20}'.format(
                            newlines, lines, reldir_of_thing))

    for thing in os.listdir(start):
        thing = os.path.join(start, thing)
        if os.path.isdir(thing):
            lines = countlines(thing, lines, header=False, begin_start=start)

    return lines

To use it, just pass the directory you'd like to start in. For example, to count the lines of code in some package foo:
countlines(r'...\foo')

Which would output something like:
     ADDED |     TOTAL | FILE
-----------|-----------|--------------------
        5  |        5  | .\__init__.py
       539 |       578 | .\bar.py
       558 |      1136 | .\baz\qux.py

A: from os import listdir
from os.path import isfile, join

def countLinesInPath(path,directory):
    count=0
    for line in open(join(directory,path), encoding="utf8"):
        count+=1
    return count

def countLines(paths,directory):
    count=0
    for path in paths:
        count=count+countLinesInPath(path,directory)
    return count

def getPaths(directory):
    return [f for f in listdir(directory) if isfile(join(directory, f))]

def countIn(directory):
    return countLines(getPaths(directory),directory)

To count all the lines of code in the files in a directory, call the "countIn" function, passing the directory as a parameter.

A: This is derived from Daniel's answer (though refactored enough that this won't be obvious). That one doesn't recurse through subdirectories, which is the behavior I wanted.
from os import listdir
from os.path import isfile, isdir, join

def item_line_count(path):
    if isdir(path):
        return dir_line_count(path)
    elif isfile(path):
        return len(open(path, 'rb').readlines())
    else:
        return 0

def dir_line_count(dir):
    return sum(map(lambda item: item_line_count(join(dir, item)), listdir(dir)))

A: Here's another one, using pathlib. Lists individual (relative) file paths with line count, total number of files, and total line count.
import pathlib

class LoC(object):
    suffixes = ['.py']
    skip = ['name of dir or file to skip', ...]

    def count(self, path, init=True):
        path = pathlib.Path(path)
        if path.name in self.skip:
            print(f'skipped: {path.relative_to(self.root)}')
            return
        if init:
            self.root = path
            self.files = 0
            self.lines = 0
        if path.is_dir():
            # recursive case
            for item in path.iterdir():
                self.count(path=item, init=False)
        elif path.is_file() and path.suffix in self.suffixes:
            # base case
            with path.open(mode='r') as f:
                line_count = len(f.readlines())
            print(f'{path.relative_to(self.root)}: {line_count}')
            self.files += 1
            self.lines += line_count
        if init:
            print(f'\n{self.lines} lines in {self.files} files')

Note I omitted the __init__ method for clarity.
Usage example:
loc = LoC()
loc.count('/path/to/your/project/directory')

A: pygount will display all the files in the folder, each with a count of codes lines (excluding documentation)
https://pypi.org/project/pygount/
pip install pygount

To list the results for the current directory run:
pygount ~/path_to_directory

A: As an addition to the pygount answer, they just added the option --format=summary to get the total number of lines in different file types in a directory.
pygount --format=summary ./your-directory

could output somthing like
  Language     Code    %     Comment    %
-------------  ----  ------  -------  ------
XML            1668   48.56       10    0.99
Python          746   21.72      150   14.90
TeX             725   21.11       57    5.66
HTML            191    5.56        0    0.00
markdown         58    1.69        0    0.00
JSON             37    1.08        0    0.00
INI              10    0.29        0    0.00
Text              0    0.00      790   78.45
__duplicate__     0    0.00        0    0.00
-------------  ----  ------  -------  ------
Sum total      3435             1007

A: If you want to count how many lines are in your project, create a script inside of your project folder and paste the following into it:
import os

directory = "[project_directory]"
directory_depth = 100 # How deep you would like to go
extensions_to_consider = [".py", ".css"]  # Change to ["all"] to include all extensions
exclude_filenames = ["venv", ".idea", "__pycache__", "cache"]
skip_file_error_list = True

this_file_dir = os.path.realpath(__file__)

print("Path to ignore:", this_file_dir)
print("=====================================")
def _walk(path, depth):
    """Recursively list files and directories up to a certain depth"""
    depth -= 1
    with os.scandir(path) as p:
        for entry in p:

            skip_entry = False
            for fName in exclude_filenames:
                if entry.path.endswith(fName):
                    skip_entry = True
                    break

            if skip_entry:
                print("Skipping entry", entry.path)
                continue

            yield entry.path
            if entry.is_dir() and depth > 0:
                yield from _walk(entry.path, depth)

print("Caching entries")
files = list(_walk(directory, directory_depth))
print("=====================================")

print("Counting Lines")
file_err_list = []
line_count = 0
len_files = len(files)
for i, file_dir in enumerate(files):

    if file_dir == this_file_dir:
        print("=[Rejected file directory", file_dir, "]=")
        continue

    if not os.path.isfile(file_dir):
        continue

    skip_File = True
    for ending in extensions_to_consider:
        if file_dir.endswith(ending) or ending == "all":
            skip_File = False

    if not skip_File:
        try:
            file = open(file_dir, "r")
            local_count = 0
            for line in file:
                if line != "\n":
                    local_count += 1
            print("({:.1f}%)".format(100*i/len_files), file_dir, "|", local_count)
            line_count += local_count
            file.close()
        except:
            file_err_list.append(file_dir)
            continue
print("=====================================")
print("File Count Errors:", len(file_err_list))
if not skip_file_error_list:
    for file in file_err_list:
        print(file_err_list)

print("=====================================")
print("Total lines |", line_count)

There's probably faster and more efficient ways to do this, but this is a nice start.
Variable Information
directory is the project directory you want to be counted
directory_depth is how deep within the project infastructure
i.e. a depth of 3 would mean it will only scan the following depth:

*

*project_dir

*

*sub_dir

*

*sub2_dir

extensions_to_consider is the file extensions to count code. If you only want to count .py files, you set extensions_to_consider = [".py"]
exclude_filenames is an array of file names (and directories) you don't want to consider the script to count code for.
skip_file_error_list is a boolean variable. If you wish to see a printout of all errors while counting, set to True. Otherwise set to False.
How To Run
Run script using the Python compiler.
To run in terminal
python path_to_file.py
or
python3 path_to_file.py

A: This has a slight air of homework assignment :-) -- nonetheless, it's a worthwhile exercise, and Bryce93's formatting is nice. I think many would be unlikely to use Python for this given that it can be done quickly with a couple of shell commands, for example:
cat $(find . -name "*.py") | grep -E -v '^\s*$|^\s*#' | wc -l

Note that none of these solutions accounts for multiline (''') comments.

A: Based on Bryce93's answer, with code_only option to exclude comments, docstrings, and empty lines from line count:
import os

def countlines(rootdir, total_lines=0, header=True, begin_start=None,
               code_only=True):
    def _get_new_lines(source):
        total = len(source)
        i = 0
        while i < len(source):
            line = source[i]
            trimline = line.lstrip(" ")

            if trimline.startswith('#') or trimline == '':
                total -= 1
            elif '"""' in trimline:  # docstring begin
                if trimline.count('"""') == 2:  # docstring end on same line
                    total -= 1
                    i += 1
                    continue
                doc_start = i
                i += 1
                while '"""' not in source[i]:  # docstring end
                    i += 1
                doc_end = i
                total -= (doc_end - doc_start + 1)
            i += 1
        return total

    if header:
        print('{:>10} |{:>10} | {:<20}'.format('ADDED', 'TOTAL', 'FILE'))
        print('{:->11}|{:->11}|{:->20}'.format('', '', ''))

    for name in os.listdir(rootdir):
        file = os.path.join(rootdir, name)
        if os.path.isfile(file) and file.endswith('.py'):
            with open(file, 'r') as f:
                source = f.readlines()

            if code_only:
                new_lines = _get_new_lines(source)
            else:
                new_lines = len(source)
            total_lines += new_lines

            if begin_start is not None:
                reldir_of_file = '.' + file.replace(begin_start, '')
            else:
                reldir_of_file = '.' + file.replace(rootdir, '')

            print('{:>10} |{:>10} | {:<20}'.format(
                    new_lines, total_lines, reldir_of_file))

    for file in os.listdir(rootdir):
        file = os.path.join(rootdir, file)
        if os.path.isdir(file):
            total_lines = countlines(file, total_lines, header=False,
                                     begin_start=rootdir, code_only=code_only)
    return total_lines

A: Use radon
python3 -mpip install radon

radon raw -s pkg_dir/

** Total **
    LOC: 2994
    LLOC: 1768
    SLOC: 1739
    Comments: 71
    Single comments: 29
    Multi: 818
    Blank: 408
    - Comment Stats
        (C % L): 2%
        (C % S): 4%
        (C + M % L): 30%

it will also calculate cyclomatic complexity
a@debian:~/build/clean/scte35-threefive$ radon cc  -a threefive
threefive/base.py
    M 61:4 SCTE35Base.kv_clean - A
    M 85:4 SCTE35Base.load - A
    M 95:4 SCTE35Base._chk_var - A
    C 9:0 SCTE35Base - A
    M 34:4 SCTE35Base.as_hms - A
    M 79:4 SCTE35Base._chk_nbin - A
    M 17:4 SCTE35Base.__repr__ - A
    M 20:4 SCTE35Base.as_90k - A
    M 27:4 SCTE35Base.as_ticks - A
    M 48:4 SCTE35Base.get - A
    M 54:4 SCTE35Base.get_json - A
threefive/bitn.py
    C 9:0 BitBin - A
    M 30:4 BitBin.as_int - A
    M 47:4 BitBin.as_charset - A
    C 99:0 NBin - A
    M 133:4 NBin.add_int - A
    M 170:4 NBin.reserve - A

      .....
246 blocks (classes, functions, methods) analyzed.
Average complexity: A (1.9024390243902438)


text:
Q: Check the repeated words in a string and keep a count in javascript I am trying to find repeated words in a string and keep a count of how many times it was repeated.
How do I do it in javascript.

 let checkWords = "I am not gonna live forever, but I wanna live while I am alive";

I am looking for output like this I = 3, am = 2, not = 1 and so on, also is it possible to find the individual letter as I = 3, a = 6, m = 2.
I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here

let str = "I am not gonna live forever, but I wanna live while I am alive",
    split = str.split(" "),
    obj = {};

for (let i = 0; i < split.length; i++) {
  if (obj[split[i]] === undefined) {
    obj[split[i]] = 1;
  } else {
    obj[split[i]]++;
  }
}

console.log(obj)

A: Firstly convert the given string to an array. To do that use string.split("").
Secondly, create an map which will store word as key and count as value.
Now iterate through the stringArray and store the current word to the map. And increase the count for the word each time the word is found.
Check the below code.
let words = "I am not gonna live forever, but I wanna live while I am alive";

function countRepeatedWords(sentence) {
  let words = sentence.split(" ");
  let wordMap = {};

  for (let i = 0; i < words.length; i++) {
    let currentWordCount = wordMap[words[i]];
    let count = currentWordCount ? currentWordCount : 0;
    wordMap[words[i]] = count + 1;
  }
  return wordMap;
}

console.log(countRepeatedWords(words));

I hope this helps you.

A: let checkWords = "I am not gonna live forever, but I wanna live while I am alive"

const newStr = checkWords.split(' ').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})

const newStr2 = checkWords.split('').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})

{newStr} for counter words
{newStr2} for counter letters

A: How to count the number of times each word appears in a string:

*

*strip punctuation from the string with .replace()

*change all character to lowercase with .toLowerCase()

*convert string into array of words with .split()

*loop through each word (.forEach), adding it to a word count object

const result = document.getElementById('result');

let str = "I am not gonna live forever, but I wanna live while I am alive.";

// strip all punctuation from string
let strStripped = str.replace(/[,.!]/g, '');
result.innerHTML = `strStripped: "${strStripped}"\n`;

// separate string into array of lowercase words
let words = strStripped.toLowerCase().split(' ');
result.innerHTML += 'words: ' + JSON.stringify(words, null, 2);

// form object of word counts
let wordCounts = {};
words.forEach(word => {
  wordCounts[word] = (wordCounts[word] || 0) + 1;
});
result.innerHTML += '\nwordCounts: ' +
  JSON.stringify(wordCounts, null, 2);


text:
Q: Windows 10 is running slow / upgrade ideas I need your advice. I have installed Windows 10 about 2 months ago, I see it is running
slower every day, it takes ages to shut down or start some program.
User Interface becomes not responsive sometimes
I have installed several
"heavy" applications, MS Visual Studio 17, 19, Office 16, DataGrip, Adobe Reader.
My Task Manager displays 100% CPU usage most of time and 80% of memory. It seems that it consumes
all available CPU and memory regardless of how many applications are running
Can you suggest how can I improve performance of my Windows?
I am looking at:

*

*Removing some services

*Putting Windows to SDD drive (currently I have 200 Gb HDD drive)

*Increasing DIMM memory ( currently I have 7 GB)

*Upgrade CPU (Intel64 Family 6 Model 23 Stepping 6 Intel(R) Core(TM)2 Duo CPU E8400@3.00GHz)

Please share your ideas

A: You should consider upgrading your CPU first. A Core 2 Duo is reaaaally old, and you can get a decent i5 (or even i7) nowadays without any problem. The main objective is to have more than 2 poor cores.
Regarding the RAM, it could be helpful to upgrade it to (at least) 16Go. You can find some cheap RAM (don't go for the high frequencies, only purist can see the real difference imho).
The disk is also an important upgrade part. As you said, having an SSD for the system would be really helpful. Using a SSD removes the problem of the slow magnetic head going through the whole disk.
Btw notice that we won't do any piece suggestion here, and your question should have been asked to Super User instead of Server Fault.


text:
Q: React native geolocation service not working for iOS I am trying to get device current position in react native. I am using below library for get the location:
react-native-geolocation-service

My code:
try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            title: 'Device current location permission',
            message:
              'Allow app to get your current location',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK',
          },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          this.getCurrentLocation();
        } else {
          console.log('Location permission denied');
        }
      } catch (err) {
        console.warn(err);
      }
     }

getCurrentLocation(){
     Geolocation.requestAuthorization();
     Geolocation.getCurrentPosition(
        (position) => {
            alert(position.coords.latitude);
            this.socket.emit('position', {
               data: position,
               id: this.id,
             });
        },
        (error) => {
          alert("map error: "+error.message);
            console.log(error.code, error.message);
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
   }

Android is working fine and getting the correct location but for IOS it's not working Also, it's not asking for allow location persmission. I am getting below error:
PERMISSION_DENIED: 1
POSITION_UNAVAILABLE: 2
TIMEOUT: 3
code: 3
message: "Unable to fetch location within 15.0s."

This is my info.plist:
<key>NSLocationWhenInUseUsageDescription</key>
<string>$(PRODUCT_NAME) would like to access your location.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>$(PRODUCT_NAME) would like to access your location.</string>

This is background modes from xcode

A: I have used the react-native-geolocation-service for getting user current location here is my code
App.js:
import Geolocation from 'react-native-geolocation-service';

async componentDidMount() {
 if(Platform.OS === 'ios'){
      this.getCurrentLocation();
    }else{
      try {
       const granted = await PermissionsAndroid.request(
         PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
         {
           title: 'Device current location permission',
           message:
             'Allow app to get your current location',
           buttonNeutral: 'Ask Me Later',
           buttonNegative: 'Cancel',
           buttonPositive: 'OK',
         },
       );
       if (granted === PermissionsAndroid.RESULTS.GRANTED) {
         this.getCurrentLocation();
       } else {
         console.log('Location permission denied');
       }
     } catch (err) {
       console.warn(err);
     }
    }
}

getCurrentLocation(){
    Geolocation.requestAuthorization();
    Geolocation.getCurrentPosition(
       (position) => {
           console.log(position);
       },
       (error) => {
         console.log("map error: ",error);
           console.log(error.code, error.message);
       },
       { enableHighAccuracy: false, timeout: 15000, maximumAge: 10000 }
   );
  }

MapScreen.js
import Geolocation from 'react-native-geolocation-service';

componentDidMount() {
  this.updateCurrentPosiiton();
}

updateCurrentPosiiton () {
    Geolocation.getCurrentPosition(
       (position) => {
          let d_lat  =  position.coords.latitude;
          let d_lng  =  position.coords.longitude;

          this.setState({
            current_lat: position.coords.latitude,
            current_lng: position.coords.longitude
          })
          // console.log('aayaaa');
          this.props.updateGps(d_lat,d_lng);

          this.getTrackData(d_lat,d_lng);

       },
       (error) => {
         console.log("map error: ",error);
           console.log(error.code, error.message);
       },
       { enableHighAccuracy: false, timeout: 15000, maximumAge: 10000 }
   );
  }

Please let me know if any issue.

A: I have solved this issue by this
async requestPermission() {
try {
  const granted = await PermissionsAndroid.requestMultiple([
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
  ]).then((result) => {
    console.log(result);
    if (
      result['android.permission.ACCESS_COARSE_LOCATION'] &&
      result['android.permission.ACCESS_FINE_LOCATION'] === 'granted'
    ) {
      this.getLocation();
      this.setState({
        permissionsGranted: true,
      });
    }
  });
} catch (err) {
  console.warn(err);
  }
}

 getLocation() {
Geolocation.getCurrentPosition(
  (position) => {
    console.log(position);
  },
  (error) => {
    // See error code charts below.
    console.log(error.code, error.message);
  },
  {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
  );
}

 componentDidMount() {
if (Platform.OS === 'ios') {
  Geolocation.requestAuthorization('always').then((res) => {
    console.log(res);
  });
}
if (Platform.OS === 'android') {
  this.requestPermission();
} else {
  this.getLocation();
 }
}

make sure you called this function with parameter  Geolocation.requestAuthorization('always') or  Geolocation.requestAuthorization('whenInUse')


text:
Q: ggplot2 change color of line based on categorical variable I am looking for a way to have one consistent line across a date range that changes colors based on a categorical variable.
Let's say the data looks like this:
Date    Value  Category
1/1/14 - 10 - A
1/2/14 - 11 - A
1/3/14 - 20 - B
1/4/14 - 26 - B
1/5/14 - 50 - D
I would like the line to change colors as it passes through the different categories. Is there a way to do this with ggplot2? Or will I need to use a different library.
I can get the line graph, but it is broken and disjointed.

Update
Currently I can get a scatterplot to do what I want with
qplot(x=data1$date, y = data1$value,data = data1, color = data1$category,geom="point")

However when I use "line" it tells me that

Each group consist of only one observation. Do you need to adjust the group aesthetic?

A: You need to assign a group variable:
using qplot:
  qplot(x=Date, y = Value,data = df, color = Category,group=1,geom="line")

or ggplot:
ggplot(df , aes(Date , Value , colour=Category , group=1)) + geom_line()

Also note, in your qplot statement you do not need to use 'yourdata$' as you define the data = yourdata. If you use yourdata$var you will have problems using ggplot.


text:
Q: avoid non constant expression in android There is a new thing since ADT 14, it's called non-constant expression: migration necessary.
Which cause that I can't do stuff like this:
TextView tv = (TextView) findViewById(R.id.text);

Or this:
getRessources().getDrawable(R.drawable.icon);

What I have to do to make it work now?

A: You must refactor your code since in library projects, the R fields are no longer constants(not final).  See http://tools.android.com/tips/non-constant-fields for details and examples on how to fix the issue.
Basically, you need to change your switch statements to if-else since you cannot switch over a non-constant.
Also, this is only for library projects.  regular android projects do not require this change.
After you make the changes be sure to clean and refresh your project as some errors/warnings may linger.

A: In Eclipse,
Click On Project -> Properties -> Android
and uncheck if true "Is Library" option.


text:
Q: How to replace all values of the same group with the minimum in PySpark I am practising with PySpark and I need to obtain something like this. I have a dataset that I have grouped by title, let's say, and I need for each title to replace a (new) third column with the minimum of another column

title
var
new_col

item1
3
0

item1
4
0

item1
5
0

item2
2
0

item2
10
0

To this table

title
var
min

item1
3
3

item1
4
3

item1
5
3

item2
2
2

item2
10
2

For now I succeeded in grouping the first table, but clearly I only end up with two rows, the first being item1 with the min of '3' and item2 with '2'. Any suggestion on how I can proceed now?

A: You can use window functions for this purpose.
from pyspark.sql import functions as F, Window

df2 = df.select(
    'title',
    'var',
    F.min('var').over(Window.partitionBy('title')).alias('min')
)

Or, for a simpler syntax:
df2 = df.selectExpr('title', 'var', 'min(var) over(partition by title) min')

A: PartitionBy title orderBy var and get first row for reach partition.
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions.col

w = Window.partitionBy("title").orderBy(col("var"))
df.withColumn("min",row_number.over(w)).where($"min" === 1)

Or
from pyspark.sql import functions as f

df.groupBy("title").agg(f.min("var").alias("min"))

A: Define a window function which partition data over "title" column. Then within each partition , get minimum of all rows in that partition.  This will give you minimum value along with other columns.
from pyspark.sql.window import Window
from pyspark.sql import functions as F
windowSpec = Window.partitionBy(df['title']) .orderBy(df['title'].desc()).rangeBetween(-sys.maxsize, sys.maxsize)
min_var =  (F.min(df['var']).over(windowSpec))
min_df =df.select("title", "var", min_var.alias("min"))
min_df.printSchema()
min_df.show()


text:
Q: Croppie.js show zoom slider only after the image is selected I am using croppie.js for image cropping and uploading. Currently, the image zoom in-out slider is being shown by default. I want the slider to be visible only when the image is selected. Until the user has selected an image, there is no use for the zoom slider. What change do I need to do in order to make the slider not be visible until image selection?
I have prepared a working snippet below to make it easy for debugging.

var resize = $('#uploadContainer').croppie({
  enableExif: true,
  enableOrientation: true,
  viewport: {
    width: 100,
    height: 100,
  },
  boundary: {
    width: 100,
    height: 100,
  }
});

$('#image').on('change', function() {
  var reader = new FileReader();
    reader.onload = function(e) {
      resize.croppie('bind', {
        url: e.target.result
      }).then(function(){});
    }
    reader.readAsDataURL(this.files[0]);
});

$('.btn-upload-image').click(function() {
  resize.croppie('result', {
    type: "canvas",
    size: "original",
    format: "jpeg",
    quality: 1
  }).then(function(img) {
    var imgval = $('#image').val();
    var dataString = {
      image: img,
      imgval: imgval
    };
    $.ajax({
      // AJAX GOES HERE
    });
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.css" rel="stylesheet"/>

  <input type="file" id="image" accept="image/*">

A: Ah! Minutes after posting the question I figured a custom solution. This was easy. I wanted to delete the question to not look stupid for posting a problem with such an easy solution but then I had a thought to answer it to help other devs who "might" be looking for the same solution.
Solution:
The slider is under a wrapper be default which we need to hide first by css.
.cr-slider-wrap {
  display: none;
}

Now, on change of image simply need to use the .show() or .fadeIn() to display it again.
$('#image').on('change', function() {
  $('.cr-slider-wrap').fadeIn(); // image load

  // REST OF THE CODE GOES HERE (please see question for reference)
});

That's it. Same way you can hide or disable the submit button to end enable or show it back depending upon your choice when the image is selected.


text:
Q: Принцип действия декоратора Property по шагам в Python друзья!
Насколько я понял, синтаксис декоратора property внутри класса:
@property
def somefunc(self)
    .
    .

эквивалентен:
def somefunc(self)
    .
    .
somefunc = property(somefunc)

Это так? Если да, то непонятно, почему не эквиваленты следующие конструкции внутри класса. Эта:
    @property
    def radius(self):
        return self.__radius

    @radius.setter
    def radius(self, radius):
        self.__radius = radius

и эта:
    @property
    def radius(self):
        return self.__radius

    def radius(self, radius):
        self.__radius = radius
    radius = radius.setter(radius)

Вторая конструкция не работает. Понятно, вроде почему. К моменту парсинга строчки:
radius = radius.setter(radius)

radius - уже не объект propery, а функция.
Тогда непонятно, почему работает первый фрагмент кода???
Который постоянно приводится в примерах в разных учебниках и статьях


text:
Q: C++/CLI Console::WriteLine with Vector of User Defined Objects I have a vector of User Defined Objects and I want to simply output some of the class members (fields?) to the console, but when I try, the program crashes. I have tried to display the 'EmployeeID' directly (it's an Int), as well as converting it to a System::String, and a std::string, using several methods for each (marshalling, converting to char array, etc).
std::vector<Employee> employee;
System::Console::WriteLine("Employee ID: " + employee.at(i).getEmployeeId());

I am at a loss as to why I can not simply print to the console, but I'm quite new to CLI, so maybe it's an easy fix and a simple mistake? I have the same issue with other variables stored in the employee object, those other items are std::string type.
I would prefer to use System::String instead of std::string for those other members, but when I do that I get a weird error message ("A member of a non-managed class cannot have a ref class type or interface class type"). Any help with either issue would be great, but this post is specifically for the Console::WriteLine problem.

A: as per @Ben Voight's suggestions:
Changing my class to a "ref" class and all of my std::string items to System::String^ items has worked.
(It did cause other issues with my code, but that's a different problem and is not related to the the fact that his answer/solution fixed this specific question/problem.)


text:
Q: Clear php-a line history When i run php -a It brings up a handy shell for testing code quickly along with a history of every line I type. Is there any way to clear this history?
Using php 5.5.9 if this makes any difference

A: On my linux laptop, there's a ~/.php_history that contains the ... history.

A: For clear history you can use readline_clear_history()
readline_clear_history ( void );

This function clears the entire command line history.
Return Values
Returns TRUE on success or FALSE on failure.

A: For Windows users, you can find the .php_history file in your home directory as well. I found mine at C:\Users\{my_name}\.php_history


text:
Q: How to assign, clear and get value of a hidden field in jquery? Consider a hiddenfield in the page HfId
<input type="hidden" id="HfId"/>

How to assign,clear and get value of a hidden field in jquery? ANy suggestion...

A: The Element Selector of jQuery is exactly designed for this. It allows you to select all elements which fit the given name, id or class:
$("a")       // Get all a-elements
$("#id")     // Get all elements with the id "id"
$(".class")  // Get all elements with the class "class"

The visibility or other properties of the element does not interfere with that, as it is still present in the DOM of the document.
Fields have the overloaded function val(), val($value) which allows you to get and set the value of the field:
$val = $("#HfId").val();  // Get
$("#HfId").val("");       // Clear
$("#HfId").val($newVal);  // Set

A: $("#HfId").val("pony");
var x = $("#HfId").val();


text:
Q: Does PHP allow getter calling in other functions/methods? So I have getter and I want to call it in __toString() method, but when I echo object, it says that __toString must not trow an exception. So I'm wondering if it is allowed, and if it is, what is wrong with my syntax?
private $price;
private $title;

public function getPrice(){
    return $this->price;
}

public function getTitle(){
    return $this->title;
}

public function __toString(){
    return "Price: " . getPrice() . "; Title: " . getTitle();
}

A: the short answer is, it's really up to you.
Personally, I would avoid accessing a vanilla getter inside your __toString() method.
 Purely because if someone else changes the method interface, it could change the output and it might not be obvious that it would break the __toString method.  (Also, it's (infinitesimally) slower, and my OCD wouldn't allow it :D)
However, if your getter has any other logic in it (implying that it's not just to access the raw class property), then you might still have to access the method.  If that was the case I'd make sure that its type-hinted to return a string (in php7) so you can be sure that the overall interface of that method is predictable.
public function getPrice(): string
{
    // some fancy logic that makes it a complex getter...
    $price = $this->someLogic($this->price);

    return $price;
}


text:
Q: How to constrain a sibling view to same height as that of TextInputEditText of an TextInputLayout I want to show the label "Km" with a white background with the same height as that of the edit text field.
   <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/textInputLayoutInputDist"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
                android:layout_width="wrap_content"
                android:layout_height="42dp"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/inputDist"
                    android:layout_width="80dp"
                    android:layout_height="match_parent"
                    android:background="@drawable/bg_left_corner_shape"
                    android:backgroundTint="@android:color/white"
                    android:fontFamily="@font/roboto_regular"
                    android:imeOptions="actionDone"
                    android:inputType="numberDecimal"
                    android:maxEms="4"
                    android:padding="4dp"
                    android:textColor="@color/colorPrimaryDark"
                    android:textSize="14sp" />
            </com.google.android.material.textfield.TextInputLayout>

            <TextView
                android:id="@+id/label_km"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_marginTop="4dp"
                android:background="@drawable/bg_right_corner_shape"
                android:backgroundTint="@android:color/white"
                android:fontFamily="@font/roboto_regular"
                android:gravity="center_vertical"
                android:text="@string/km"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="14sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@+id/textInputLayoutInputDist"
                app:layout_constraintTop_toTopOf="@+id/textInputLayoutInputDist" />
        </androidx.constraintlayout.widget.ConstraintLayout>

But the TextInputLayout is taking some more height that the edit text field, I cant align the edit text and the "Km" label vertically the same levels.

A:
As I understand your question check below answer
Give kmLable top and bottom constraint to edit text. Here I give fix width for a temporary purpose (change according to your requirement).

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayoutInputDist"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/inputDist"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/dividerColor"
            android:fontFamily="@font/roboto_bold"
            android:imeOptions="actionDone"
            android:inputType="numberDecimal"
            android:maxEms="4"
            android:padding="4dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="14sp" />
    </com.google.android.material.textfield.TextInputLayout>

    <TextView
        android:id="@+id/label_km"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:background="@color/dividerColor"
        android:fontFamily="@font/roboto_medium"
        android:gravity="center_vertical"
        android:text="km"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="@+id/textInputLayoutInputDist"
        app:layout_constraintStart_toEndOf="@+id/textInputLayoutInputDist"
        app:layout_constraintTop_toTopOf="@+id/textInputLayoutInputDist" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: try
setHintEnabled(false)

in your xml like this:
<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayoutInputDist"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:hintEnabled="false">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/inputDist"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/dividerColor"
            android:fontFamily="@font/roboto_bold"
            android:imeOptions="actionDone"
            android:inputType="numberDecimal"
            android:maxEms="4"
            android:padding="4dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="14sp" />
    </com.google.android.material.textfield.TextInputLayout>


text:
Q: How to run gcloud if Google Cloud SDK if my project is on another drive? I'm building an API with Google Cloud functions and I had the same issue as the guy from this post: Could not load the default credentials? (Node.js Google Compute Engine tutorial)
When trying to use my API, I received this error:
Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.
So I went on and followed the steps suggested in the question I mentioned. I downloaded the gcloud SDK, installed it, and at the end of the installation wizard there is an option to run the google cloud cli immediately.
I ran it successfully and logged in properly, now any time I open the command prompt I can use the gcloud command without a problem.
Mi issue is the following. I'm running my commands in VSCode bash terminal and I get an error saying that the gcloud command is not found.
My project is in my D: drive, and the SDK is on C:, which I believe is the reason why the gcloud command is not recognized when I attempt to use it.
Should/can I install the Google Cloud SDK in my D: drive and use it there, or should I move my project to the C: drive?
I read somewhere that this might be a problem with the bash terminal, but I tried running it from command prompt in VSCode and I get the same error, so I guess it's got nothing to do with it.
Thank you for your time.


text:
Q: HighCharts Semi-Pie Circle I'm trying to build a Semi-pie chart in HighCharts. I need to provide only 1 value to the semi-circle with value 45%, in this case Firfox is 45%.  I want that when I provide only 1 value , it should actually render the pie circle for only 45%, not the whole 100%. How can I do that?
Here is my jsfiddle link

A: I'm not sure if this is what you want: see example at jsfiddle
End angle is calculated as proportion of 45*180/100 = 81. So, end angle is at -9.
            startAngle: -90,
            endAngle: -9,
            center: ['50%', '75%']

And data is only one value:
        data: [
            ['Firefox',   45.0]
        ]

And tooltip is changed to show 45% instead of 100%
    tooltip: {
        pointFormat: '{series.name}: {point.y:.1f}%'
    },

Update: Used idea from @Mark to calculate endData using input data (see Mark's comment in his answer). Added also variable for startAngle. See update at jsfiddle:
var data = 45;
var startAngle = -90;
var endAngle = (data/100 * 180) + startAngle;
endAngle = endAngle == 0 ? 0.01 : endAngle;
...
            startAngle: startAngle,
            endAngle: endAngle,
...
        data: [
            ['Firefox',   data]
...

A: Not to steal @AntoJurković's thunder but his idea in the comment is the simplest way to accomplish what you want.
Here's an example fiddle.
The important parts are:
series: [{
        type: 'pie',
        name: 'Browser share',
        innerSize: '50%',
        data: [
            {y: 45, name: 'Firefox'},
            {y: 55, color: 'transparent',dataLabels:{enabled: false}} // instead of the background color, use transparent, and disable dataLabels
        ]
  }]

and
   tooltip: {
        formatter: function(){
            if (this.point.color == "transparent") {
                return false; // suppress the tooltips if it has no color
            } else {
                return this.series.name + ':' + this.point.percentage +'%';
            }
        }
    },


text:
Q: Why are the wrong clusters projected onto PCA using Sklearn? I am projecting my cluster centers onto 2 principal components, but the plot given is not in the correct central place of my 2 sets of data points. My code is given below. Does anyone see where I am going wrong? The PCA is fine, but one of the data points for the cluster is way off. I will mention that half of my centroid data points are negative. I have played around with inversing the pca transform and really am not sure where the error is coming from. Any help is greatly appreciated!
import numpy as np
import sklearn
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

data = normalize(key)

key_N=normal(key,key)

pca=PCA(n_components=21)
pca.fit(data[:,0:-1])
keytrain_T = pca.transform(data[:,0:-1])

kmeans = KMeans(n_clusters=2, init='k-means++', n_init=100, max_iter=300,
            tol=0.0001, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=1)
kmeans.fit(data[:,0:-1])

centroid = cluster_centers_
print("The centroids:",centroid)

# Project the cluster points to the two first principal components
clusters = pca.fit_transform(centroid)

print("The clusters:",clusters)

A: You fit_transform the centroids instead of transforming them.


text:
Q: set any process that takes 50ms or longer is logged in mongod.conf I wanna set any process that takes 50ms or longer is logged
I am aware of the below methods
db.setProfilingLevel
db.setLoglevel
mongod --profile 2 --slowms 50
But i wanna set it from /etc/mongod.conf
any suggestions?

A: We can update mongod configuration file with the below configuration
operationProfiling:
  slowOpThresholdMs: 50


text:
Q: Find $\nabla\cdot (\frac{x}{|x|})$ I saw this in an analysis book and was curious how to calculate such a function. My thought is the following:
Let $x\in \mathbb{R}^{n}\backslash\{0\}$
\begin{eqnarray*}
\nabla \cdot \left(\frac{x}{|x|}\right)&=& \sum_{i=1}^n\partial_i\left(\frac{x_i}{|x|}\right)\\
&=& \sum_{i=1}^n|x|^{-1}+x_i\left(-\frac{x_i}{|x|^3}\right)\\
&=&\frac{n}{|x|}-\frac{1}{|x|}\\
&=&\frac{n-1}{|x|}.
\end{eqnarray*}
My question is when looking at the divergence in the first equality, does the denominator see the index? That is, should it look like "$\frac{x_i}{|x_i|}$"? This is a trivial question but I haven't worked with this is quite some time. Thank you for your insight.


text:
Q: How to loop through all files in Jekyll's _data folder? How can I loop through every file in my _data folder in Jekyll?
Currently I have a list of files in a file called sidebarlist.yml like this:
- file1
- file2
- file3

In order to loop through all of these files, I use this code:
{% for sidebar in site.data.sidebarlist %}
{% for entry in site.data.sidebars[sidebar].entries %}
...
{% endfor %}
{% endfor %}

I would like to avoid using sidebarlist.yml and just iterate through all files within _data automatically. Can I do this?

A: Nesting loops allows you to loop through the contents of _data files.
When I did this I used a subdirectory, since I didn't want to loop through every data file, and I think that applies to many use cases. It also keeps my _data directory a little tidier.
My _data directory looks like this:
_data/
  navigation.yml
  news.yml
  people/
    advisors.yml
    board.yml
    staff.yml

Each of the files within people/ uses a structure like this:
- name: Anne Smith
  role: Role A
  url: mysite.com
- name: Joe Shmoe
  role: Role B
  url: mysite.org

And on the page where I'm looping through each of these data files:
{% for people_hash in site.data.people %}
{% assign people = people_hash[1] %}

  {% for person in people %}

{{ person.name }}, {{ person.role }}

  {% endfor %}

{% endfor %}

This results in:

Anne Smith, Role A

Joe Shmoe, Role B

It's very similar to what you've already done, but eliminates the need for that extra yaml file.

Note the use of people_hash[1] - this is what is targeting the appropriate values within the array.
If instead you do:
{% for people_hash in site.data.people %}
{% assign people = people_hash[1] %}

{{ people }}

{% endfor %}

You'll get the array of values that is returned, which should help you debug your template.

A: I have read your question title, and I will answer your last question:
You can't loop through files you keep in _data folder. According to Jekyll Variable doc and  Jekyll Directory structure all the file in _data with supported extension .yml .yaml .csv .jsonby default will be loaded in site.data like @wasthishelpfull's answered and you access it via {{site.data.*filename.data*}} and loop though like this answer
If you wanna loop through files, create a folder (no underscore) serve it as static files, and use jquery.get() for the data in the file.
Or change _data to data in _config.yml by adding data_source: data and access at a url endpoint /data see this post for more

A: According to the documentation, jekyll will load YAML resources (.yml, .yaml, .json, and .csv files) directly into site.data. If your files use one of these formats, you can do:
{% for data in site.data %}
    ...
{% endfor %}

A: I assume you need to access jekyll site.data in a way of looping multi levels object:
{% assign my_data = site.data %}
{% assign my_level = "sidebarlist.sidebars.sidebar" | split: "." %}

{% for level in my_level %}
    {% assign my_data = my_data[level[i]] %}
    {% for data in my_data %}
        {{ data }} : {{ my_data[data] }}
    {% endfor %}
{% endfor %}


text:
Q: How to solve (AccessDeniedException) when calling the Scan operation: User: arn:aws:sts... is not authorized to perform: dynamodb:Scan on resource.."? I am trying to deploy an Instagram-like application to AWS using Elastic Beanstalk and Flask. After using eb deploy command, I am able to access the application main page, which does not requires access to DynamoDB tables. When I try to login, the application should access a DynamoDB table to retrieve data, such as number of likes in pictures, however it shows an

500 Internal Server Error

And my eb logs returns this error.

ClientError: An error occurred (AccessDeniedException) when calling the >Scan operation: User: arn:aws:sts::013051511429:assumed-role/aws->elasticbeanstalk-ec2-role/i-049593eb550052c8f is not authorized to >perform: dynamodb:Scan on resource: arn:aws:dynamodb:us-east->1:013051511429:table/cloudgram

I think this is happening because of an IAM misconfiguration, it says that the user corresponding to my EC2 Instance (i-04959..) is not authorized to perfom a Scan on my DynamoDB table.
I have tried following this:
https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html
These are the policies I have attached to my aws-elasticbeanstalk-ec2-role:

*

*AmazonRDSFullAccess

*AmazonS3FullAccess

*AWSLambdaDynamoDBExecutionRole

*AWSElasticBeanstalkWebTier

*AWSElasticBeanstalkMulticontainerDocker

*AWSElasticBeanstalkWorkerTier

I'm using:
 Python 2.7
 Flask 1.0.2

A: The policy you have supplied, AWSLambdaDynamoDBExecutionRole, is for DynamoDB streams. It doesn't allow access to tables.
One way to solve this is to add the AmazonDynamoDBFullAccess policy though a better way would be to create an IAM Policy that permits only those actions required and only those resources (the DynamoDB tables) that you need. Here is an example of doing that.

A: I had the same issue with an extended cause. For people having the same, I want to mention my solution.
It was because of permission boundaries.


text:
Q: Return data to the view via JSON or ILIST in MVC What is the best way / fastest way to use minimum resources while sending data back to the server. For example I have a table on the View and I am looping through it via IList
In the controller / repository I am filling the IList, and during this time I am creating a new object and adding this object in the IList. (Does creating each object too much memory?)
Is this the right way to do things and fastest using least resource or I should use JSON to return the data to the View

A: Json is not for pushing data to the view but to the client. The connection between Controller and View happens on the server side - so it does not matter much (in terms of performance/datasize) what kind of datatype you use to send data to your view. Than the view gets rendered to html on the server and the resulting html is sent to the client.
And here is the point where datasize matters. When you have a large table you want ot display the generated html is much bigger than the pure data you need to create the table.
So you might consider to use ajax and request just the data from your controller which responds with a Json object. The client will receive the data in a javascript callback and construct the html table (jQuery template is a good toolkit for this).


text:
Q: ravendb from console app I'm trying to get raven working in a rhino.etl console to import date from sql to raven.
I have a RavenInstaller:
public class RavenInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                Component.For<IDocumentStore>().ImplementedBy<DocumentStore>()
                    .DependsOn(new { connectionStringName = "SomeRavenConnectionString" })
                    .OnCreate(DoInitialisation)
                    .LifeStyle.Singleton
                );
        }

        static IDocumentSession GetDocumentSesssion(IKernel kernel)
        {
            var store = kernel.Resolve<IDocumentStore>();
            return store.OpenSession();
        }

        public static void DoInitialisation(IKernel kernel, IDocumentStore store)
        {
            store.Initialize();
        }
    }

However - when I call  _documentSession.OpenSession() the app just hangs.
Is there something I need to specify for the console app environment? It keeps saying it's timed out - but the url in the config is localhost:8080 which is correct?
i've changed it to now use:
using (var documentStore = new DocumentStore { Url = "http://localhost:8080" })
            {
                documentStore.Initialize();
                using (var session = documentStore.OpenSession())
                {
                    var mp = _container.Resolve<MainProcess>();
                    mp.DocumentSession = session;
                    mp.Execute();
                }
            }

but still hanging on opensession.

A: Where is the hang actually occurs? In what method inside OpenSession?


text:
Q: could not find function "flextable_to_rmd" library(flextable)
ft <- flextable(head(mtcars))
ft <- autofit(ft)

for(i in 1:2){
  flextable_to_rmd(ft)
}

Error:
could not find function "flextable_to_rmd".
This error arises when when knitting to html file.
This code was taken from flextable book. pandoc version I have 2.14.0.3. is there any function/code am I missing here?


text:
Q: Unable to convert example of `useSwr` hook to use `react-query`'s `useMutation` hook? I tried changing the useSwr hook to use:
import { useMutation } from 'react-query';

const { data: user, mutate: mutateUser } = useMutation<User>('/api/user');

But I get an error stating:

No mutationFn found

Unable to solve this. I tried adding mutationFn inside useMutation like the following & it works but it is static:
const { data: user, mutate: mutateUser } = useMutation<User>('/api/user', {
    mutationFn: () => {
      const u: User = {
        isLoggedIn: false,
        avatarUrl: '',
        login: '',
      }
      return Promise.resolve(u)
    },
  })

If I use a dynamic request using something like axios then do I need to put the fetchJson from login.tsx to mutationFn hook?
Basically, I want to use react-query instead of swr & ky instead of fetchJson & unable to find a solution?
I'm pretty sure it's really simple but haven't been able to make it work.
Stackblitz Demo → https://stackblitz.com/edit/next-iron-session-with-react-query?file=lib%2FuseUser.ts (go to /login route, enter a github username like vvo & click Login to see the error in console)
Repo → https://github.com/deadcoder0904/next-iron-session-with-react-query

A: By navigating through the documentation it seems that the first argument of the useMutation if the mutationFn and not the mutationKey
useMutation
What if the code changes to:

const { data: user, mutate: mutateUser } = useMutation<User, unknown, { username: string }>((body) => {
      return fetchJson('/api/login', {
       method: 'POST',
       headers: { 'Content-Type': 'application/json' },
       body: JSON.stringify(body),
      })
    }, {
      mutationKey: '/api/user'
    }
  })

and when you need to actually mutate
mutateUser({ username: 'Username' })


text:
Q: Persist changes to core data item from SwiftUI view I'm working on a SwiftUI app that is to display a number of entries from a Core Data database. Basically just about what the XCode template for such apps implements.
I've made two changes:

*

*I put the code for the list item view into a separate file (BookmarkableItemView)

*I added a property bookmarked to the item, which I called BookmarkableItem
The code in my view to show the list of items is now:
List(bookmarkableItems) { item in
    BookmarkableItemView(item: item)
}

In BookmarkableItemView, the item property is an @ObservedObject.
Now, my BookmarkableItemView also contains a button that should toggle the bookmarked property on the item that the view represents. All fine and well - this is easy. But now I have to persist the changes...
I can think of the following two solutions:

*

*Pass an action (simple a (BookmarkableItem) -> Void) to the BookmarkableItemView that's then called when button in the view is pressed

*Have the view itself save the managed object context

The latter is  a no-go in my opinion. The first solution works. There's now an bookmarkAction property in the BookmarkableItemView, so the above code looks like that:
List(bookmarkableItems) { item in
    BookmarkableItemView(bookmarkAction: { toggleBookmark(item) }, item: item)
}

The action is called by the BookmarkableItemView and as a consequence, the toggleBookmark(_ item:) method is called.
But somehow I feel that I'm missing something about bindings in SwiftUI that would make the process easier? How can I have my parent view get a notification when a sub view performs changes to the data model so I can persist them?

A: onDisappear check if item.hasChanges
or use onChange on item.hasChanges


text:
Q: Span tag and content not rendering inside quill editor I have recently started exploring quill to implement a rich text editor. I want to render following html content in quill editor:
Second span
However when rendered, span tag is removed and its content is wrapped inside P tag and rendered. I learnt that as part of optimization quill removed span tags. But I really want span tag to render so I added a SPAN blot extending BlockEmbed. However after adding SPAN blot, nothing rendered in the editor. I don't understand what I am doing wrong; Here is the SPAN Blot:
let quill = require("quill");
let BlockEmbed = quill.import("blots/block/embed");

class SpanBlot extends BlockEmbed {
    public static create(value: any): any {
        let node = super.create(value);
        node.setAttribute("data-embed-id", value);
        return node;
    }

    public static value(node: any): any {
        return node;
    }

    public static formats(node: any): any {
        let format: any = {};
        if (node.hasAttribute("data-embed-id")) {
            format.height = node.getAttribute("data-embed-id");
        }
        return format;
    }

    public formats(): any {
        let formats = super.formats();
        formats["span"] = SpanBlot.formats(this.domNode);
        return formats;
    }
 }

SpanBlot.blotName = "Span";
SpanBlot.tagName = "SPAN";
SpanBlot.class = "social";

export { BlockEmbed, SpanBlot };


text:
Q: Single update query to update a single document (containing subarray documents)? I have an existing document in DB:
Plan Collection (In DB):
{ _id: ObjectId('XXX'),
  name: 'Plan A',
  remark: 'YYY',
  products: [ {name: 'Pdt1', qty: '10'},
              {name: 'Pdt2', qty: '20'} ]
}

I need to do update to 'Plan A' doc with products entirely to below (no matching required to existing products in DB) below:
{ _id: ObjectId('XXX'),
  name: 'Plan A',
  remark: 'edited YYY',
  products: [ {name: 'Pdt1', qty: '10'},
              {name: 'Pdt3', qty: '30'},
              {name: 'Pdt4', qty: '40'}  ]

Question:
Is there a simple MongoDB way to update existing 'Plan A' document to update its fields + replace all products subarrays in DB? Thank you

A: If you want to replace the entire product subdocument you can do it with positional all $[] operator in MongoDb 3.6+
var filter = {
    name: 'Plan A'
};

var update = {
    $set: {
        'products.$[]': [
            {name: 'Pdt1', qty: '10'},
            {name: 'Pdt3', qty: '30'},
            {name: 'Pdt4', qty: '40'}
        ]
    }
};

var options = {
    multi: true
};

db.collection.update(filter, update, options);


text:
Q: Use user input as function arguments in tkinter I want to use the users inputs in e1, e2, e3, e4 as class arguments for the class Data(). I tried creating a function get_args() but it just returns empty stings since action by the user has to be taken to actually show the inputs. What is the best way of taking user input and using them as funtion arguments?
d = Data()

import tkinter as tk
from hist import Data

def quit(root):
    root.destroy()

#def get_args():
    #return e1.get(), e2.get(),e3.get(), e4.get()

def show_entry_fields():
    print("Ticker: %s\nStart Date: %s\nEnd Date: %s\nBasis: %s" % (e1.get(), e2.get(),e3.get(),e4.get()))

root = tk.Tk()

tk.Label(root, text="Ticker").grid(row=0)
tk.Label(root, text="Start Date").grid(row=1)
tk.Label(root, text="End Date").grid(row=2)
tk.Label(root, text="Basis").grid(row=3)

e1 = tk.Entry(root)
e2 = tk.Entry(root)
e3 = tk.Entry(root)
e4 = tk.Entry(root)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)

#Data = Data(get_args())
#Ticker = d.get_histocial_prices()

tk.Button(root, text='Show', command=show_entry_fields).grid(row=4, column=1, sticky=tk.W, pady=4)

tk.Button(root, text='Quit', command=root.quit).grid(row=4, column=0, sticky=tk.W, pady=4)
#tk.Button(root, text='Show', command=Ticker).grid(row=4, column=2, sticky=tk.W, pady=4)
root.mainloop()

A: You can define variables as global in get_args() function as:
import tkinter as tk
from hist import Data

def get_args():
    global ticker, start_date, end_date, basics

    ticker = e1.get()
    start_date = e2.get()
    end_date = e3.get()
    basics = e4.get()
    # print variables and initialize Data
    init_data()

def init_data():
    print("Ticker: %s\nStart Date: %s\nEnd Date: %s\nBasis: %s" % (ticker, start_date,end_date,basics))
    global d
    d = Data(ticker, start_date, end_date, basics)

root = tk.Tk()

tk.Label(root, text="Ticker").grid(row=0)
tk.Label(root, text="Start Date").grid(row=1)
tk.Label(root, text="End Date").grid(row=2)
tk.Label(root, text="Basis").grid(row=3)

e1 = tk.Entry(root)
e2 = tk.Entry(root)
e3 = tk.Entry(root)
e4 = tk.Entry(root)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)

tk.Button(root, text='get entries', command=get_args).grid(row=4, column=1, sticky=tk.W, pady=4)

root.mainloop()


text:
Q: When I open a specific website, I am switched to my router's password web page. Why does this happen?
Possible Duplicate:
Opening a specific website switches me to my router's password web page

My router is Huawei MT880. When I open the my website that i m hosting, a dialog box asking for my router password appears. I am also using Apache webserver for publishing my own website. I have also register a free domain, that is pointing to my routers IP.

A: It could be a mis-configured website, which is issuing a redirect to a private IP address which happens to be the same as the private IP address of your router.


text:
Q: Ruby complaining it could not find builder? I reinstalled rmagick and mini_magick using gem install, and after that, running a ruby script I need to fix, I get the following errors:
/Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:247:in `to_specs': Could not find builder (~> 3.0.0) amongst [Ascii85-1.0.2, actionpack-3.2.12, activemodel-3.2.12, activerecord-3.2.12, activerecord-mysql2-adapter-0.0.3, activesupport-3.2.12, addressable-2.3.3, afm-0.2.0, archive-tar-minitar-0.5.2, arel-3.0.2, aws-s3-0.6.3, aws-ses-0.4.4, builder-3.1.4, bundler-1.2.4, columnize-0.3.6, cookiejar-0.3.0, daemon-kit-0.2.1, diff-lcs-1.2.1, em-http-request-1.0.3, em-socksify-0.2.1, em-synchrony-1.0.3, erubis-2.7.0, eventmachine-1.0.0, factory_girl-4.2.0, god-0.13.1, hashery-2.1.0, hike-1.2.1, http_parser.rb-0.5.3, i18n-0.6.1, journey-1.0.4, linecache19-0.5.12, little-plugger-1.1.3, logging-1.8.1, mail-2.5.3, mailfactory-1.4.0, mime-types-1.21, mini_magick-3.5.0, multi_json-1.6.1, mysql2-0.3.11, pdf-reader-1.3.1, polyglot-0.3.3, prawn-0.12.0, prawn-fast-png-0.2.3, rack-1.5.1, rack-cache-1.2, rack-protection-1.3.2, rack-test-0.6.2, rake-10.0.3, redis-3.0.2, redis-namespace-1.2.1, resque-1.23.0, rmagick-2.13.2, rspec-2.12.0, rspec-core-2.12.2, rspec-expectations-2.12.1, rspec-mocks-2.12.2, rubigen-1.5.8, ruby-debug-base19-0.11.25, ruby-debug-base19x-0.11.29, ruby-debug-ide-0.4.16, ruby-rc4-0.1.5, ruby_core_source-0.1.5, rubygems-bundler-1.1.0, rufus-scheduler-2.0.17, rvm-1.11.3.6, safe_attributes-1.0.9, safely-0.3.2, sinatra-1.3.4, sprockets-2.8.2, state_machine-1.1.2, subexec-0.2.2, tenderlove-frex-1.0.1.20090313144615, thor-0.17.0, tilt-1.3.3, treetop-1.4.12, ttfunk-1.0.3, tzinfo-0.3.35, vegas-0.1.11, xml-simple-1.1.2] (Gem::LoadError)
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:778:in `block in activate_dependencies'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:767:in `each'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:767:in `activate_dependencies'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:751:in `activate'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:781:in `block in activate_dependencies'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:767:in `each'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:767:in `activate_dependencies'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:751:in `activate'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems.rb:212:in `rescue in try_activate'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems.rb:209:in `try_activate'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:59:in `rescue in require'
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:35:in `require'
    from ./q_test.rb:4:in `<main>'

I have the following gems installed on my rvm gemset:
actionpack (3.2.12)
activemodel (3.2.12)
activerecord (3.2.12)
activerecord-mysql2-adapter (0.0.3)
activesupport (3.2.12)
addressable (2.3.3)
afm (0.2.0)
archive-tar-minitar (0.5.2)
arel (3.0.2)
Ascii85 (1.0.2)
aws-s3 (0.6.3)
aws-ses (0.4.4)
builder (3.1.4)
bundler (1.2.4)
columnize (0.3.6)
cookiejar (0.3.0)
daemon-kit (0.2.1)
diff-lcs (1.2.1)
em-http-request (1.0.3)
em-socksify (0.2.1)
em-synchrony (1.0.3)
erubis (2.7.0)
eventmachine (1.0.0)
factory_girl (4.2.0)
god (0.13.1)
hashery (2.1.0)
hike (1.2.1)
http_parser.rb (0.5.3)
i18n (0.6.1)
journey (1.0.4)
linecache19 (0.5.12)
little-plugger (1.1.3)
logging (1.8.1)
mail (2.5.3)
mailfactory (1.4.0)
mime-types (1.21)
mini_magick (3.5.0)
multi_json (1.6.1)
mysql2 (0.3.11)
pdf-reader (1.3.1)
polyglot (0.3.3)
prawn (0.12.0)
prawn-fast-png (0.2.3)
rack (1.5.1)
rack-cache (1.2)
rack-protection (1.3.2)
rack-test (0.6.2)
rake (10.0.3)
redis (3.0.2)
redis-namespace (1.2.1)
resque (1.23.0)
rmagick (2.13.2)
rspec (2.12.0)
rspec-core (2.12.2)
rspec-expectations (2.12.1)
rspec-mocks (2.12.2)
rubigen (1.5.8)
ruby-debug-base19 (0.11.25)
ruby-debug-base19x (0.11.29)
ruby-debug-ide (0.4.16)
ruby-rc4 (0.1.5)
ruby_core_source (0.1.5)
rubygems-bundler (1.1.0)
rufus-scheduler (2.0.17)
rvm (1.11.3.6)
safe_attributes (1.0.9)
safely (0.3.2)
sinatra (1.3.4)
sprockets (2.8.2)
state_machine (1.1.2)
subexec (0.2.2)
tenderlove-frex (1.0.1.20090313144615)
thor (0.17.0)
tilt (1.3.3)
treetop (1.4.12)
ttfunk (1.0.3)
tzinfo (0.3.35)
vegas (0.1.11)
xml-simple (1.1.2)

No idea why this is happening? It was working up to the point where I removed and reinstalled rmagick?

A: You need builder 3.0.x while you have builder 3.1.4 installed.
It says "Could not find builder (~> 3.0.0)". The "~>" marks "pessimistic version constraint" (described here http://docs.rubygems.org/read/chapter/16#page74 ) which simply means "don't care about the last digit". So, any 3.0.x will suite, but 3.1.x won't.


text:
Q: How to evalute Rule criteria of workflow with Apex Programming? I want to evaluate Rule Criteria Expression with Apex Programming.
For Example :-
Rule Criteria :-
(Account: Account Name EQUALS ads) AND (Account: Account Number EQUALS 1234)
I want to evaluate this expression and need a boolean result.

A: What you are asking is essentially how to reimplement a huge chunk of the Salesforce infrastructure - replacing optimized Salesforce code that can take advantage of a wide variety of techniques and caching solutions not available to you in Apex - with your hand-rolled Apex-based parser and evaluation engine.
That's going to come with a wide variety of consequences.

*

*It would be a large and highly complex engineering effort.

*It will cost you a chunk of Apex limit to write a fully generalized expression parser and evaluator, which essentially goes to waste.

*You will need to do extensive and complex testing to validate that your code behaves the same way as the native Salesforce workflow evaluation engine. It will be nearly impossible to cover all of the potential cases, opening the door to future regressions.

*You'll have to talk to the Metadata API to obtain workflow definitions and cache them somewhere, which adds more overhead and change management.

*It's unlikely to be as fast as you think. Parsing and text manipulation in general isn't the fastest operation you can perform.

*It may break managed packages (or your own code!) that depend on the standard Salesforce order of execution being followed.

If you're in a situation where your triggers are so expensive to run that two invocations in a transaction will cause CPU time exceptions, this route is highly unlikely to save you, and there are other strategies that are more likely to be successful.

*

*You should focus on reducing the execution time of your triggers and pushing expensive computations and queries into asynchronous code, like Queueables or Batch Apex.

*You might use effective static collection-based recursion guards to avoid processing the same records twice in the same transaction.

*You might reimplement specific workflow rules that run on many or most records of an object as elements of your before trigger handlers - not by writing a workflow evaluation engine, but by removing specific workflows and rewriting them in Apex.


text:
Q: Creating concave polygon with constraint angles in QGIS I'm having point data. By using that I want to create concave polygon with some constraint angles (i.e., >45 and <225 degree).
Is it possible to do in QGIS?


text:
Q: angular : delete some properties in obj with angular here is my data :
$scope.datas = {
      "name": "000",
      "id" : 1,
      "type" : "record"
      "children": [
        {name:111,id:2,children:[
          {name:444,id:5,children:[]}
        ]}
        {name:222,id:3,children:[]}
        {name:333,id:4,children:[]}
      ]
    }

and this is my delete function :
deleteNode = (node,id) ->
    if node.id == id
      $timeout ->
        console.log 'findNode',node
        node = null
        return
    if node.children
      for rows,i in node.children
        if rows.id == id
          $timeout ->
            console.log 'findNode',rows
            rows = null
        else
          deleteNode(rows,id)

I need to find the specified id in my $scope.datas
after I execute this function deleteNode($scope.datas,5)
it find the correct obj indeed,but the $scope.datas doesn't change,why?

Found the answer,I change deleteNode function to blew

deleteNode = (node,id) ->
    if node.id == id
      $timeout ->
        node = {}
        return
    if node.children
      for rows,i in node.children
        if rows.id == id
          node.children.splice(i,1)
          return
        else
          deleteNode(rows,id)

A: Try returning the object after you make the changes to it i.e.
deleteNode = (node,id) ->
    if node.id == id
      $timeout ->
        console.log 'findNode',node
        node = null
         // return the node
        return node;
    if node.children
      for rows,i in node.children
        if rows.id == id
          $timeout ->
            console.log 'findNode',rows
            rows = null
            // return the node
            return node;
        else
          deleteNode(rows,id)

A: try to use
deleteNode = (node,id) ->
 if node.id == id
   $timeout ->
     console.log 'findNode',node
     node = null
     $timeout(angular.noop)
    return
if node.children
  for rows,i in node.children
    if rows.id == id
      $timeout ->
        console.log 'findNode',rows
        rows = null
        $timeout(angular.noop)
    else
      deleteNode(rows,id)


text:
Q: Using Go modules with private repositories via HTTP without SSL Is there a way to force the go command to use HTTP instead of HTTPS?
I am trying to move a project to Go Modules, but this project includes a private git repository as a dependency.
This git repository is hosted in a private LAN behind a firewall and I usually
clone it with something like cd $GOPATH/git.ourdomain.net/foo/bar/ && git clone http://my-user:my-password@git.ourdomain.net/foo/bar/reponame.git.
However now the commands go mod, go get and go test are trying to use HTTP with SSL (HTTPS).
This setting is not helping:
git config \
  --global \
  url."http://my-user:my-password@git.ourdomain.net/foo/bar/reponame".insteadOf \
  "http://git.ourdomain.net"

(Check here for some context around git settings for private repositories: https://medium.com/cloud-native-the-gathering/go-modules-with-private-git-repositories-dfe795068db4)
I've amended the file go.mod to include a reference to that private repository (using a pattern like git.ourdomain.net/foo/bar/reponame@v0.0.0-<YYYYMMDDHHmmSS>-<GIT_COMMIT_ID>), but when invoking go test with a file go.mod including that private repo, then I see:
go: git.ourdomain.net/foo/bar/reponame@v0.0.0-<YYYYMMDDHHmmSS>-<GIT_COMMIT_ID>: unrecognized import path "git.ourdomain.net/foo/bar/reponame" (https fetch: Get https://git.ourdomain.net/foo/bar/reponame?go-get=1: dial tcp <PUBLIC_IP_ADDRESS>:443: connect: connection refused)

I've also tried to revert go.mod to the original version (without that private repository) and tried to go get from the path where the file go.mod is stored, assuming that will somehow update the go.mod file via HTTP because of -insecure (check here https://golang.org/cmd/go/#hdr-Module_aware_go_get), like this:
GO111MODULE=on go get -insecure -u git.ourdomain.net/foo/bar/reponame

But this gave the error message:
fatal: remote error: Repository not found
The requested repository does not exist, or you do not have permission to
access it.

I know I should use SSL, but I've never had control on this git server to configure it the way it should be configured. So I just used git clone providing an HTTP URL (when behind the firewall) and it always worked.

A: The go command begins fetching a given module path by resolving that path to a version-control location. In order to resolve the path, it issues an HTTPS request and looks for a <meta name="go-import" […]> tag as described at https://tip.golang.org/cmd/go/#hdr-Remote_import_paths.
If you want it to skip that step, you must indicate that the import path is a raw version-control path by using a version-control suffix (listed in that same documentation).
If you write import "git.ourdomain.net/foo/bar/reponame.git" instead of import "git.ourdomain.net/foo/bar/reponame", you should find that the initial HTTPS resolution is skipped and the subsequent git operation uses the insteadOf declaration from your global git configuration.


text:
Q: Add multiple 2 element Lists to 1 list I am trying to get output in the form:
Result = [[5,2.23607], [4,2.0], [3,1.7321]] ;

The idea of the program is that you input two numbers, N and M.
N is always greater than M.
The program finds the square root of the numbers from N to M (inclusive).
The above Result would be the result of the function sqrt_finder(5,3,Result).
I've been trying to figure out how to do this but don't understand the recursive appending process.
Even if I did get this working, I don't think the output would be in the format I require.
This is what I have so far.
sqrt_finder(N,M,Result) :-
   N is M,
   Y is sqrt(N),
   Result = [N,Y].
sqrt_finder(N,M,Result) :-
   X is N-1,
   Y is sqrt(N),
   append([N,Y],sqrt_finder(X,M,Result),Result).

Can anyone please help explain the appending process and how the variable Result factors into this?
Thank you for your help.
Update
sqrt_finder(N,N,[[N,Y]]) :-
   Y is sqrt(N).
sqrt_finder(N,M,[[N,Y]|Result]) :-
   N > M,
   X is N-1,
   Y is sqrt(N),
   sqrt_finder(X,M,Result).

A: Let's try and break it down to exactly what you specified in your question (not saying this is the most elegant solution, just trying to keep it simple):

The idea of the program is that you input two numbers, N and M where N is always greater than M.

main(N,M,Result) :-
    N > M,
    calc_roots(N,M,Result).

The program finds the square root of the numbers from N to M (inclusive).

I'm guessing this is an assignment and the fact they are asking to now include M into your calculations is to make it a little bit more difficult given the first condition was that N should always be greater than M. Again, there are several ways to accomplish this, but we're going for the simple approach.
We write down the possible states:
-N is less than M, this is an invalid condition our termination condition when decreasing N to calculate all the square roots from N to M included and we must stop the execution here.
-N is greater than or equal to M, in this case we want the square root of N and decrease it by 1 to recursively keep doing the same until we reach our base case we defined above.
% Base case
calc_roots(N,M,[]) :- N < M.

% N is greater than or equal to M (we need M inclusive)
calc_roots(N,M,[[N,Sqrt]|Result]) :-
    N >= M,
    - calc square root -
    - decrease N -
    - make recursive call with new N -

Up to you to fill in the blanks. Good luck!