text:
Q: Yellow Pages Scraper in Python Not working I am trying to scrape data from Yellow Pages. I  used this scraper many times, but it has recently stopped.
Got this error

'NoneType' object has no attribute 'group' 0 results found

can anyone please help me to fix this problem
Where am I going wrong on this?
import requests
import requests_random_user_agent
import urllib.parse
from bs4 import BeautifulSoup
import re
from math import ceil
import csv
import os
import sys
import subprocess
from os import system, name
import time
from tqdm import tqdm

class Scraper:
    def __init__(self,keyword,location):
        self.keyword=keyword
        self.location=location
        self.params = urllib.parse.urlencode({"search_terms": self.keyword, "geo_location_terms": self.location})

    def get_info(self, link):

        try:
            r = requests.get(link)
            html = BeautifulSoup(r.content, "html.parser")
        except:
            return False

        try:
            name = html.find('h1').text
        except:
            name = None

        try:
            phone = html.find(class_='phone').text
        except:
            phone = None

        try:

            website = html.find('a',class_='primary-btn website-link')["href"]

            if len(website.split("?")) > 1:
                website = website.split("?")[0]

        except:
            website = None

        try:
            email = html.find('a', class_='email-business')["href"].split(":")[1]
        except:
            email=None

        try:
            address = html.find('h2',class_='address').text
        except:
            address=None

        return {"name": name, "email": email, "phone": phone, "address": address, "website":website}

    def get_num_pages(self):

        try:
            url = f"https://www.yellowpages.com/search?{self.params}"

            response = requests.get(url)

            html = BeautifulSoup(response.content, "html.parser")
            pagination = html.find(class_="pagination")

            if not pagination:
                pagination = 1
                links = html.select("a[class='business-name']")

                num_results = 0

                for l in links:
                    try:
                        l["data-analytics"]
                        num_results += 1
                    except:
                        continue

                return num_results, pagination

            num_results = int(re.search('We found(.*?)results',pagination.text).group(1))

            return num_results, int(ceil(int(num_results) / 30))

        except Exception as e:
            print(e)
            return False, False

    def get_links(self, page):

        try:
            url = f"https://www.yellowpages.com/search?{self.params}&page={page}"

            response = requests.request("GET", url, timeout=10)
            html = BeautifulSoup(response.content, "html.parser")
            links = html.select("a[class='business-name']")

            links_filtered=[]

            for l in links:
                try:
                    l["data-analytics"]
                    links_filtered.append(l)
                except:
                    continue

            links_list = []

            for link in links_filtered:
                links_list.append(f"https://www.yellowpages.com{link['href']}")

            return links_list
        except Exception as e:
            print(e)
            return []

def open_file(filename):

    try:
        if sys.platform == "win32":
            os.startfile(filename)
        else:
            opener = "open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, filename])
    except:
        return False

def create_csv(elements):

    row_list = [["Name", "Address", "Phone", "Email", "Website"]]

    for e in elements:

        name = e["name"]
        address = e["address"]
        phone = e["phone"]
        email = e["email"]
        website = e["website"]

        row_list.append([name, address, phone, email, website])

    with open('output.csv', 'w', newline='', encoding='utf8') as file:
        writer = csv.writer(file)
        writer.writerows(row_list)

def clear():

    # for windows
    if name == 'nt':
        _ = system('cls')

    # for mac and linux(here, os.name is 'posix')
    else:
        _ = system('clear')

def main():

    clear()

    try:

        while True:
            keyword = input("Keyword: ")

            if keyword != "":
                break

        while True:
            city = input("City: ")
            if city != "":
                break

        clear()

        scraper = Scraper(keyword, city)

        results, num_pages = scraper.get_num_pages()

        if not results:
            print("0 results found")
            return False

        print(f"{results} results found {keyword} - {city}")

        data = []

        pages = tqdm(range(1, num_pages + 1))

        for page in pages:
            clear()
            try:
                pages.set_description(f"Scraping page {page}/{num_pages}...")

                links = scraper.get_links(page)

                if not (len(links) > 0):
                    continue

                links = tqdm(links)

                for link in links:
                    try:
                        links.set_description(f"Scraping {link}")

                        info = scraper.get_info(link)
                        # print(info)
                        data.append(info)

                        create_csv(data)

                    except:
                        continue

            except:
                continue

        print("Opening file...")

        open_file("output.csv")

        print("Task finished")

    except:
        return False

if __name__ == "__main__":
    main()

A: It fails on the line
num_results = int(re.search('We found(.*?)results',pagination.text).group(1))

A very simple check of the search results page, by opening the browser, would have shown you that the text "We found x results" is not present on the page. So re.search returns None, even if there are many results.
Adjust your script to work without num_pages and only paginate via the page links at the bottom or by incrementing the page= parameter in the URL until no more results/pages are listed.
FYI, next time, put in some minimal debugging effort and not post your entire script.


text:
Q: Anime or cartoon that features a talking dog with a power stone in its tooth There was a cartoon that I used watch sometimes in my childhood. I want to watch that again. There was a talking dog in that anime or cartoon with power stone in his tooth. I think the story was about the stone.

A: Might this be Shin Hakkenden (1999)...?

Based on the long cherished, classic Japanese novel Nanso Satomi Hakkenden by Bakin Kyokutei Takizawa (1767), a modified version of it was made into animation.
Taking place in the future, during this time wars were occuring in heaven, mostly for possession between the eight moons created by the savior Fuse that surrounded God's land. When the war ended, there was only one ruling family - that of the Oowaris, and the remaining son gained control of all the moons of heaven, except for one. Meiten, the moon of the pope, where people refrained from war and were therefore out of its terms.
Eight people. Each from one of the eight moons. Each possessing one of the jewels - the elements that compose Earth. They are those who are destined to become saviors of humanity. All of them have sacrificed for these jewels, and are determined to complete their duty to Queen Fuse who entrusted these to them. When the mad emperor Kai threatens to revive a ghost who wants to prevent the restoration of Earth, these eight must battle using the powers given by their jewels in order to create Earth and defeat those who want to prevent it.
So they all go to Kusanagi, the ship in the center of God's land. They must gather the jewels in the key called Yatsufusa at Kusanagi's center, in order to create Earth.

One of the main characters is Chuji, a talking dog with a jewel on its left canine tooth. You can see it at the 0:51 mark in the video below.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Errors importing my exported CSV file from MYSQL database using PHPmyadmin I am trying to export a MYSQL database from PHPmyadmin with over 800 products that uses virtuemart shopping cart.
When I export the information from my product table selecting CVS type file it exports but it won't import the information into joomla 2.5.
The report tells me These fields have been found but are not supported by CSVI:
Does this mean that I can't export the products from MYSQL as a table, is there a way around this?
Thanks
Devanstra


text:
Q: Trello alike CSS layout I'm trying to accomplish a layout similar to Trello:

*

*kanban is always fully visible.

*lane shrinks to fit the cardList.

*cardList overflows when it reaches the bottom of kanban

*kanban overflows horizontally when lanes are out of sight.

I'm not sure how to overflow the cardList component. I know it currently doesn't work because of the height: 100% property within .cardList, but I'd like to not have to give it a fixed height.
Also, I can't seem to overflow the kanban horizontally when I add overflow-x: scroll to .kanban.
Here's also a codesandbox in case it's easier.

:root {
  --padding-card: 4px;
}

.App {
  font-family: sans-serif;
  text-align: center;
}

.container {
  height: 90vh;
}

.kanbanWrapper {
  background: black;
  height: 100%;
  overflow: hidden;
}

.kanban {
  display: inline-flex;
  background: lightgrey;
  border-radius: 4px;
  padding: 1rem;
  margin: 1rem;
}

.kanban .lane {
  margin: 0 var(--padding-card);
}

.lane {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: lightpink;
  width: 200px;
  overflow: auto;
}

.laneHeader {
  font-weight: bold;
  border: 1px solid black;
  padding: 0.5rem 0;
}

.laneFooter {
  font-weight: bold;
  border: 1px solid green;
}

.cardList {
  padding: 4px;
  min-height: 150px;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: auto;
  border: 1px solid blue;
}

.cardList .card {
  margin: var(--padding-card);
}

.card {
  background: lightgreen;
  border-radius: 4px;
  padding: 1rem 2rem;
}

To do

Card 1 Longer title...

Card 2

Card 3

Card 4

Card 5

Card 6

Card 7

Card 8

Card 9

Card 10

Card 11

Card 12

+ Add card

Doing

Card 11

Card 12

Card 13

Card 14

Card 15

Card 16

Card 17

+ Add card

Done

Card 21

Card 22

+ Add card

Quality

+ Add card


text:
Q: trying to use sbt assembly sbt version is 0.13.9 and scala 2.11.7/  I know previous versions of sbt relied on scala 2.10 - is that still the case?  I have a Java project for which I added an assembly.sbt file in the project directory (as per the sbt assembly instructions for this version of sbt assembly):
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.2")

I ran sbt reload/clean as well as compile.  However, when I try to run assembly, I get the following exception:
> assembly
[error] Not a valid command: assembly
[error] Not a valid project ID: assembly
[error] Expected ':' (if selecting a configuration)
[error] Not a valid key: assembly
[error] assembly
[error]         ^

what step(s) a I missing before I can create a runnable jar for my java project using sbt?
I can setup a merge strategy if one is needed but I received a different exception when I tried using that. Any helpful suggestions would be quite welcome.
Update
I had created the assemly.sbt file in the wrong location.  When I placed the assembly.sbt file in the same directory as the build.sbt, and ran reload/compile, I got the following error:
    [trace] Stack trace suppressed: run last *:update for the full output.
    [error] (*:update) sbt.ResolveException: unresolved dependency: com.eed3si9n#sbt-assembly;0.14.2: not found
    [error] Total time: 2 s, completed Mar 13, 2016 3:20:02 PM

**running with last *:update**
[warn]  Note: Some unresolved dependencies have extra attributes.  Check that these dependencies exist with the requested attributes.
[warn]      com.eed3si9n:sbt-assembly:0.14.2 (scalaVersion=2.11, sbtVersion=0.13)
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      com.eed3si9n:sbt-assembly:0.14.2 (scalaVersion=2.11, sbtVersion=0.13) (/home/me/test-server/assembly.sbt#L1-2)
[warn]        +- com.test:test-server_2.11:1.0.0
sbt.ResolveException: unresolved dependency: com.eed3si9n#sbt-assembly;0.14.2: not found
    at sbt.IvyActions$.sbt$IvyActions$$resolve(IvyActions.scala:294)
    at sbt.IvyActions$$anonfun$updateEither$1.apply(IvyActions.scala:191)
    at sbt.IvyActions$$anonfun$updateEither$1.apply(IvyActions.scala:168)
    at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:155)
    at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:155)
    at sbt.IvySbt$$anonfun$withIvy$1.apply(Ivy.scala:132)
    at sbt.IvySbt.sbt$IvySbt$$action$1(Ivy.scala:57)
    at sbt.IvySbt$$anon$4.call(Ivy.scala:65)
    at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:93)
    at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:78)
    at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:97)
    at xsbt.boot.Using$.withResource(Using.scala:10)
    at xsbt.boot.Using$.apply(Using.scala:9)
    at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:58)
    at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:48)
    at xsbt.boot.Locks$.apply0(Locks.scala:31)
    at xsbt.boot.Locks$.apply(Locks.scala:28)
    at sbt.IvySbt.withDefaultLogger(Ivy.scala:65)
    at sbt.IvySbt.withIvy(Ivy.scala:127)
    at sbt.IvySbt.withIvy(Ivy.scala:124)
    at sbt.IvySbt$Module.withModule(Ivy.scala:155)
    at sbt.IvyActions$.updateEither(IvyActions.scala:168)
    at sbt.Classpaths$$anonfun$sbt$Classpaths$$work$1$1.apply(Defaults.scala:1392)
    at sbt.Classpaths$$anonfun$sbt$Classpaths$$work$1$1.apply(Defaults.scala:1388)
    at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$90.apply(Defaults.scala:1422)
    at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$90.apply(Defaults.scala:1420)
    at sbt.Tracked$$anonfun$lastOutput$1.apply(Tracked.scala:37)
    at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:1425)
    at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:1419)
    at sbt.Tracked$$anonfun$inputChanged$1.apply(Tracked.scala:60)
    at sbt.Classpaths$.cachedUpdate(Defaults.scala:1442)
    at sbt.Classpaths$$anonfun$updateTask$1.apply(Defaults.scala:1371)
    at sbt.Classpaths$$anonfun$updateTask$1.apply(Defaults.scala:1325)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
    at sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:40)
    at sbt.std.Transform$$anon$4.work(System.scala:63)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:226)
    at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:226)
    at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
    at sbt.Execute.work(Execute.scala:235)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:226)
    at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:226)
    at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:159)
    at sbt.CompletionService$$anon$2.call(CompletionService.scala:28)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
[error] (*:update) sbt.ResolveException: unresolved dependency: com.eed3si9n#sbt-assembly;0.14.2: not found

Project structure
I will add screenshots later.  For now, please bear with me.
I tried creating the assembly.sbt file inside the project subdirectory  - it did not work.  Then I added it to the plugins.sbt inside the same project subdirectory.  When it did not work, I copied the assembly.sbt and plugin.sbt into the root directory of the project but it did not solve the issue.
Project directory: test-server
I have added assembly.sbt and build.sbt inside /test-server
I have also tried adding it ti /test-server/project
Neither worked.  I am reasonably sure I am doing something wrong or missing something in my config.  Kindly share your thoughts as to what needs to be done to resolve the issue.
assembly.sbt
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.2")

A: The issue was due to a typo in my assembly.sbt file.  The assembly.sbt file needs to be inside the project subdirectory i.e. if your project root directory is test-server, one needs to place the assembly.sbt file inside the test-server/project subdirectory.
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.2")


text:
Q: Rotate object to head to magnetic north in ARCore I want to rotate an object so it heads to magnetic north, for example I want to create a compass needle, how can I do that?
I can rotate objects in local space like below, but how to align to real world North:
Node solarControls = new Node();
solarControls.setParent(sun);
solarControls.setRenderable(solarControlsRenderable);
solarControls.setLocalPosition(new Vector3(0.0f, 0.25f, 0.0f));
Quaternion orientation1 = Quaternion.axisAngle(new Vector3(0.0f, 1.0f, 0.0f), 90);
solarControls.setLocalRotation(orientation1);


text:
Q: Is a locally invertible weak limit of injective maps injective almost everywhere? Let $\Omega_1,\Omega_2 \subseteq \mathbb R^2$ be open, connected, bounded, with non-empty $C^1$ boundaries.
Let $f_n:\bar\Omega_1 \to \bar\Omega_2$ be Lipschitz injective maps with $\det(df_n)>0$, and suppose that $f_n$ converges to a $C^1$ function $f: \bar\Omega_1 \to \bar\Omega_2$ weakly in $W^{1,2}$, and that $\det(df)>0$ everywhere on $\bar\Omega_1$.

Is it true that $|f^{-1}(y)| \le 1$ a.e. on $\Omega_2$?

Does the answer change if we assume in addition that $f_n|_{K} \to f|_{K}$ strongly in $W^{1,2}$ for every $K \subset \subset \Omega_1$?


text:
Q: How to read Firebase Node.js module? I am running a polymer starter kit app and I need a firebase connection, but I don't know why the browser say that require is undefined.
$ npm install firebase --save

var Firebase = require("firebase");

A: The problem is that require is a function provided by node.js's 'module' module. It is not part of the ES5 spec, and so it is not natively available in web browsers.
In order to load modules using require, you will have to use a web bundler (like Webpack, Browserify or RequireJS). This will  bundle together all of the JS in your project into a single file, automatically handling calls to require.
I'd recommend reading Getting started with Webpack to get you on your way.


text:
Q: Stop Pro-Guard from adding "compiled from:" to the classes So iv'e been enabling Pro-Guard to a project and after building the apk i decompiled it to make sure Pro-Guard did he's job and notices that it adds, for example, to the BaseAdapter class -

/* compiled from: BaseAdapter */

See picture -

Now I'm asking, doesn't it lose the point of the Pro-Guard if it says what class that was?
Is there any way to tell the Pro-Guard not to add this info line at all the classes?
My code where i added Pro-Guard -
buildTypes {
    debug {
        debuggable true
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        shrinkResources true
    }
    release {
        signingConfig signingConfigs.somethingsomething
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        shrinkResources true
    }
}

Thanks.

A: Proguard is not adding this line.
/* compiled from: BaseAdapter */

The decompiler is doing mapping of obfuscated name with original name. You are seeing it as you might be using jadx or online service like this
You can try using dex2jar and jd-gui to look at decompiled code. This line will not be present there.
Make sure that 'proguard-rules.pro' file does not have following attributes in it.
-keepattributes SourceFile

If you add this statement no decompiler will be able make this mapping.


text:
Q: Eclipse RCP, how to highlight occurrences (or write) of selection dynamically? As my question, I'd like to know, what need to be done to implement occurrences (or write) highlight dynamically, which like java editor does.
Current, there is good syntax highlight and basic code partitions (multiple line comment, single line comment, others). What do i need to do next for implementing the dynamical highlight?
Thanks a lot.


text:
Q: Create vector of all classes implementing an interface I have an interface "Vehicle" and classes implementing that interface Car, Bicycle, Bike etc.
Can I create a Vector of the interface and assign it instances of the implementing classes?
For ex:
Vector<Vehicle> vi;
vi.add(0, new Car());
vi.add(1, new Bicycle());

etc.
So at runtime, I can simply check the index and invoke the required function?

A: Sure, you can. It's a classical example of a polymorphism usage in runtime.
import java.util.Vector;

interface Vehicle {
    public int getNumberOfWheels();
}

class Car implements Vehicle {

    final int numberOfWheels = 4;

    public int getNumberOfWheels() {
        return numberOfWheels;
    }
}

class Bicycle implements Vehicle {

    final int numberOfWheels = 2;

    public int getNumberOfWheels() {
        return numberOfWheels;
    }
}

public class Program {

    public static void main(String args[]) {
        Vector<Vehicle> vi = new Vector<Vehicle>();
        vi.add(0, new Car());
        vi.add(1, new Bicycle());
        for(Vehicle v: vi) {
            System.out.println(v.getClass().getName()
                + " has " + v.getNumberOfWheels() + " wheels");
        }
    }
}

Demo

A: Yes, you can do that. Interfaces are meant to be used that way.
Now for suggesting better ways to do that: very difficult to do, as it is not very clear what you need to do exactly. The first suggestion would be to use ArrayList instead of Vector. The main difference between the two is that Vector is "synchronized", which means thread safe. However, synchronization has a big impact on performance, and the Vector class achieve full thread safety by synchronizing access to ALL its methods. It is generally better to use non-synchronized containers and, if you need thread safety, to manage your own synchronization outside the container, as you can put them only where you need them depending on your usage.
In the extreme case where your list has a fixed size known in advance, you can even use a simple array, i.e.:
Vehicle[] vi = new Vehicle[2];
vi[0] = new Car();
vi[1] = new Bicycle();


text:
Q: How to catch when an `` is selected through the keyboard? I have an interface where users click on an <option> to select a building from a list to get more information. This triggers a DOM click event on the <option> which I catch to provide relevant information. Some users press Up/Down to select an adjacent <option>. How can I catch this event? None of change, keypress, keydown, or focus fire.
var newOption = document.createElement('option');
// ....
newOption.addEventListener('change', handleMyEvent);

It's fine if the handler also fires when the user clicks since both should do the same thing.

A: You should attach an onchange event listener to the select element
<select id="mySelect" onchange="handleMyEvent()">
  <option value="1">Option 1
  <option value="2">Option 2
</select>

You can use this demo to experiment by selecting options with your keyboard at w3schools.com.

A: If you're trying to detect when the user navigates to the select via the mouse or keyboard, you'd need bind the function to the focus event. Then you can get the selected option.  Something like this would work:
HTML
<select id="foo"></select>

JavaScript
var select = document.getElementById('foo');

for(var i = 1; i <= 5; i++) {
    var newOption = document.createElement('option');
    newOption.innerHTML = "bar"+i;
  select.appendChild(newOption);
}

select.addEventListener('change', handleMyEvent);
select.addEventListener('focus', handleMyFocusEvent);

function handleMyEvent() {
    console.log(this.value)
}

function handleMyFocusEvent() {
    console.log('Select is focused')
    console.log(this.value)
}

JS Fiddle Example: https://jsfiddle.net/qzkL1y7w/1/
Hope that helps!

A: You need to add an onKeyUp event handler as well if you want to track it as the option is cycled.  The select element still has focus and a form element is not "changed" until it loses focus (depends on browser/version).
var newOption = document.createElement('option');
// ....
newOption.addEventListener('change', handleMyEvent);
newOption.addEventListener('keyup', handleMyEvent);


text:
Q: Specify PascalCase Naming Convetion for Variables of JSX.Element Type in eslint Rules I'd like to enforce PascalCase for variables of type JSX.Element in my React+Typescript project. I frequently use the following pattern to create functional components, and I like to distinguish my eponymous export by giving it a PascalCase name:
//MyComponent.tsx
//PascalCase for MyComponent
export const MyComponent= (): JSX.Element =>{
  return (

      My Component

  )
}
export default MyComponent

With my current linter settings, I get a warning that Variable name `MyComponent` must match one of the following formats: camelCase, UPPER_CASE. How can I add a rule to my linter settings that will enforce PascalCase for variables of type JSX.Element?
Here's my current .eslintrc.json:
{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint", "react-hooks"],
  "extends": [
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "rules": {
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn",
    "react/prop-types": "off",
    "@typescript-eslint/naming-convention": "warn",
    "@typescript-eslint/explicit-function-return-type": [
      "warn",
      {
        "allowExpressions": true
      }
    ]
  },
  "settings": {
    "react": {
      "pragma": "React",
      "version": "detect"
    }
  }
}

A: Looks like it is not currently possible at the point of declaration (see link below). However, the incorrect casing can't proliferate beyond the file in which it is declared, as lowercase names are reserved for intrinsic types like div, span, etc.
// my-component.tsx
export const myComponent: FC<{}> = () => (

My Component

);

export default myComponent;

// app.tsx
import { myComponent } from './my-component';

// Fails to compile with: Property 'myComponent' does not
// exist on type 'JSX.IntrinsicElements'.  TS2339
const App = (): JSX.Element => <myComponent />;

In the case of a default export, the name used in the declaring file is effectively erased, as it's simply assigned to whatever name is chosen in the importing file:
// app.tsx
import SomeOtherName from './my-component';

const App = (): JSX.Element => <SomeOtherName />;

Discussion about not having a rule specific to React components here: typescript-eslint/issues/2607

Additionally - there's no guarantee that a function that returns a
JSX.Element is in fact a react component. Utility functions that
return JSX.Element, but aren't react components are a relatively
common practice, which would cause false-positives.

A: I think eslint doesn't have settings for such case, but You can create custom rule and apply it. Please check following link for the same.
https://stackoverflow.com/a/49225308/13162789


text:
Q: Ошибка LNK2019 в работающей библиотеке Решил попробовать подключить эту библиотеку:
https://github.com/mrtazz/restclient-cpp
Подключал так:
Project -> properties -> VC++ Directories -> include Directories. Выбрал там путь к папке, а именно

C:\Users\Andrey\Desktop\REST_LIB\include

И при таком коде:
#include "stdafx.h"
#include "restclient-cpp/restclient.h"

int main()
{
    RestClient::Response r = RestClient::get("http://google.com");
    return 0;
}

Выбивает эту ошибку (P.S Кромешный ужас, сам боюсь):

Severity  Code    Description Project File    Line    Suppression State
  Error LNK2019 unresolved external symbol "struct RestClient::Response
  __cdecl RestClient::get(class std::basic_string,class std::allocator > const &)"
  (?get@RestClient@@YA?AUResponse@1@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
  referenced in function _main  ConsoleApplication1 D:\C++
  Projects\pomogite\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1.obj 1

Окей, если бы именно эта библиотека не подключалась - я бы просто забил. Но так делают почти все библиотеки в моих VS 2015 и 2017.
Что я делаю не так в этой жизни?


text:
Q: Get PR number from Github API push event I'm trying to create one or many comments in one or many files after a commit.
The way I'm doing the POST request now is through the PR's number, passing the body, commit_id, path, and position. And it works well hardcoding the number of the PR, because I have the commit_id, which is returned within the payload, when a PUSH event is sent through the webhook.
If I do the POST request to https://api.github.com/repos/author/repo/pulls/number/comments, it creates successfully the comment, within a specific line, as I need. But I must know they PR number beforehand.
The question is, is there a way to get the PR number if I have the commit_id, or any other received within the payload for a push event?
The current payload looks like:
{"ref"=>"refs/heads/third",
 "before"=>"0000000000000000000000000000000000000000",
 "after"=>"0000000000000000000000000000000000000001",
 "created"=>true,
 "deleted"=>false,
 "forced"=>false,
 "base_ref"=>nil,
 "compare"=>"https://github.com/author/repo/commit/831a7cb888ab",
 "commits"=>
  [{"id"=>"0000000000000000000000000000000000000001",
    "tree_id"=>"tree_id",
    "distinct"=>true,
    "message"=>"message",
    "timestamp"=>"2018-08-12T03:22:31-03:00",
    "url"=>"https://github.com/author/repo/commit/0000000000000000000000000000000000000001",
    "author"=>{"name"=>"author_name", "email"=>"", "username"=>"author"},
    "committer"=>{"name"=>"author_name", "email"=>"", "username"=>"author"},
    "added"=>["filename"],
    "removed"=>[],
    "modified"=>[]}],
 "head_commit"=>
  {"id"=>"0000000000000000000000000000000000000001",
   "tree_id"=>"tree_id",
   "distinct"=>true,
   "message"=>"#1",
   "timestamp"=>"2018-08-12T03:22:31-03:00",
   "url"=>"https://github.com/author/repo/commit/0000000000000000000000000000000000000001",
   "author"=>{"name"=>"author_name", "email"=>"", "username"=>"author"},
   "committer"=>{"name"=>"author_name", "email"=>"", "username"=>"author"},
   "added"=>["filename"],
   "removed"=>[],
   "modified"=>[]},
 "repository"=>
  {"id"=>repository_id,
   "node_id"=>"node_id==",
   "name"=>"repo",
   "full_name"=>"author/repo",
   "owner"=>
    {"name"=>"author",
     "email"=>"",
     "login"=>"author",
     "id"=>id,
     "node_id"=>"MDQ6VXNlcjExODg4MTkx",
     "avatar_url"=>"https://avatars2.githubusercontent.com/u/id?v=4",
     "gravatar_id"=>"",
     "url"=>"https://api.github.com/users/author",
     "html_url"=>"https://github.com/author",
     "followers_url"=>"https://api.github.com/users/author/followers",
     "following_url"=>"https://api.github.com/users/author/following{/other_user}",
     "gists_url"=>"https://api.github.com/users/author/gists{/gist_id}",
     "starred_url"=>"https://api.github.com/users/author/starred{/owner}{/repo}",
     "subscriptions_url"=>"https://api.github.com/users/author/subscriptions",
     "organizations_url"=>"https://api.github.com/users/author/orgs",
     "repos_url"=>"https://api.github.com/users/author/repos",
     "events_url"=>"https://api.github.com/users/author/events{/privacy}",
     "received_events_url"=>"https://api.github.com/users/author/received_events",
     "type"=>"User",
     "site_admin"=>false},
   "private"=>true,
   "html_url"=>"https://github.com/author/repo",
   "description"=>nil,
   "fork"=>false,
   "url"=>"https://github.com/author/repo",
   "forks_url"=>"https://api.github.com/repos/author/repo/forks",
   "keys_url"=>"https://api.github.com/repos/author/repo/keys{/key_id}",
   "collaborators_url"=>"https://api.github.com/repos/author/repo/collaborators{/collaborator}",
   "teams_url"=>"https://api.github.com/repos/author/repo/teams",
   "hooks_url"=>"https://api.github.com/repos/author/repo/hooks",
   "issue_events_url"=>"https://api.github.com/repos/author/repo/issues/events{/number}",
   "events_url"=>"https://api.github.com/repos/author/repo/events",
   "assignees_url"=>"https://api.github.com/repos/author/repo/assignees{/user}",
   "branches_url"=>"https://api.github.com/repos/author/repo/branches{/branch}",
   "tags_url"=>"https://api.github.com/repos/author/repo/tags",
   "blobs_url"=>"https://api.github.com/repos/author/repo/git/blobs{/sha}",
   "git_tags_url"=>"https://api.github.com/repos/author/repo/git/tags{/sha}",
   "git_refs_url"=>"https://api.github.com/repos/author/repo/git/refs{/sha}",
   "trees_url"=>"https://api.github.com/repos/author/repo/git/trees{/sha}",
   "statuses_url"=>"https://api.github.com/repos/author/repo/statuses/{sha}",
   "languages_url"=>"https://api.github.com/repos/author/repo/languages",
   "stargazers_url"=>"https://api.github.com/repos/author/repo/stargazers",
   "contributors_url"=>"https://api.github.com/repos/author/repo/contributors",
   "subscribers_url"=>"https://api.github.com/repos/author/repo/subscribers",
   "subscription_url"=>"https://api.github.com/repos/author/repo/subscription",
   "commits_url"=>"https://api.github.com/repos/author/repo/commits{/sha}",
   "git_commits_url"=>"https://api.github.com/repos/author/repo/git/commits{/sha}",
   "comments_url"=>"https://api.github.com/repos/author/repo/comments{/number}",
   "issue_comment_url"=>"https://api.github.com/repos/author/repo/issues/comments{/number}",
   "contents_url"=>"https://api.github.com/repos/author/repo/contents/{+path}",
   "compare_url"=>"https://api.github.com/repos/author/repo/compare/{base}...{head}",
   "merges_url"=>"https://api.github.com/repos/author/repo/merges",
   "archive_url"=>"https://api.github.com/repos/author/repo/{archive_format}{/ref}",
   "downloads_url"=>"https://api.github.com/repos/author/repo/downloads",
   "issues_url"=>"https://api.github.com/repos/author/repo/issues{/number}",
   "pulls_url"=>"https://api.github.com/repos/author/repo/pulls{/number}",
   "milestones_url"=>"https://api.github.com/repos/author/repo/milestones{/number}",
   "notifications_url"=>"https://api.github.com/repos/author/repo/notifications{?since,all,participating}",
   "labels_url"=>"https://api.github.com/repos/author/repo/labels{/name}",
   "releases_url"=>"https://api.github.com/repos/author/repo/releases{/id}",
   "deployments_url"=>"https://api.github.com/repos/author/repo/deployments",
   "created_at"=>1501475657,
   "updated_at"=>"2018-07-17T01:30:41Z",
   "pushed_at"=>1534054956,
   "git_url"=>"git://github.com/author/repo.git",
   "ssh_url"=>"git@github.com:author/repo.git",
   "clone_url"=>"https://github.com/author/repo.git",
   "svn_url"=>"https://github.com/author/repo",
   "homepage"=>nil,
   "size"=>55534,
   "stargazers_count"=>0,
   "watchers_count"=>0,
   "language"=>"JavaScript",
   "has_issues"=>true,
   "has_projects"=>true,
   "has_downloads"=>true,
   "has_wiki"=>true,
   "has_pages"=>false,
   "forks_count"=>0,
   "mirror_url"=>nil,
   "archived"=>false,
   "open_issues_count"=>0,
   "license"=>nil,
   "forks"=>0,
   "open_issues"=>0,
   "watchers"=>0,
   "default_branch"=>"master",
   "stargazers"=>0,
   "master_branch"=>"master"},
 "pusher"=>{"name"=>"author", "email"=>""},
 "sender"=>
  {"login"=>"author",
   "id"=>id,
   "node_id"=>"MDQ6VXNlcjExODg4MTkx",
   "avatar_url"=>"https://avatars2.githubusercontent.com/u/id?v=4",
   "gravatar_id"=>"",
   "url"=>"https://api.github.com/users/author",
   "html_url"=>"https://github.com/author",
   "followers_url"=>"https://api.github.com/users/author/followers",
   "following_url"=>"https://api.github.com/users/author/following{/other_user}",
   "gists_url"=>"https://api.github.com/users/author/gists{/gist_id}",
   "starred_url"=>"https://api.github.com/users/author/starred{/owner}{/repo}",
   "subscriptions_url"=>"https://api.github.com/users/author/subscriptions",
   "organizations_url"=>"https://api.github.com/users/author/orgs",
   "repos_url"=>"https://api.github.com/users/author/repos",
   "events_url"=>"https://api.github.com/users/author/events{/privacy}",
   "received_events_url"=>"https://api.github.com/users/author/received_events",
   "type"=>"User",
   "site_admin"=>false},
 "installation"=>{"id"=>installation_id}}

The request's body is very simple and looks like:
{
    "body": "body message",
    "commit_id": "commit_id",
    "path": "file",
    "position": position_as_integer
}

A: Yes, you can leverage this endpoint which will give you a list of all PRs containing that COMMIT_SHA.
From here you can filter find the associated number (ie for the first PR response[0]["number"]).
Here is python-code to get the first associated PR:
import requests

def build_headers(token, username, password):
    """Format secret(s) for headers of API call."""
    if token:
        headers = {
            "Authorization": f"token { token }",
        }
    elif username and password:
        headers = {"Authorization": f"Basic { username }:{ password }"}
    else:
        raise Exception(
            "Either Authentication Token or Username + Password need to be included in request."
        )
    return headers

def get_pr_id_from_commit_id(
    organization,
    repository,
    commit_id,
    token=None,
    username=None,
    password=None,
    **kwargs,
):
    """Gets a pull_request id, by pulling PRs that include commit_id."""
    headers = build_headers(token, username, password)
    curr_endpoint = f"{ base_url }/repos/{ organization }/{ repository }/commits/{commit_id}/pulls"
    logging.info(f"URL: { curr_endpoint }")
    response = requests.get(curr_endpoint, headers=headers)
    pr_id = json.loads(response.text)[0]["number"]
    return pr_id


text:
Q: "Ballot numbers" sum up to Catalan numbers Summing certain numbers and comparing the results with OEIS, I found that
$
\sum_{k=1}^n \frac{k^2}{n} \binom{2n-k-1}{n-1} = C_{n+1} - C_{n},
$
where $C_n$ denotes the $n^{\textrm{th}}$ Catalan Number. How can I prove this equation? And is there any combinatorial interpretation?
Some background information: The number $\frac{k}{n} \binom{2n-k-1}{n-1}$ denotes the number of unranked trees of size $n$ with a root degree $k$ (these numbers are known as ballot numbers, see e.g. the book Analytic Combinatorics from Flajolet and Sedgewick, page 68). So one must have $\sum_{k=1}^n \frac{k}{n} \binom{2n-k-1}{n-1} =  C_{n}$, since there are $C_n$ many trees of size $n$.

A: Notice that:
$$
   \sum_{k=1}^n \frac{k^2}{n} \binom{2n-k-1}{n-1} \stackrel{k \to n+1-k}{=} \sum_{k=1}^n \frac{(n+1-k)^2}{n} \binom{n+k-2}{n-1} \stackrel{\binom{a}{b} = \binom{a}{a-b}}{=} \sum_{k=1}^n \frac{(n+1-k)^2}{n} \binom{n+k-2}{k-1} = \sum_{k=0}^{n} \frac{(n-k)^2}{n} \binom{n+k-1}{k}
$$
This this nothing but a convolution of two sequences $a_{k} = \frac{k^2}{n}$ and $b_{k} = \binom{n+k-1}{k}$. Therefore the generating function for the sum $c_n = \sum_{k=0}^{n} a_{n-k} b_k$ is the product of generating functions of $a_k$ and $b_k$:
$$
   \sum_{k=0}^\infty x^k a_k = \frac{1}{n} \sum_{k=0}^\infty x^k k^2 = \frac{1}{n} \left( x\frac{\mathrm{d}}{\mathrm{d} x}\right)^2 \sum_{k=0}^\infty x^k = \frac{1}{n} \frac{x(1+x)}{(1-x)^3}
$$
$$
   \sum_{k=0}^\infty \binom{n+k-1}{k} x^k = \frac{1}{(1-x)^n}
$$
Thus:
$$
    c_n = [x]^n \left( \frac{1}{n} \frac{x(1+x)}{(1-x)^3}  \frac{1}{(1-x)^n} \right) = [x]^n \left( \frac{1}{n} \frac{x}{(1-x)^{n+3}} + \frac{1}{n} \frac{x^2}{(1-x)^{n+3}} \right) = \frac{1}{n} \left(\binom{2n+1}{n-1} + \binom{2n}{n-2}  \right)
$$
Now, using
$$
   \binom{2n}{n-2} = \binom{2n+1}{n-1} - \frac{2n}{n-1} \binom{2n-1}{n-2}
$$
which is easily proven using recurrence relation for factorials comprising binomial coefficients,  we get
$$
   c_n = \frac{2}{n} \binom{2n+1}{n-1} - \frac{2}{n-1} \binom{2n-1}{n-2} = C_{n+1} - C_{n}
$$

A: Consider the space of lattice points $(p,q)$ where $0 \leq p \leq q, q = 0, 1, \dots$;
the number of (shortest) paths in this space from $(p,q)$ to $(0,0)$ is the ballot number
$$N(p,q) = \frac{q-p+1}{q+1} \cdot \binom{p+q}{p}; \quad N(0,0) =_D 1.$$
Using this notation we have $ N(n-k,n-1) = \frac{k}{n} \binom{2n-k-1}{n-1} $.
The problem asks to show
$$\sum_{k=1}^n k N(n-k, n-1) =  C_{n+1} - C_{n}.$$
Note that $ C_{n} $ is the nth Catalan number and that $ C_{n} = N(n,n) $, so
$ C_{n+1} - C_{n} $ is the number of paths from point $(n-1, n+1)$ to $(0,0)$ (all paths from
$(n+1, n+1)$ to $(0,0)$ which don't use point $(n,n)$ must use point $(n-1, n+1)$).
Any path from point $(n-1, n+1)$ to point $(0,0)$ must use one and only one of the arcs $a(k)$
which start from point $(k, n)$ and stop in point $(k, n-1)$, where $0 \leq k \leq n-1$.
But the number of such paths is $(n-k)N(k,n-1)$ because the number of paths from $(n-1, n+1)$
to point $(k, n)$ is $(n-k)$, and the number of paths from point $(k,n)$ which use arc $a(k)$ is
$N(k,n-1)$, so the total number of paths from point $(n-1, n+1)$ to $(0,0)$ is
$\sum_{k=0}^{n-1} (n-k) N(k,n-1)$.

Voineasa.


text:
Q: Do parentheses need spaces either side? I should place parentheses after a space or without any spacing? Which one of below sentences is right?

*

*We adopted DM (Data Mining) in this lecture.

*We adopted DM(Data Mining) in this lecture.

A: The first. Parentheses should have spaces on either side, just like words. For example (taken from The Punctuation Guide):

Parentheses (always used in pairs) allow a writer to provide additional information. The parenthetical material might be a single word, a fragment, or multiple complete sentences.

A: Yes, parentheses have spaces before and after the enclosure (your example #1).  However, there is never a space between a closing parenthesis and another piece of punctuation (like the period in this or the last sentence).
Unrelated to your question, the actual word for an acronym is normally used first and then is followed by the acronym presented in parentheses.  This is to establish what the acronym will mean for the rest of the paper.

The lecture encouraged us to adopt Data Mining (DM), but I was still on the fence.  DM is an important feature in...


text:
Q: Different node types in a ExtJS 4.1 TreeStore I have a tree datastructure with nested data.
TreeNodes and DataNodes. Like in a filesystem, the TreeNodes are the folders and the DataNodes are the files.
But the JSON structure is like this:

{
  name: 'root',
  data: [
    [a, b, 100, 23],
    [a, b, 100, 23],
    [a, b, 100, 23]
    ...
  ]
  children: [
    {
      name: 'child1',
      data: [...],
      children: [...]
    },
    {
      name: 'child2',
      data: [...],
      children: [...]
    },
    ...
  ]
}

I want to parse the children to TreeNodes and the data arrays to DataNodes, and use them in one TreeStore.
Is this possible?
ATM I got TreeNodes and every Tree node has an association for its data records, which is a suboptimal solution.

A: I have a similar situation. What you need to do is create a model class that encompass both data types (extract overlapping properties). As far as the tree store it wont distinguish record types, but you can customize the look of the tree through icons to give each record type a distinct look. The data must be the same though, for example Name property must be the same for both record types.
Since your JSON structure from server response is somewhat odd you have to parse it yourself and shape into the structure the treestore expects. Alternatively, you'll need to get control of your server side implementation and tweak it there.


text:
Q: sencha architect store config as an object I'm trying to do this:
...
store: ZAdmin.store.TreeFactory.create('ZAdmin.model.Category', 'Application\\Entity\\Category')
...

But getting:
...
store: 'ZAdmin.store.TreeFactory.create(\'ZAdmin.model.Category\', \'Application\\Entity\\Category\')'
...

There is no way to change store from string to object type.
How to fix it?
P.S. I'm about editing config properties in GUI. Sencha Architect assumes store to be a string, so auto-escapes any value.

A: store config takes store object or its name, so in case you want to pass an object you can either create it in-place OR in initialize method you can do this:
var myStore = ZAdmin.store.TreeFactory.create('ZAdmin.model.Category', 'Application\\Entity\\Category'); // Any kind of store creation
this.setStore(myStore);
myStore.load();   // Optional

having late store association/load gives you advantage of quickly showing the view without waiting for data to load.

A: If you are keen to keep the initialisation in the definition then the best bet if you create an override class for your object. I.e. on the top of the code edit window press the "Create override" button then enter your own initialisation code there under config. E.g. if you want to set a dataview object's store on this way then create the override for the dataview with a code like this:
Ext.define('MyApp.view.MyDataView', {
extend: 'Ext.dataview.DataView',

config: {
    store: ZAdmin.store.TreeFactory.create('ZAdmin.model.Category', 'Application\\Entity\\Category')
}
});

To be able to override your control on this way you need to promote it to class first (right click in the control -> promote to class -> create override for the newly created class).


text:
Q: Making an immitation "Craigslist Program" - how can I seperate results from inputs? I am writing an imitation craigslist project. I need to ask a user if they want to:
1. Enter a product
2. Buy a product
When the user types 1, they are asked if they want to sell a (b)ike or a (t)ruck, they give an input, and are then asked for a price.
I used append to add this to a list.
However, I can't get the inputs for if a user types "2" to work,
it completely disregards what I have asked it to print if the user types "2" and instead asks if they want to sell a (b)ike or (t)ruck.
heres a look at my code :
play = True
productList =[['bike', 50]] #supposed to be a bike on the list already

print "Would you like to:"
print "1. Add an item."
print "2. Find an item."

choice = raw_input ("Enter your selection")

while play:
    if choice == "1":
    play = True
    print "What would you like to sell, a bike or truck?"
    item = raw_input ("enter the item type, b or t.)

    elif item == "b":
        price = raw_input ("enter item cost:")
        bikePrice = "bike" ,price
        productList.append (bikePrice)
        print "Your product has been added to Craigslist"
    elif item == "t":
        price = raw_input ("enter item cost:"
        bikePrice = "bike" ,price
        productList.append (bikePrice)
        print "Your product has been added to Craigslist"

if choice == "2":
    play = True
    print "yay"

so essentially, the program completely disregards the fact that when I type a "2" it is supposed to print yay. How can I make my program only show the options for "Enter a item" (1) if the user types (1), and only show the options for "Find an item" (2) if the user types (2)?
I know there is an easy fix to this, but I'm two weeks into coding and very clueless :)
Thank you!

A: I cleaned things up a bit to get it running. Notice where I set play to False so that you don't have an infinite loop.
play = True
productList =[['bike', 50]] #supposed to be a bike on the list already

print "Would you like to:"
print "1. Add an item."
print "2. Find an item."

choice = raw_input ("Enter your selection")

while play:
    if choice == "1":
        play = False
        print "What would you like to sell, a bike or truck?"
        item = raw_input ("enter the item type, b or t.")
        if item == "b":
            price = raw_input ("enter item cost:")
            bikePrice = ["bike", price]
            productList.append(bikePrice)
            print "Your product has been added to Craigslist"
        elif item == "t":
            price = raw_input ("enter item cost:")
            truckPrice = "truck", price
            productList.append(truckPrice)
            print "Your product has been added to Craigslist"
    if choice == "2":
        play = False
        print "yay"


text:
Q: Simplify/Automate the branching in this If Statement have posted about this before, and have received some very good awnsers recently though I still have not completely solved the issue. I now have some somewhat workable code, that I though someone on this site may be able to fix, or show me how to fix lol.
Okay basically a rundown as to what I am aiming to accomplish, because I have been told many times that what i am doing is useless or that I have not provided enough information, I will try my best here. I have a program that creates invoices on PDF files and prints them out. The python script is fed from a CSV file of all necessary customer/service info etc.
Now, The issue in my code so far, is the number of services I have, and the fact that in Python Reportlabs, You must choose the location of where to draw the string on the page. A command example for this would be:
cursor.drawstring(xLocation,yLocation,String)

The common practice would be draw string 1 through string six, one by one underneath the one above it. In the next three examples you see, the first is how the function would output if all services are being charged. The second(Middle) is the output if some services are not being charged to the customer. the final(RightMost) example is the code How I would like it outputted.
Service 1         Service 1        Service 1
Service 2                          Service 3
Service 3         Service 3        Service 4
Service 4         Service 4        Service 6
Service 5
Service 6         Service 6

Unfortunaly, based on boolean logic, and the fact that there are 6 possible services, and each can be charged or not charged, empty or full if you prefer, Then there are 64 possible ways of writing this same function to achieve perfect output.
If we make a boolean for each service, 0 being empty and 1 being full,
then we would have to test every possibilty from 000000-111111. That is 64. Which is completely reasonable to code out.
However, I need much more than six services, and the number of functions needed grows exponentially. Instead of writing each function, I have been working on a program that will take a file of 0 and 1 sets, ie:
0000000000
0000000001
0000000010
etc..

and test each bit in each line. this function will then write out a function for each line in the file, based on the bits in the line. Right now, it produces incorrect output. I will show you my script first:
def testFIle():
# This Function will be used to enumerate through the same file you
used to create the switch dictionary,
# but will define a function for each line.

# filepath = '/home/smiley/Desktop/sampletenbools'
filepath = '/home/smiley/Desktop/10boolsALL'
with open(filepath) as fp:
    num = 1
    for cnt, line in enumerate(fp):
        var = line
        b1 = str(var)[0]
        b2 = str(var)[1]
        b3 = str(var)[2]
        b4 = str(var)[3]
        b5 = str(var)[4]
        b6 = str(var)[5]
        b7 = str(var)[6]
        b8 = str(var)[7]
        b9 = str(var)[8]
        b10 = str(var)[9]

        # YdrawLocationSVC1=490
        # YdrawLocationSVC2=475
        # YdrawLocationSVC3=460
        # YdrawLocationSVC4=445
        # YdrawLocationSVC5=430
        # YdrawLocationSVC6=415
        # YdrawLocationSVC7=400
        # YdrawLocationSVC8=375
        # YdrawLocationSVC9=360
        # YdrawLocationSVC10=345

        if b1 == "0":
            YdrawLocationSVC1=1111
            YdrawLocationSVC2=1
        if b1 == "1":
            YdrawLocationSVC1 = 1

        if b2 == "0":
            YdrawLocationSVC2=1111
            YdrawLocationSVC3=2
        if b2 == "1":
            YdrawLocationSVC2 = 2

        if b3 == "0":
            YdrawLocationSVC3=1111
            YdrawLocationSVC4=3
        if b3 == "1":
            YdrawLocationSVC3 = 3

        if b4 == "0":
            YdrawLocationSVC4=1111
            YdrawLocationSVC5=4
        if b4 == "1":
            YdrawLocationSVC4 = 4

        if b5 == "0":
            YdrawLocationSVC5=1111
            YdrawLocationSVC6=5
        if b5 == "1":
            YdrawLocationSVC5 = 5

        if b6 == "0":
            YdrawLocationSVC6=1111
            YdrawLocationSVC7=6
        if b6 == "1":
            YdrawLocationSVC6 = 6

        if b7 == "0":
            YdrawLocationSVC7=1111
            YdrawLocationSVC8=7
        if b7 == "1":
            YdrawLocationSVC7 = 7

        if b8 == "0":
            YdrawLocationSVC8=1111
            YdrawLocationSVC9=8
        if b8 == "1":
            YdrawLocationSVC8 = 9

        if b9 == "0":
            YdrawLocationSVC9=1111
            YdrawLocationSVC10=9
        if b9 == "1":
            YdrawLocationSVC9 = 9

        if b10 == "0":
            YdrawLocationSVC10=1111
        if b10 == "1":
            YdrawLocationSVC10 = 10

        print "# Bitrep ="+str(var).strip("\n")
        print "def Print"+str(num)+"():"
        print"\tc.setFont('Deja', 12, leading=None)"
        print "\t# SERVICE NAME"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC1)+", stringn1)"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC2)+", stringn2)"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC3)+", stringn3)"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC4)+", stringn4)"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC5)+", stringn5)"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC6)+", stringn6)"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC7)+", stringn7)"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC8)+", stringn8)"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC9)+", stringn9)"+\
        "\n\tc.drawString(100, "+str(YdrawLocationSVC10)+", stringn10)"

        # print("{} : {}".format(str(line).strip("\n"), "Print" + str(num)))
        num += 1
        # print "\n"

testFIle()

Currntly this code produces proper Output like this here so long as only one service is missing:
# Bitrep =1111111101
def Print1022():
c.setFont('Deja', 12, leading=None)
# SERVICE NAME
c.drawString(100, 1, stringn1)
c.drawString(100, 2, stringn2)
c.drawString(100, 3, stringn3)
c.drawString(100, 4, stringn4)
c.drawString(100, 5, stringn5)
c.drawString(100, 6, stringn6)
c.drawString(100, 7, stringn7)
c.drawString(100, 9, stringn8)
c.drawString(100, 1111, stringn9)
c.drawString(100, 10, stringn10)
# Bitrep =1111111110
def Print1023():
c.setFont('Deja', 12, leading=None)
# SERVICE NAME
c.drawString(100, 1, stringn1)
c.drawString(100, 2, stringn2)
c.drawString(100, 3, stringn3)
c.drawString(100, 4, stringn4)
c.drawString(100, 5, stringn5)
c.drawString(100, 6, stringn6)
c.drawString(100, 7, stringn7)
c.drawString(100, 9, stringn8)
c.drawString(100, 9, stringn9)
c.drawString(100, 1111, stringn10)
# Bitrep =1111111111
def Print1024():
c.setFont('Deja', 12, leading=None)
# SERVICE NAME
c.drawString(100, 1, stringn1)
c.drawString(100, 2, stringn2)
c.drawString(100, 3, stringn3)
c.drawString(100, 4, stringn4)
c.drawString(100, 5, stringn5)
c.drawString(100, 6, stringn6)
c.drawString(100, 7, stringn7)
c.drawString(100, 9, stringn8)
c.drawString(100, 9, stringn9)
c.drawString(100, 10, stringn10)

However the logic in my code breaks with more than one missing service, like this here:
# Bitrep =1111100101
def Print998():
c.setFont('Deja', 12, leading=None)
# SERVICE NAME
c.drawString(100, 1, stringn1)
c.drawString(100, 2, stringn2)
c.drawString(100, 3, stringn3)
c.drawString(100, 4, stringn4)
c.drawString(100, 5, stringn5)
c.drawString(100, 1111, stringn6)
c.drawString(100, 1111, stringn7)
c.drawString(100, 9, stringn8)
c.drawString(100, 1111, stringn9)
c.drawString(100, 10, stringn10)
# Bitrep =1111100110
def Print999():
c.setFont('Deja', 12, leading=None)
# SERVICE NAME
c.drawString(100, 1, stringn1)
c.drawString(100, 2, stringn2)
c.drawString(100, 3, stringn3)
c.drawString(100, 4, stringn4)
c.drawString(100, 5, stringn5)
c.drawString(100, 1111, stringn6)
c.drawString(100, 1111, stringn7)
c.drawString(100, 9, stringn8)
c.drawString(100, 9, stringn9)
c.drawString(100, 1111, stringn10)

If anyone can Fix this so that the output comes out looking like this next bit for all lines in the file, I will upvote the **** out of you lol:
def Print999():
c.setFont('Deja', 12, leading=None)
# SERVICE NAME
c.drawString(100, 1, stringn1)
c.drawString(100, 2, stringn2)
c.drawString(100, 3, stringn3)
c.drawString(100, 4, stringn4)
c.drawString(100, 5, stringn5)
c.drawString(100, 1111, stringn6)
c.drawString(100, 1111, stringn7)
c.drawString(100, 6, stringn8)
c.drawString(100, 7, stringn9)
c.drawString(100, 1111, stringn10)

def Print764():
c.setFont('Deja', 12, leading=None)
# SERVICE NAME
c.drawString(100, 1, stringn1)
c.drawString(100, 2, stringn2)
c.drawString(100, 1111, stringn3)
c.drawString(100, 3, stringn4)
c.drawString(100, 4, stringn5)
c.drawString(100, 1111, stringn6)
c.drawString(100, 1111, stringn7)
c.drawString(100, 5, stringn8)
c.drawString(100, 6, stringn9)
c.drawString(100, 1111, stringn10)

As always, if you made it to the end of my post I am more than impressed lol. Thank you to anyone who puts even the slightest effort into this, and to all the people who have helped me get this far already.

A: Not wanting to deflate your efforts, but people have been telling you you're doing it wrong for a reason :)
Reportlab lets you use programming tools to create dynamic PDF documents, meaning that the layout changes when the content changes. Attempting to hard-code the position of every line when you're expecting a variety of different content will become unwieldy/impossible very quickly and break easily.
Make it easy on yourself and use a loop instead. As a simplest case, here is some code for a basic page list...
from reportlab.lib.units import cm

# get the data selection first
my_services_list = [1,3,6]  # or my_dict, e.g. services {'1': 'message1', etc}

# set the cursor starting position
pos_X, pos_Y = 5, 15

for service in my_services_list:
    c.drawString(pos_X*cm, pos_Y*cm, service)
    # move the cursor down a line - remember that zero is the page bottom
    pos_Y -= 1

And that's it, no blank lines. .drawString will work fine for simpler pages. If you need a more comprehensive approach, read the documentation on Frames and Flowables. You can flow your text into text boxes if you need to, just as you would with desktop publishing software.


text:
Q: League of Legends damage modifiers while channeling If a damage buff or debuff (e.g. exhaust) is applied to a champion while they are channeling a spell (after they started the channeling) like ww' ult, kata's ult or fiddle's ult is the damage for that spell adjusted mid-channeling, or the buff/debuff has to be applied before they started channeling in order to take effect for that spell damage. What about spells that involve traveling projectiles like ez, ashe, draven, ziggs ulties? Or delayed spells like leona's ult?
I ask this as I mainly play support and when I see one of those ults, if I can't cc to stop them, I apply exhaust while they are channeling to lower their ult's damage for the remaining of the channel and I was just wondering if that works or I am just wasting my summoner's spell.
Also, as a side-note, how do you even test for something like this, or where do you get an (semi-)official answer?

A: So I tried this stuff out a bit and I came to the following conclusion:
Every damage modification is applied Instantly
This means that the damage of a spell/dot/projectile is applied for the exact duration of the damage buff or debuff. The damage of an Ashe arrow for example is reduced only if she is exhausted on its impact. Dots work similar (I tried this with teemo shrooms): When someone walks into your shroom and you buy an item with ability power during the DOT time the dot will become stronger as soon as you have the item in your inventory (Same goes for leveling up a skill. I had this with malzahar e before). The dot damage is lowered for the duration of the exhaust on teemo and is also applied immediately.
This also means that if an ezreal fires an ult for example it won't help if you exhaust him while he's channeling if the ult hits 4 seconds later.
TL;DR
Exhaust reduces damage while it's on the enemy. Not before and not after.

A: Jutschge has the right answer but just to make a more general one.
Damage on abilities/auto attacks are calculated at the time the damage is taken, not when it is cast.
Channeling abilities are damage over time not continuous as they look so every tick of damage will go through all the math required to determine how much damage it will do (eg armor/mr, debuffs, pen etc).
Ex1) Jinx shoots her ult across the map, but you exhaust her before it hits the target, the damage will be reduced by 30%
Ex2) Lucian is channeling the culling(his ult), and you exhaust mid channel, all subsequent shots will have 30% reduced damage. (Note: the amount of shots based on attack speed will not change as this is calculated at the time of cast)


text:
Q: Vanilla JS query selector not grabbing the elements in the dom? I'm trying to use document.querySelectorAll('a') in this mobile site: https://pwa.www.1800flowers.com, but its only grabbing 3 anchor elements. Its weird because by looking at the console, there's many anchor elements. I wanted to grab a specific one, but just doing this simple query selector, its only grabbing 3.
Any ideas on why this is happening? Or if I wanted to go about grabbing a specific anchor element, how would I go about doing so?

A: They are using iron pages
https://github.com/PolymerElements/iron-pages
In my searches, I found something like:
this.$$('a');

returns:
(435) [a, a, a, a, a, a, a, a, a, a, a, a, a, a#radio-icon, a#cart-icon, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, …]


text:
Q: How to validate a text area and throw error while writing? I have a text area and I want that if it reaches max length to show a error(not after pressing submit)
Code:
HTML
  <textarea maxlength="5000" id="summernote"  rows="4" cols="30"></textarea>

JS
 $(document).ready(function () {
    var area = document.getElementById("summernote");
    var message = document.getElementById("message");
    var maxLength = 5000;
    var checkLength =()=> {
        if (area.value.length < maxLength) {
            message.innerHTML = "5000 karaktere";
        }
        }
        setInterval(checkLength, 300);
    })

A: Instead of using a setInterval, use the input event. Also, you are currently checking if the length of the entered string is less than the maxlength when you should be checking if it is equal.

document.querySelector("#summernote").addEventListener("input", function(e){
  if(this.value.length == this.maxLength){
    document.querySelector("#message").textContent = `Max length of ${this.maxLength} characters reached.`;
  }
});
<textarea maxlength="10" id="summernote"  rows="4" cols="30"></textarea>

A: Your code works fine except for one thing wrong, you need to switch the "less than" sign to a "greater than" sign and it will work.
if (area.value.length < maxLength) {

to
if (area.value.length > maxLength) {

This works in my browser when I test it. The original code posted displays the message whenever the limit is not reached, but I believe you wanted the error message displayed when the limit is exceeded, so switching the "less than" sign to a "greater than" sign will solve the issue.
Also, one change I suggest making to the code is use your maxLength variable in the error message so you are not writing 5000 twice in the code.
In other words, instead of saying
message.innerHTML = "5000 karaktere";

You can write
message.innerHTML = maxLength + " karaktere";

Bruce


text:
Q: Windows 10 Pro getting half the original internet speed My PC suddenly started only getting at maximum 300Mbps (mostly 270Mbps), while every other computer on the network gets 500Mbps.
The same cable on the same switch on another computer gets the 500Mbps, only my desktop doesn't even reach 300Mbps.
Already tried answers from other questions and no luck, sometimes even got worse results.
My motherboard is Asus ROG STRIX X470-F Gaming.
My switch is TL-SG108E.
The cable that gets the connection from the router to the switch is Cat.5E.
EDIT: On safe-boot with network I get the 500Mbps. So I already ruled out hardware failure, it's some configuration on windows.

A: As booting in Safe Mode fixes the problem, this indicates
that some third-party application or driver is responsible for it.
Check first the driver for your network adapter. See if the Support website
of the computer manufacturer has a newer version of it.
Otherwise, to locate a problematic application, you may use the free tool
Autoruns for Windows.
This utility shows all programs configured to run during system bootup or login
in its "Everything" tab.
You may turn off startup items with a click and return
them later with another click. You may avoid listing Microsoft products by
using the menu Options > Hide Microsoft Entries,
Hide Empty Locations and Hide Windows Entries
I would suggest turning off startup entries in bunches, drilling down to the startup
program that causes this behavior. Once identified, it might have some setting
that can avoid the problem, or can be left out of startup and only be invoked
when required.
I would start with disabling any security package you have installed and any other
internet-watching products.


text:
Q: How obtain directly the model from a query? -> CodeIgniter Can I obtain the model directly from a query in Code Igniter?
Model
<?php
class User_Model extends CI_Model {

    public $user_id;
    public $name;
    public $team_id

    public function getTeamName() {
        $this->db->select('name');
        $this->db->from('team');
        $this->db->where('team_id',$this->team_id);
        $query = $this->db->get();
        $team = $query->row();
        if($empresa == null){
            return "";
        } else {
            return $team->name;
        }
    }

public function getUser($id) {
    $query = $this->db->get_where('users', array('user_id' => $id));
    $user = $query->row();
    return $user;
}

I would like getUser($id) function returns a user object like 'new User_Model()' to be able to use getTeamName() function in the view. Can I do it?
Now returns an object, but not a User_Model() object.

A: is wrong call a method in the model from the view.
in the model use
function getUser($id){

    $query = $this-db->select('*')
            ->from('users')
            ->where('user_id', $id)
            ->get();

        return $query->result();

}

this return a object with all data, then you call the method in the controller like this
$data['user_model'] = $this->model_name->getUser($id);
$this->load->view('Your_View',$data);

then in the view  $user_model is the object
in the view
print_r($user_model);

A: As long as the model is loaded, in your view you can access any public function or property like:
$this->user_model->getUser() or $this->user_model->team_id
View:
<?php

echo $this->user_model->getUser(1)->username;

This is against MVC in some respects but I can understand the logic behind doing so based on the following scenario where you want to say use num_rows and result without doing count:
class User_Model extends CI_Model {

    public function getUsers() {
        return $this->db->get('users');
    }
}

class Some_Controller extends CI_Controller {

    public function index() {
        $this->load->model('user_model');
        $data['users'] = $this->user_model->getUsers();
        $this->load->view('some_view', $data);
    }
}

View:
<?php

if ($users->num_rows() > 0) {
    foreach ($users->result() as $row) {
        echo $row->username;
    }
} else {
    echo 'No users';
}

A: Actually there is another possibility you can use
create a Team_model and an User_model
The Team_model could look like
class Team_model extends CI_Model
{

    $arrTeamNames = [];

    public function getTeamName($team_id)
    {
        if (!isset($this->arrTeamNames[$team_id]))
        {
            $query = $this->db
                ->select('name')
                ->from('team')
                ->where('team_id',$this->team_id)
                ->get();

            if ($query->num_rows() ==  1)
            {
                $objTeam = $query->row();
                $this->arrTeamNames[$team_id] = $objTeam->name;
                return $objTeam->name;
            }
            return '';
        }
        return $this->arrTeamNames[$team_id];
    }
}

and the User_model
class User_Model extends CI_Model
{
    public function getUser($id)
    {
        $query = $this->db->get_where('users', array('user_id' => $id));
        if ($query->num_rows() == 1)
        {
            $user = $query->row(0, 'User_Object');
            return $user;
        }
    }
}

class User_Object
{
    public function getTeamName()
    {
        $ci = get_instance();
        $ci->load->model('Team_model');
        return $ci->team_model->getTeamName($this->team_id);
    }
}

Note in the User_model you have an additional User_Object which
  gets mapped by the row() function which is well documented
  here.

Now if you call this model in one of your controller and pass it to your view you actually can access to a model function in a proper way e.g.
class User extends CI_Controller
{
    public function detail($user_id)
    {
        $this->load->model('User_model');
        $objUser = $this->User_model->getUser($user_id);
        $this->load->view('user-detail', ['objUser' => $objUser]);
    }
}

//user-detail view
echo $objUser->getTeamName();


text:
Q: Setting a time-out limit to readLine()? I have the following code that reads response from a POP server through Sockets in Java. But the problem is sometimes, when I use the readLine() function to read from the server and if the server does not reply with any response, my application will hang there, waiting for a response from the server.
socket.connect(new InetSocketAddress("pop.server.com", 110), 3000);
input = socket.getInputStream();
BufferedReader incoming = new BufferedReader(new InputStreamReader(input));
incoming.readLine();   //This line will cause my application to hang if the server does not respond with a reply

Is there a way to set a timeout or some other ways that when the server does not reply after a certain amount of time, the application should stop waiting for a response and continue its other execution?

A: I suggest you try Socket.setSoTime(timeout)


text:
Q: Linux list loop issue I am using the find command to create a list of files. my issue is utilizing the output of it because of the syntax of the lies and folders. An example returned by the find command is in the variable $LIST
if i run
IFS=\n
echo "$LIST"

I will get
/C D/e f
/C D/t est

So if I use this in a for loop such as...
for file in $LIST
do
echo $file
echo "File printed"

done

I am getting
/C D/e f
/C D/t est
File Printed

at the output as a single block by setting the IFS to \n
What I want and was expecting is
/C D/e f
File Printed
/C D/t est
File Printed

A: By far the best way to act on the files you've found with the find command is not to use a for loop at all but to do it with the -exec switch:
find . -iname '*.java' -exec cp '{}' /tmp/backup/ ';'

This will look for all files matching *.java from the current directory and downwards, and then run
cp filename /tmp/backup/

on each one. You should look at the man page for find, but one thing to note in particular is that if you end with ';' then the files will get processed one at a time, whereas if you end with '+' then lots will be processed together.
The other option is xargs, for which you really need to use -print0 as a switch to find and then -0 as a switch to xargs to avoid problems with spaces etc. in filenames:
find . -iname '*.java' -print0 | xargs -0 grep 'static'

will look for static in all .java files.

A: To interpret the \n escape sequence as a newline, you need to use `$'...' syntax:
IFS=$'\n'

Or you can put a literal newline:
IFS='
'


text:
Q: angularJS about how to use service in every .js file I define some service in app1.js
like this
app1.js
  angular.module('todoApp.services', []).factory('TodoService', function($http, $location) {
  ┊ return {
  ┊ ┊ send: function(url, par) {
  ┊ ┊ ┊ return $http.get(url, {
  ┊ ┊ ┊ ┊ params: par
  ┊ ┊ ┊ });
  ┊ ┊ },
  ┊ ┊ get_default_data: function($scope, url, par) {
  ┊ ┊ ┊ this.send(url, par).success(function(data) {
  ┊ ┊ ┊ ┊ $scope.data = data;
  ┊ ┊ ┊ });
  ┊ ┊ },
  ┊ ┊ change_status: function($scope, url, par) {
  ┊ ┊ ┊ this.send(url, par).success(function() {
  ┊ ┊ ┊ ┊ angular.forEach($scope.data, function(item) {
  ┊ ┊ ┊ ┊ ┊ if (item.id === par.sid) {
  ┊ ┊ ┊ ┊ ┊ ┊ item.status = par.status;
  ┊ ┊ ┊ ┊ ┊ }
  ┊ ┊ ┊ ┊ });
  ┊ ┊ ┊ });
  ┊ ┊ },
    })

and how can I use this todoApp.services in another .js file?
I use like this
app2.js
angular.module('myapp', ['todoApp.services'])

It doesn't work, how can I use it?

A: As per your current implementation you have declared todoApp.services module with a factory in it and you have defined the dependency of todoApp.services for myapp which prefect.
However you should return  promise from service rather than manipulating $scope
angular.module('todoApp.services', []).factory('TodoService', function($http, $location) {
    return {
        get_default_data: function() {
            return $http.get(url, par)
        }
    }
})

To use you have to injcet the service to your contoller
myApp.controller('MainCtrl', ['TodoService', '$scope', function(TodoService, $scope){

    //Call the service method
    TodoService.get_default_data().then(function(){
        $scope.data = data;
    });
}]);

A: I would just link the service off of your app module and then inject the service into controllers with DI.
app.js
(function() {

    angular.module('app', []);

})();

app.services.js
(function() {

    function appService() {
        // service code
    }

    angular.module('app')
        .factory('appService', appService);

})();

app.controller.js
(function() {

    function appController(appService) {
        // controller code
    }

    angular.module('app')
        .controller('appController', appController);

})();

this will give you your factory data inside your controller.

A:     var myApp = angular.module('myApp', []);
    myApp.factory('myService', function() {
        return {
            myFunction: function() {
                alert("I'm foo!");
            }
        };
    });

Define service at rootscope.
    myApp.run(function($rootScope, myService) {
        $rootScope.appData = myService;
    });

access service at any controller :
    myApp.controller('MainCtrl', ['$scope', function($scope){
        $scope.appData.myFunction();
    }]);


text:
Q: OpenGL - Convert from DisplayList to use VBO I have the following global variables:
vector<vector<unsigned int> > faces;
vector<float> vertexCoords;
unsigned int modelList;

In my initialization there is this code:
glEnableClientState(GL_VERTEX_ARRAY);   // vertex array
glVertexPointer(3, GL_FLOAT, 0, &vertexCoords[0]);

modelList = glGenLists(1);  // generate display list
glNewList(modelList, GL_COMPILE);
for (unsigned int i = 0; i < faces.size(); i++) {
    glBegin(GL_TRIANGLE_STRIP);
    for (vector<unsigned int>::iterator it = faces[i].begin();
            it != faces[i].end(); it++)
        glArrayElement(*it - 1);
    glEnd();
}
glEndList(); // End display list.

which in my glutDisplayFunc, I call:
glCallList(modelList); // Execute display list.

Instead of a DisplayList, I would like to now use a VBO. How can I go about converting this code? Thanks in advance.

A: You're in luck. The structure of your program already has everything in place. We can even get around that annoying 1-based indexing.
First create a VBO:
GLuint vbo_id;
GLuint eabo_id; /* EIB = Element Array Buffer */
size_t eabo_n_elements;

void make_vbo()
{
    GLuint genbuf_ids;
    glGenBuffers(2, genbuf_ids);

    vbo_id  = genbuf_ids[0];
    eabo_id = genbuf_ids[1];

    glBindBuffer(GL_ARRAY_BUFFER, vbo_id);

Allocate space for the data, any copy the vertex data into the buffer. Since your vertex element index array is shifted by one, we allocate for one vertex more and copy the data into it with an offset (we could as well use the GL_ARB_draw_elements_base_vertex extensions, but I'd like to show it this way:
    glBufferData(
        GL_ARRAY_BUFFER,
        (vertexCoords.size() + 3)*sizeof(vertexCoords[0]),
        NULL,
        GL_STATIC_DRAW );

    glBufferSubData(
        GL_ARRAY_BUFFER,
        sizeof(vertexCoords[0])*3, /* offset by 1 vertex */
        (vertexCoords.size())*sizeof(vertexCoords[0],
        &vertexCoords[0]);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

The same for the element array buffer; you "stacked" two vectors into each other… which is not very efficient by the way. Let's unroll this. First again allocate the memory for tha buffer, but don't copy the data into it. Since each subvector may have a different length (although if used for a specific primitive draw mode they should be all the same size) first determine the total number of elements (using the C++11 feature auto to save some typing and so that we can use iterators); also later on we need to know that number to draw them:
    eabo_n_elements = 0;
    for(auto i = faces.begin(); i != faces.end(); i++) {
        eabo_n_elements += i.size();
    }

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eabo_id);
    glBufferData(
        GL_ELEMENT_ARRAY_BUFFER,
        sizeof(faces[0][0]) * eabo_n_elements,
        NULL,
        GL_STATIC_DRAW );

Unroll-copy the face data into the EAB
    size_t offset = 0;
    for(auto i = faces.begin(); i != faces.end(); i++) {
        size_t const len = i.size() * sizeof(i[0]);
        glBufferSubData(
            GL_ELEMENT_ARRAY_BUFFER,
            offset,
            len,
            &i[0] );
        offset += len;
    }

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

Now we can draw that. Technically we could use a VAO (and with OpenGL-4 we have to have one), but let's safe that. Drawing VBOs is very similar to drawing from client side vertex arrays. Now you used glVertexPointer which indicates you're using the fixed function pipeline. We can use that. But then VBOs became OpenGL core functionality only with OpenGL-3 (before that it was available for a long time as an extension). So it's glVertexAttribPointer plus a matching shader instead. To keep the transition as small as possible, let's recycle your use of glVertexPointer. The main difference is, that we bind the VBO before making the glVertexPointer call and pass a integer-cast-to-a-pointer (which actually may invoke UB for anything other than 0) offset into the data parameter:
void draw_vbo()
{
    glEnableClientState(GL_VERTEX_ARRAY);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
    glVertexPointer(3, GL_FLOAT, 0, (void*)0);

Once the VBO has been "linked" into a vertex array access, we can unbind it. The data will still be fetched from the VBO.
    glBindBuffer(GL_ARRAY_BUFFER, 0);

And finally make the draw call. Remember that we applied the 1-element offset when copying the vertex data to the VBO. So we just pass through the face vertex element indices. Same pattern as for the VBO: Bind, cast integer offset to pointer and pass that to glDrawElements
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eabo_id);
    glDrawElements(GL_TRIANGLE_STRIP, eabo_n_elements, GL_UNSIGNED_INT, (void*)0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}


text:
Q: Number Format Exception occuring, try catch throwing exception? I am having an issue with this part of the method. The program is supposed to pass arguments, which in my binaryToDecimal method it does just fine. But everytime this method, the decimalToBinary attempts to pass the value of 5 to binary, it tells me the Number Format Exception occurs and it doesn't do the calculation. Anything I could try to avoid this from happening?
public static String decimalToBinary(String decimalString) {
    int decimal = 0;

    try {
        decimal = Integer.parseInt("decimalString");
    }catch(NumberFormatException e){
            System.out.println("Number format exception occured");
        }

    String answer = "";

    while(decimal > 0) {
        answer = decimal%2+answer;

    }
    return answer;
}

A: Your issue is in here decimal = Integer.parseInt("decimalString");
you should used your parameter decimalString
instead of this decimal = Integer.parseInt("decimalString");
try using this decimal = Integer.parseInt(decimalString);


text:
Q: How to specify application pool identity user and password from PowerShell I have been having lots of difficulty automating the setup of a Web application and configuring IIS appropriately with the Application Pool Identity.  I am doing this in a Web application deployment script written in PowerShell. My requirement is that I need my PowerShell script to set the application pool identity user to a specific service account mydomain\svcuser and password.  Here is the sample code:
$pool = New-Item "IIS:\AppPools\MyAppPool" -Force
$svcuser = "mydomain\svcuser"
$pool.processModel.userName = $svcuser
$password = "somepassword"
$pool.processModel.password = $password
$pool.processModel.identityType = 3
$pool | Set-Item -ErrorAction Stop

When I run this, everything appears to work correctly--no errors are thrown and the application identity user name appears in IIS--but for some reason the password does not get set correctly, if at all.  Since it is a password I cannot verify whether it has been set, but I can conclude that it if it is, it is not set correctly.  It will not authenticate the resulting application pool user until I manually go in and enter the password in IIS.  As a result the application fails after being deployed to the Web server and requires manual intervention.
Am I missing something here?

A: You would do this as follows:
Import-Module WebAdministration
Set-ItemProperty IIS:\AppPools\app-pool-name -name processModel -value @{userName="user_name";password="password";identitytype=3}

See this document here for an explanation, and a reference of the indentity type numeric for the user type you will run the app pool under: http://www.iis.net/configreference/system.applicationhost/applicationpools/add/processmodel

A: seems you can do this a little more directly now
appcmd set apppool junkapp /processmodel.password:junkpassword

A: After few experiments
Here is my Answer, I hope this will helps , I've worked on IIS 8.5
$credentials = (Get-Credential -Message "Please enter the Login credentials including Domain Name").GetNetworkCredential()

$userName = $credentials.Domain + '\' + $credentials.UserName

Set-ItemProperty IIS:\AppPools\$app_pool_name -name processModel.identityType -Value SpecificUser

Set-ItemProperty IIS:\AppPools\$app_pool_name -name processModel.userName -Value $username

Set-ItemProperty IIS:\AppPools\$app_pool_name -name processModel.password -Value $credentials.Password

A: I'm on powershell v4 which doesn't have 'ConvertFrom-SecureString', in the end I got the following to work for me:
Import-Module WebAdministration

$cred = Get-Credential -Message "Please enter username and new password to reset IIS app pool password (for app pools running as username)"

$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($cred.Password)
$plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)

$applicationPools = Get-ChildItem IIS:\AppPools | where { $_.processModel.userName -eq
$cred.UserName }

foreach($pool in $applicationPools)
{
    $apppool = "IIS:\AppPools\" + $pool.Name

    Set-ItemProperty $apppool -name processModel.password -Value $plaintext
}

Write-Host "Application pool passwords updated..." -ForegroundColor Magenta
Write-Host ""
Read-Host -Prompt "Press Enter to exit"


text:
Q: Checking if a geohash intersects another geohash I have a problem where I need to check if a geohash falls into a list of other points with dynamic radiuses/boxes. What I am currently doing is getting ortb bid request messages that contain lat/lon and using redis to check what campaigns would match against the ortb's device lat/lon. This works fine if I query with a fixed radius. The problem is that I want to store the campaigns with dynamic radii dependending on population density.
The Current implementation
In 3.2 versions of redis you have the ability to store geohashes in a zset using the built in commands. This converts the lat/lon into a 52 bit geohash.
Using the redis zset functionality I can query the list of campaigns also passing in a radius. This will return me (0,n) campaigns that fall into the current radius.
The Current implementation drawbacks
The problem I have is that the campaigns have dynamic radii. So for example 1 campaign may have a 3 miles radius where another may have a 20 mile radius. Since I am required to pass in a single radius I simply pass 5 miles but this will exclude requests from the 20 mile radius.
Potential Improved Implementation
I was thinking about this problem but am not sure how to put it together. I think what would be a better solution would be to have a list of geohashes in a sorted set with different precision essentially creating a geo hash box for each entry. The problem now is that I am not 100% sure about how to go about putting this together or if it would work as I want it to. I am really looking for guidance if this would work and if anyone has put something together like this. I think I can accomplish this using a simple sorted set and then masking the bits down the precision of the entry in the sorted set. However I can see this being an issue when dealing with a large list of campaigns. Not exactly sure if it will work with multiple integers of different precision or how the O notation would work out on this one. I need it to be as fast as possible due to the fact that I am dealing with around 4+billion requests a day.
Notes
I hope I have done a decent job of the problem since it is a fairly complex problem to describe. I have also looked at quite a few libraries but I don't think they will solve the problem for me. I have started writing my own implementation but the complexity quickly makes my head hurt.
The original library that I investigated. Allows for single box query.
https://github.com/kungfoo/geohash-java
This one looks more promising but I wasn't sure if it will actually give the ability to search multiple boxes.
https://github.com/davidmoten/geo
Here is an outstanding overview of geohasing. Not sure why it is located at an IP but I am glad I found it.
http://23.239.12.206:8000/posts/2014-04-05-geohash-proximity-pt2.html

A: You could try a weighted voronoi diagram and a point in polygon test. A simple and fast solution could be a bitmap with each cell of the weighted voronoi diagram has a color. Then simply check the color of the point.


text:
Q: How I can rotate a polar chart? I want a polar chart (with highcharts library), but I need the chart is rotated 45º. I have the following base script:
$(function () {

var interval = 90;
var startAngle = 0;

window.chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        polar: true,
        margin: 60
    },
    title: {
        text: 'Style of thought',
    },
    pane: {
        startAngle: startAngle
    },
    xAxis: {
        tickmarkPlacement: 'on',
        startOnTick: true,
        tickInterval: interval,
        min: 0,
        max: 360
    },
    yAxis: {
        min: 0,
        max: 100
    },
    plotOptions: {
        series: {
            pointStart: 0,
            pointInterval: interval
        },
        column: {
            pointPadding: 0,
            groupPadding: 0
        }
    },
    series: [
        {
            type: 'area',
            name: 'Luis',
            data: [40, 60, 35, 89]
        }, {
            type: 'line',
            name: 'Media de comunidad',
            data: [60, 75, 15, 52]
        }]
    });
});

Example in jsfiddle and the chart nice.
I need to rotate the chart 45º, for this I change the value of  startAngle to 45
$(function () {

var interval = 90;
var startAngle = 45;

window.chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        polar: true,
        margin: 60
    },
    title: {
        text: 'Style of thought',
    },
    pane: {
        startAngle: startAngle
    },
    xAxis: {
        tickmarkPlacement: 'on',
        startOnTick: true,
        tickInterval: interval,
        min: 0,
        max: 360
    },
    yAxis: {
        min: 0,
        max: 100
    },
    plotOptions: {
        series: {
            pointStart: 0,
            pointInterval: interval
        },
        column: {
            pointPadding: 0,
            groupPadding: 0
        }
    },
    series: [
        {
            type: 'area',
            name: 'Luis',
            data: [40, 60, 35, 89]
        }, {
            type: 'line',
            name: 'Media de comunidad',
            data: [60, 75, 15, 52]
        }]
});
});

Example 2 in jsfiddle and now the chart is bad. If you see it, the center of the circle is not equidistant from the circumference.
Any idea of the problem?
Thank you very much!!

A: It looks like a bug, so I've reported to our devs here: https://github.com/highslide-software/highcharts.com/issues/1561
Thanks for suggestion


text:
Q: Error installing Ruby on Ubuntu 14.04 The following install commands:
gpg --keyserver hkp://keys.gnupg.net --recv-keys         409B6B1796C275462A1703113804BB82D39DC0E3

 \curl -sSL https://get.rvm.io | bash -s stable --rails

Returns this error:
 Installing requirements for ubuntu.
 Updating system................
 Error running 'requirements_debian_update_system ruby-2.2.1',
showing last 15 lines of /home/gav/.rvm/log/1458060663_ruby-                                      2.2.1/update_system.log     ++ /scripts/functions/logging : rvm_pretty_print()  78 > case  "${TERM:-   dumb}" in   ++ /scripts/functions/logging : rvm_pretty_print()  81 > case "$1" in
++ /scripts/functions/logging : rvm_pretty_print()  83 > [[ -t 2 ]]
++ /scripts/functions/logging : rvm_pretty_print()  83 > return 1
++ /scripts/functions/logging : rvm_error()  117 > printf %b 'There has       been error while updating '\''apt-get'\'', please give it some time and   try again later.
404 errors should be fixed for rvm to proceed. Check your sources   configured in:
 /etc/apt/sources.list
 /etc/apt/sources.list.d/*.list
\n'
There has been error while updating 'apt-get', please give it some  time     and try again later.
404 errors should be fixed for rvm to proceed. Check your sources    configured in:
/etc/apt/sources.list
/etc/apt/sources.list.d/*.list

++ /scripts/functions/requirements/ubuntu :    requirements_debian_update_system()  53 > return 100
Requirements installation failed with status: 100.

A: You have problems with your sources
heres one solution, open a terminal type in
sudo apt-get update

take note of the names that are causing the 404s, errors, etc.
then open your software center and choose sources

there pick "Other Software" (second tab)

expand that window and start disabling the repositories that cause you trouble

as you uncheck any repositories, try again
sudo apt-get update

until you see no errors

make sure you don't see any errors or not found sources
afterward type in
source ~/.rvm/scripts/rvm

and
rvm requirements

and That's it...


text:
Q: XF86-video-intel vs Modesetting for a 2nd Monitor [Manjaro] I am trying to get an external monitor (Dell) working on my laptop (dell) via a ubc-c docking station (dell). and I am having some issue - Running on an up to date Manjaro (5.4.28-1)
Basically while in KDE, the 2nd monitor is detected correctly and signal is going, but I have no image. I can't figure out what is going on. If move to a tty (ctrl+alt+F2) the second screen comes to life.
If I boot on my win session (same laptop) all is working good.
I have tryied the xf86-video-intel driver, but it is just broken. KDE is unsuable so I had to revert back to modeseting.
Any suggestion most welcome.
Many thanks!!

A: so in desperation I wiped the system and went for a kubuntu 20.04 - I have a dell dev edition so I thought that might help. It did initialy, but after few update it stopped working again.
So that made me start looking in KDE. and I finally found it.
Appenrently, something, I don't know if it is the laptop, the screen or the docking station doesn't like OpenGL.
By changing the rendering to something else that openGL it worked just fine. So I am assuming it would be the same fix in Manjaro.
For the time Beeing I am happy in Kubuntu - Much better battery life ;)
I hope that can be uselfull to somebody.


text:
Q: onChange on a dynamic element to collect objects in an array I have inputs which values I collect and send to firebase(as strings, objects and arrays).
all inputs work fine. the only one I'm struggling with is a dynamic one, which is rendered through a map() method on an array of inputs. I use the onChange method on the input and am able to get to unsatisfactory results: either getting only the last value from the the array of inputs, or getting every charecter entery as an event thus creating an array like this: ['b', 'be', 't', 'th', 'the', 'g', 'gy', 'g', 'gu', 'guy'].
what is the correct method? tried using both array.push() and useState([]).
so I'm trying to collect the values of dynamically rendered inputs. here are the relevant code pieces:
const [newTodo, setNewTodo] = useState([]);

const [todoInput, setTodoInput] = useState([{ todo: "" }]);

this returns the values (be, the, guy) as a newTodo = ['b', 'be', 't', 'th', 'the', 'g', 'gy', 'g', 'gu', 'guy']
 {todoInput.map((singleTodo, index) => (

          <input
            type="text"
            className="todo-input"
            onChange={(event) => {
              newTodo.push(event.target.value);
            }}

this return newTodo as ['guy']:
{todoInput.map((singleTodo, index) => (

          <input
            type="text"
            className="todo-input"
            onChange={(event) => {
              setNewTodo([event.target.value]);
            }}

this also returns newTodo = ['b', 'be', 't', 'th', 'the', 'g', 'gy', 'g', 'gu', 'guy']:
{todoInput.map((singleTodo, index) => (

          <input
            type="text"
            className="todo-input"
            onChange={(event) => {
              setNewTodo([...newTodo, event.target.value]);
            }}

the entire component for context:
const AddTask = () => {
  const db = getFirestore();
  const colTaskRef = collection(db, "Task");
  const [newTitle, setNewTitle] = useState("");
  const [newInCharge, setNewInCharge] = useState("");
  const [newCollabs, setNewCollabs] = useState([]);
  const [newPriority, setNewPriority] = useState("");
  const [newTodo, setNewTodo] = useState([]);

  const [todoInput, setTodoInput] = useState([{ todo: "" }]);
  const handleTodoAdd = () => {
    setTodoInput([...todoInput, { todo: "" }]);
  };
  const handleTodoRemove = (index) => {
    const list = [...todoInput];
    list.splice(index, 1);
    setTodoInput(list);
  };

  const handleSelect = (e) => {
    setNewInCharge(e.target.value);
  };
  const handleCheck = (e) => {
    setNewCollabs([...newCollabs, e.target.value]);
  };

  const handleClick = () => {
    console.log(newTodo);
    createTask();
  };

  const createTask = async () => {
    await addDoc(colTaskRef, {
      Title: newTitle,
      InCharge: newInCharge,
      Priority: newPriority,
      Todos: newTodo,
      Collaborators: newCollabs,
      InProgress: false,
      Completed: false,
    });
  };
  return (

      <input
        className="title-input"
        type="text"
        placeholder="Task Title"
        onChange={(event) => {
          setNewTitle(event.target.value);
        }}
      />
       Who's in charge of this task?
      {<GetCollaborators handleSelect={handleSelect} />}

        Who do you want to collaborate with?

      {<GetCollaboratorsCheckBox handleCheck={handleCheck} />}

        Priority?

      <select
        name="priority"
        className="priority-selector"
        onChange={(event) => {
          setNewPriority(event.target.value);
        }}
      >
        <option value="top"> Top </option>
        <option value="first">First</option>
        <option value="second">Second</option>
        <option value="last">Bottom</option>
      </select>

To Do list:

      {todoInput.map((singleTodo, index) => (

          <input
            type="text"
            className="todo-input"
            onChange={(event) => {
              setNewTodo([...newTodo, event.target.value]);
            }}
          />
          {todoInput.length - 1 === index && todoInput.length < 5 && (
            <button className="plus-btn" onClick={handleTodoAdd}>
              +
            </button>
          )}
          {todoInput.length > 1 && (
            <button
              className="minus-btn"
              onClick={() => handleTodoRemove(index)}
            >
              -
            </button>
          )}

      ))}

      <button className="btn btn__task-submit" onClick={handleClick}>
        Submit Task
      </button>

  );
};

A: if you don't want the eventlistener to trigger on change, don't use the onChange event.
If you tell your function to execute every time the input changes, it will do exactly that. You should probably use some other form of event in order to trigger your listener - maybe a button to press once the input is done. Or on a certain buttonpress (spacebar / enter) or onBlur. I don't know at which point you want the input to actually be added to the array. Depending on that, choose an event, that actually fits your purpouse (onClick for a buttonpress for example)
Reacts onChange uses the html/JS event oninput and not onchange