text:
Q: Performance problem with python elementTree XML parser I have a memory problem with parsing the large XML file.
The file looks like (just first few rows):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE raml SYSTEM 'raml20.dtd'>
<raml version="2.0" xmlns="raml20.xsd">
  <cmData type="actual">

      <log dateTime="2019-02-05T19:00:18" action="created" appInfo="ActualExporter">InternalValues are used</log>

    <managedObject class="MRBTS" version="MRBTS17A_1701_003" distName="PL/M-1" id="366">

PL/TE-2/p>

Name of street

      <list name="PiOptions">

0

5

2

6

7

3

9

10

      </list>

4251

1

    </managedObject>
    <managedObject class="MRBTS" version="MRBTS17A_1701_003" distName="PL/M10" id="958078">

PLMN-PLMN/MRSITE-138

Street 2

748

3

    </managedObject>
    <managedObject class="MRBTS" version="MRBTS17A_1701_003" distName="PL/M21" id="1482118">

Stree 3

529

4

    </managedObject>
  </cmData>
</raml>

And I am using xml eTree Element parser, but with a file over 4GB and 32 GB of RAM on machine, I'm running out of memory.
Code I'm using:
def parse_xml(data, string_in, string_out):
    """
    :param data: xml raw file that need to be processed and prased
    :param string_in: string that should exist in distinguish name
    :param string_out: string that should not exist in distinguish name
    string_in and string_out represent the way to filter level of parsing (site or cell)
    :return: dictionary with all unnecessary objects for selected technology
    """
    version_dict = {}
    for child in data:
        for grandchild in child:
            if isinstance(grandchild.get('distName'), str) and string_in in grandchild.get('distName') and string_out not in grandchild.get('distName'):
                inner_dict = {}
                inner_dict.update({'class': grandchild.get('class')})
                inner_dict.update({'version': grandchild.get('version')})
                for grandgrandchild in grandchild:
                    if grandgrandchild.tag == '{raml20.xsd}p':
                        inner_dict.update({grandgrandchild.get('name'): grandgrandchild.text})
                    elif grandgrandchild.tag == '{raml20.xsd}list':
                        p_lista = []
                        for gggchild in grandgrandchild:
                            if gggchild.tag == '{raml20.xsd}p':
                                p_lista.append(gggchild.text)
                            inner_dict.update({grandgrandchild.get('name'): p_lista})
                            if gggchild.tag == '{raml20.xsd}item':
                                for gdchild in gggchild:
                                    inner_dict.update({gdchild.get('name'): gdchild.text})
                    version_dict.update({grandchild.get('distName'): inner_dict})
    return version_dict

I have tried with iterparse, with root.clear(), but nothing really helps.
I heard that DOM parsers are slower ones, but SAX gives me an error:
ValueError: unknown url type: '/development/data/raml20.dtd'

Not sure why. If anyone has any suggestion on how to improve way and performance, I will be really thankful.
I there is a need for bigger XML samples, I am willing to provide it.
Thanks in advance.
EDIT:
Code I tried after the first answer:
import xml.etree.ElementTree as ET
def parse_item(d):
#     print(d)
#     print('---')

    a = '<root>'+ d + '</root>'
    tree = ET.fromstring(a)
    outer_dict_yield = {}
    for elem in tree:
        inner_dict_yield = {}
        for el in elem:
            if isinstance(el.get('name'), str):
                inner_dict_yield.update({el.get('name'): el.text})
            inner_dict.update({'version': elem.get('version')})
#                 print (inner_dict_yield)
    outer_dict_yield.update({elem.get('distName'): inner_dict_yield})
#     print(outer_dict_yield)
    return outer_dict_yield

def read_a_line(file_object):
    while True:
        data = file_object.readline()
        if not data:
            break
        yield data

min_data = ""
inside = False

f = open('/development/file.xml')
outer_main = {}
counter = 1
for line in read_a_line(f):
    if line.find('<managedObject') != -1:
        inside = True
    if inside:
        min_data += line
    if line.find('</managedObject') != -1:
        inside = False
        a = parse_item(min_data)
        counter = counter + 1
        outer_main.update({counter: a})
        min_data = ''

A: If you only need to extract the data from the XML file and don't need to perform any XML-specific operations like XSL transformations etc, the approach with a very low memory footprint is to define your own TreeBuilder. Example:
import pathlib
from pprint import pprint
from xml.etree import ElementTree as ET

class ManagedObjectsCollector:
    def __init__(self):
        self.item_count = 0
        self.items = []
        self.curr_item = None
        self.attr_name = None
        self.list_name = None
        self.list_entry = False

    def start(self, tag, attr):
        if tag == '{raml20.xsd}managedObject':
            self.curr_item = dict()
            self.curr_item.update(**attr)
        elif tag == '{raml20.xsd}p':
            if self.list_name is None:
                self.attr_name = attr.get('name', None)
            self.list_entry = self.list_name is not None
        elif tag == '{raml20.xsd}list':
            self.list_name = attr.get('name', None)
            if self.list_name is not None:
                self.curr_item[self.list_name] = []

    def end(self, tag):
        if tag == '{raml20.xsd}managedObject':
            self.items.append(self.curr_item)
            self.curr_item = None
        elif tag == '{raml20.xsd}p':
            self.attr_name = None
            self.list_entry = False
        elif tag == '{raml20.xsd}list':
            self.list_name = None

    def data(self, data):
        if self.curr_item is None:
            return
        if self.attr_name is not None:
            self.curr_item[self.attr_name] = data
        elif self.list_entry:
            self.curr_item[self.list_name].append(data)

    def close(self):
        return self.items

if __name__ == '__main__':
    file = pathlib.Path('data.xml')
    with file.open(encoding='utf-8') as stream:
        collector = ManagedObjectsCollector()
        parser = ET.XMLParser(target=collector)
        ET.parse(stream, parser=parser)
    items = collector.items
    print('total:', len(items))
    pprint(items)

Running the above code with your example data will output:
total: 3
[{'PiOptions': ['0', '5', '2', '6', '7', '3', '9', '10'],
  'btsName': '4251',
  'class': 'MRBTS',
  'distName': 'PL/M-1',
  'id': '366',
  'linkedMrsiteDN': 'PL/TE-2',
  'name': 'Name of street',
  'spareInUse': '1',
  'version': 'MRBTS17A_1701_003'},
 {'btsName': '748',
  'class': 'MRBTS',
  'distName': 'PL/M10',
  'id': '958078',
  'linkedMrsiteDN': 'PLMN-PLMN/MRSITE-138',
  'name': 'Street 2',
  'spareInUse': '3',
  'version': 'MRBTS17A_1701_003'},
 {'btsName': '529',
  'class': 'MRBTS',
  'distName': 'PL/M21',
  'id': '1482118',
  'name': 'Stree 3',
  'spareInUse': '4',
  'version': 'MRBTS17A_1701_003'}]

Because we don't construct the XML tree in the ManagedObjectsCollector and don't keep more than the current file line in memory at a time, the memory allocation of the parser is minimal and the memory usage is largely affected by the collector.items list. The example above parses all the data from each managedObject item, so the list can grow pretty large. You can verify it by commenting out the self.items.append(self.curr_item) line - once the list doesn't grow, the memory usage remains constant (somewhat about 20-30 MiB, depending on your Python version).
If you need only parts of the data, you will benefit from a simpler implementation of TreeBuilder. For example, here's a TreeBuilder that only collects the version attributes, ignoring the rest of tags:
class VersionCollector:
    def __init__(self):
        self.items = []

    def start(self, tag, attr):
        if tag == '{raml20.xsd}managedObject':
            self.items.append(attr['version'])

    def close(self):
        return self.items

Bonus
Here is a self-contained script that is extended with memory usage measurements. You'll need some extra packages to be installed:
$ pip install humanize psutil tqdm

Optional: use lxml for faster parsing:
$ pip install lxml

Run the script with filename as parameter. Example output of a 40 MiB XML file:
$ python parse.py data_39M.xml
mem usage:   1%|▏    | 174641152/16483663872 [00:01<03:05, 87764892.80it/s, mem=174.6 MB]
total items memory size: 145.9 MB
total items count: 150603
[{'PiOptions': ['0', '5', '2', '6', '7', '3', '9', '10'],
  'btsName': '4251',
  'class': 'MRBTS',
  'distName': 'PL/M-1',
  'id': '366',
  'linkedMrsiteDN': 'PL/TE-2',
  'name': 'Name of street',
  'spareInUse': '1',
  'version': 'MRBTS17A_1701_003'},
  ...

Notice that for a 40MB XML file, the peak memory usage is at ~174 MB, while the memory allocation for the items list is ~146 MB; the rest is Python overhead and remains constant regardless of file size. This should give you a rough estimation of how much memory you'll need to read larger files.
Source code:
from collections import deque
import itertools
import pathlib
from pprint import pprint
import os
import sys
import humanize
import psutil
import tqdm

try:
    from lxml import etree as ET
except ImportError:
    from xml.etree import ElementTree as ET

def total_size(o, handlers={}, verbose=False):
    """https://code.activestate.com/recipes/577504/"""
    dict_handler = lambda d: itertools.chain.from_iterable(d.items())
    all_handlers = {
        tuple: iter,
        list: iter,
        deque: iter,
        dict: dict_handler,
        set: iter,
        frozenset: iter,
    }
    all_handlers.update(handlers)
    seen = set()
    default_size = sys.getsizeof(0)

    def sizeof(o):
        if id(o) in seen:
            return 0
        seen.add(id(o))
        s = sys.getsizeof(o, default_size)

        if verbose:
            print(s, type(o), repr(o), file=sys.stderr)

        for typ, handler in all_handlers.items():
            if isinstance(o, typ):
                s += sum(map(sizeof, handler(o)))
                break
        return s

    return sizeof(o)

class ManagedObjectsCollector:
    def __init__(self, mem_pbar):
        self.item_count = 0
        self.items = []
        self.curr_item = None
        self.attr_name = None
        self.list_name = None
        self.list_entry = False
        self.mem_pbar = mem_pbar
        self.mem_pbar.set_description('mem usage')

    def update_mem_usage(self):
        proc_mem = psutil.Process(os.getpid()).memory_info().rss
        self.mem_pbar.n = 0
        self.mem_pbar.update(proc_mem)
        self.mem_pbar.set_postfix(mem=humanize.naturalsize(proc_mem))

    def start(self, tag, attr):
        if tag == '{raml20.xsd}managedObject':
            self.curr_item = dict()
            self.curr_item.update(**attr)
        elif tag == '{raml20.xsd}p':
            if self.list_name is None:
                self.attr_name = attr.get('name', None)
            self.list_entry = self.list_name is not None
        elif tag == '{raml20.xsd}list':
            self.list_name = attr.get('name', None)
            if self.list_name is not None:
                self.curr_item[self.list_name] = []

    def end(self, tag):
        if tag == '{raml20.xsd}managedObject':
            self.items.append(self.curr_item)
            self.curr_item = None
        elif tag == '{raml20.xsd}p':
            self.attr_name = None
            self.list_entry = False
        elif tag == '{raml20.xsd}list':
            self.list_name = None

        # Updating progress bar costs resources, don't do it
        # on each item parsed or it will slow down the parsing
        self.item_count += 1
        if self.item_count % 10000 == 0:
            self.update_mem_usage()

    def data(self, data):
        if self.curr_item is None:
            return
        if self.attr_name is not None:
            self.curr_item[self.attr_name] = data
        elif self.list_entry:
            self.curr_item[self.list_name].append(data)

    def close(self):
        return self.items

if __name__ == '__main__':
    file = pathlib.Path(sys.argv[1])
    total_mem = psutil.virtual_memory().total
    with file.open(encoding='utf-8') as stream, tqdm.tqdm(total=total_mem, position=0) as pbar_total_mem:
        collector = ManagedObjectsCollector(pbar_total_mem)
        parser = ET.XMLParser(target=collector)
        ET.parse(stream, parser=parser)
    items = collector.items
    print('total:', len(items))
    print('total items memory size:', humanize.naturalsize(total_size(items)))
    pprint(items)

A: Can I ask a hackish question? Is the file flat? It seems like there are a few parent tags and then all the other tags are managedObject items, maybe you could write a custom parser by which you parse each tag out, treat it like an XML document, then discard it.  Streaming through the file will allow you to alternately read, analyze and discard items, effectively conserving the memory that you are limited by.
Here's some sample code that will stream the file and allow you to process each chunk one by one.  Replace parse_item with something that is useful to you.
def parse_item(d):
    print('---')
    print(d)
    print('---')

def read_a_line(file_object):
    while True:
        data = file_object.readline()
        if not data:
            break
        yield data

min_data = ""
inside = False

f = open('bigfile.xml')
for line in read_a_line(f):
    if line.find('<managedObject') != -1:
        inside = True
    if inside:
        min_data += line
    if line.find('</managedObject') != -1:
        inside = False
        parse_item(min_data)
        min_data = ''

I should also mention I was lazy and used the generator listed here to read the file (but I modified it a bit): Lazy Method for Reading Big File in Python?


text:
Q: iOS Mail app archive button sometimes goes back to inbox view? Normally pressing "archive" brings me to the next email but occasionally it brings me back to the inbox. Is this just a bug?
I'm using my gmail account and I'm in the "all inboxes" view. My OS is up to date.

A: No longer having this issue...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error in InputSreamReader with Http Connection I am extening "AsyncTask" in class
and running below code in run method using timer class
its a continue task.
 HttpClient client = new DefaultHttpClient();
 HttpPost httpPost = new HttpPost(sche.URL);
 long startTime = System.currentTimeMillis();
 HttpResponse response = client.execute(httpPost);
 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
 String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
 File file = new File(extStorageDirectory+"/"+runInBackend.count+sche.file_name);
 **is=new InputStreamReader(response.getEntity().getContent());**
 long bytesRead = 0;
 long totalBytesRead
 //long startTime = System.currentTimeMillis();

 while ((bytesRead = is.read())!=0)
 {
     totalBytesRead += bytesRead;
 }

it is printing the below Output in logCat lines continuously but when i remove
InputStreamReader line that is bolded its work fine can anyone why this is behaving
like this
03-30 12:34:01.001: DEBUG/dalvikvm(862): GC freed 6389 objects / 256392 bytes in 151ms
03-30 12:34:01.561: DEBUG/dalvikvm(862): GC freed 18546 objects / 1005008 bytes in 172ms
03-30 12:34:02.001: DEBUG/dalvikvm(862): GC freed 16351 objects / 524352 bytes in 121ms
03-30 12:34:02.470: DEBUG/dalvikvm(862): GC freed 16347 objects / 524208 bytes in 164ms
03-30 12:34:02.910: DEBUG/dalvikvm(862): GC freed 16348 objects / 524264 bytes in 119ms
03-30 12:34:03.400: DEBUG/dalvikvm(862): GC freed 16351 objects / 524352 bytes in 162ms
03-30 12:34:03.841: DEBUG/dalvikvm(862): GC freed 16347 objects / 524192 bytes in 126ms
03-30 12:34:04.390: DEBUG/dalvikvm(862): GC freed 16348 objects / 524264 bytes in 224ms
03-30 12:34:04.840: DEBUG/dalvikvm(862): GC freed 16348 objects / 524256 bytes in 128ms
03-30 12:34:05.341: DEBUG/dalvikvm(862): GC freed 16351 objects / 524344 bytes in 171ms
03-30 12:34:05.791: DEBUG/dalvikvm(862): GC freed 16347 objects / 524224 bytes in 121ms
03-30 12:34:06.280: DEBUG/dalvikvm(862): GC freed 16351 objects / 524344 bytes in 164ms
03-30 12:34:06.721: DEBUG/dalvikvm(862): GC freed 16347 objects / 524200 bytes in 125ms
03-30 12:34:07.181: DEBUG/dalvikvm(862): GC freed 16350 objects / 524288 bytes in 156ms

A: Use org.apache.http.util.EntityUtils.toByteArray(final HttpEntity entity) to read byte array from the server response.
Another point - read it only once. In your code it looks like you are trying to do this twice.


text:
Q: Why does @Output create circular json error? Trying to catch an event emitted from my quantity-component
When I take away the @Output decorator everything works fine, but when I include it to catch the event I get this error:

EXCEPTION: Error in ./QuantityComponent class
  QuantityComponent - inline template:0:567 caused by: Converting
  circular structure to JSONErrorHandler.handleError @
...
ORIGINAL EXCEPTION: Converting
  circular structure to JSON

What am I doing wrong?
// item-component.ts
import {Component, Input, Output, EventEmitter} from '@angular/core';

@Component({
    selector: 'item-component',
    template: '<quantity-component [initialQuantity]="initialQuantity" (change)="myValueChange($event)" ></quantity-component>'
})
export class ItemComponent {
    myValueChange($event){
        console.log($event);
    }
}

// quantity-component.ts
import {Component, Input, Output, EventEmitter} from '@angular/core';

@Component({
    selector: 'quantity-component',
    templateUrl: 'quantity.component.html'
})
export class QuantityComponent {
    @Input() item: string;

    @Input('initialQuantity') counterValue = 0;
    @Output('change') counterChange: EventEmitter<any> = new EventEmitter();

    increase() {
        this.counterValue++;
        this.counterChange.emit({
            value: this.counterValue
        })
    }

    decrease() {
        this.counterValue--;
        this.counterChange.emit({
            value: this.counterValue
        })
    }
}


text:
Q: How to amplify a signal containing square pulses at milivolts to a couple volts I was on it for a time. I'm planning to generate a signal containing square pulses from a smart phone's audio output. As I can get any shape of audio signal from smartphone's audio output, I want to encode digital data into audio signal with square pulses.(Surely pulses represent 1.)
I wrote an application and generated desired signal, everything is OK so far. But I measured peak value of pulses, it's approximately 20 mV. The problem is: this needs to be amplified to a couple volts such as 3 V so that digital devices can read the data properly.
One solution was using transistors, but I couldn't find any kind of transistor having such low threshold voltage.
Transformers also won't work because data is rare and very little part of the whole signal.
I couldn't come up with another solution.
Please help me, what is the simplest way to get this?
EDIT:
OpAmp's will help, I guess. Thank you


text:
Q: MATLAB error: Implementing formula and receiving / can't be used because matrix dimensions do not agree error I have a simple MATLAB program I wrote but I am getting errors. I am trying to plot TS1, TS2 and TS3 as a function of t from 0 to 40. However, I am getting various errors.
One of the errors I am getting is "/ can't be used because matrix dimensions do not agree" . I am also attaching a picture of the actual formula I am supposed to implement. Any help would be greatly appreciated.
%Ground Surface Temperature Plot

clc;
clear;

var t
var e1
var e2
var e3
var Ts1
var Ts2
var Ts3

t = linspace(0,40,1000);
Ti = 285.93;
Twind1 = 244.2611111;
Twind2 = 238.7055556;
Twind3 = 233.15;
x = 0;
h = 16.3987;
a = 13.78579*10^(-6);
k = 0.52;
L = 60.96;

e1 = erfc(x/(2*sqrt(a*t*86400)));
e2 = exp(h*x/k + h^2*a*t*86400/k^2);
e3 = erfc(x/(2*sqrt(a*t*86400))+(h*sqrt(a*t*86400)/k));

Ts1 = (e1 - e2*e3)*(Twind1 - Ti) + Ti;
Ts2 = (e1 - e2*e3)*(Twind2 - Ti) + Ti;
Ts3 = (e1 - e2*e3)*(Twind3 - Ti) + Ti;

figure
Plot(t,Ts1,t,Ts2,t,Ts3);

The formula that is being coded is below.

A: The error occurs at this line.
e1 = erfc(x/(2*sqrt(a*t*86400)));

These are the sizes of the things you're trying to divide.
>> size(2*sqrt(a*t*86400))
ans =
           1        1000
>> size(x)
ans =
     1     1

I believe you are trying to do an element wise division so use ./ as follows.
e1 = erfc(x./(2*sqrt(a*t*86400)));

Note you need to do this whenever you are performing element wise division or multiplication between a number and matrices so edit e2 and e3 accordingly.


text:
Q: Need advice about Magento events I created a module with a function inside Observer.php of said module.
I want to run this script everytime there is a change inside the database regarding products but I can't find the right event to attach my observer, any tips?

A: Really depends what changes you are looking for, but this one will catch most fundamental product changes;
catalog_product_save_before

or
catalog_product_save_after

Depending on what it is you need to achieve.
These cheat sheets from Nick Jones are well worth a look https://www.nicksays.co.uk/magento-events-cheat-sheet-1-9/


text:
Q: How to configure the number of parallel job executions It looks like that the number of parallel job executions is limited. My observation is that the Spring XD runtime (singlenode mode) executes at most 10 jobs at the same time.
I've created 15 jobs (wait1, wait2, ...) that simply wait for a minute and executed them right after each other (job launch wait1, job launch wait2, ...).
I've got a lot of jobs that block because they are waiting for other servers to respond, so I'd like to increase the number of executing jobs. Couldn't find anything in the documentation and couldn't find anything in servers.yml

A: When running in singlenode mode with a local transport, batch jobs run on the Spring Integration TaskScheduler which defaults to 10 threads, per the documentation.
To override this config, we need to add a property to servers.yml; please open a JIRA issue.
To override this, a taskScheduler bean needs to be added to the global context.
In the meantime, if you use a different transport (redis or rabbit), you won't have this limitation.
EDIT:
To increase the thread count for the scheduler:

*

*create a subdirectory META-INF in xd/config

*create a file spring.integration.properties in that directory (xd/config/META-INF)

*add a property: spring.integraton.taskScheduler.poolSize=30

*restart xd-singlenode
(where 30 is a little larger than the number of concurrent batch jobs you want to run).


text:
Q: Two y axis in core plot graph with different axis scales I am programming a app where I have graph with two y axis and one x axis.left y axis has range from 0 to 20 so there are 20 majorTick axis.Right y axis has range from 0 to 10,so I want left y axis to be labelled for every alternate majorTickAxis.
here is my code snippet
//code
   CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
float xmax=10.0;
float xmin=0.0;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xmin)      length:CPTDecimalFromFloat(xmax-xmin)];
float ymax=20.0;
float ymin=0.0;
float ymax2=10.0;
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(ymin) length:CPTDecimalFromFloat(ymax-ymin)];

// Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.75];

CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];

CPTMutableLineStyle *redLineStyle = [CPTMutableLineStyle lineStyle];
redLineStyle.lineWidth = 2.0;
redLineStyle.lineColor = [[CPTColor redColor] colorWithAlphaComponent:0.5];

CPTMutableLineStyle *greenLineStyle = [CPTMutableLineStyle lineStyle];
greenLineStyle.lineWidth = 2.0;
greenLineStyle.lineColor = [[CPTColor greenColor] colorWithAlphaComponent:0.5];

// Axes
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
CPTXYAxis *x          = axisSet.xAxis;
x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
x.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:@"1"] decimalValue];
x.minorTicksPerInterval       = 4;
x.labelOffset = 3.0f;
x.title         = @"Time";
x.titleOffset   = 20.0;
x.titleLocation = CPTDecimalFromFloat((xmax+xmin)/2);
x.majorGridLineStyle= majorGridLineStyle;
x.minorGridLineStyle=minorGridLineStyle;

CPTXYAxis *y = axisSet.yAxis;
y.majorIntervalLength         = CPTDecimalFromString(@"1.0");
y.majorTickLength=2.0f;
y.minorTicksPerInterval       = 4;
y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0);
y.labelExclusionRanges = [NSArray arrayWithObjects:
                          [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0.0)
                                                       length:CPTDecimalFromInteger(0.0)],Nil];
y.majorGridLineStyle= majorGridLineStyle;
y.minorGridLineStyle=minorGridLineStyle;

CPTXYAxis *y2 = [[(CPTXYAxis *)[CPTXYAxis alloc] initWithFrame:CGRectZero] autorelease];
y2.plotSpace    =plotSpace;
y2.orthogonalCoordinateDecimal = CPTDecimalFromFloat(xmax);
y2.majorGridLineStyle=majorGridLineStyle;
y2.minorGridLineStyle=minorGridLineStyle;
y2.minorTicksPerInterval       = 4;
y2.majorIntervalLength        = CPTDecimalFromString(@"1.0");
y2.labelOffset        = 10.0;
y2.coordinate          =CPTCoordinateY;

y2.axisLineStyle       = x.axisLineStyle;
y2.labelTextStyle              = x.labelTextStyle;
y2.labelOffset                 = -30.0f;
y2.visibleRange                = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0) length:CPTDecimalFromInteger(ymax2)];

y2.title                       = @"Temperature";
y2.titleLocation               = CPTDecimalFromInteger(5.0);
y2.titleTextStyle              =x.titleTextStyle;
y2.titleOffset                 =-45.0f;
y2.labelExclusionRanges = [NSArray arrayWithObjects:
                          [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(0.0)
                                                       length:CPTDecimalFromInteger(0.0)],Nil];

self.graph.axisSet.axes = [NSArray arrayWithObjects:x, y, y2, nil];

// Create a plot that uses the data source method for red graph
CPTScatterPlot *redPlot = [[[CPTScatterPlot alloc] init] autorelease];
redPlot.identifier = @"red Plot";;

CPTMutableLineStyle *lineStyle = [[redPlot.dataLineStyle mutableCopy] autorelease];
lineStyle.miterLimit        = 1.0f;
redPlot.dataLineStyle = redLineStyle;
redPlot.dataSource = self;
redPlot.interpolation = CPTScatterPlotInterpolationStepped;

[self.graph addPlot:redPlot];

// Create a plot that uses the data source method for green graph
CPTScatterPlot *greenPlot = [[[CPTScatterPlot alloc] init] autorelease];
greenPlot.identifier = @"green Plot";;

CPTMutableLineStyle *greenlineStyle = [[greenPlot.dataLineStyle mutableCopy] autorelease];
greenlineStyle.miterLimit       = 1.0f;
greenPlot.dataLineStyle = greenLineStyle;
greenPlot.dataSource = self;
[self.graph addPlot:greenPlot];

 // Add some data
NSMutableArray *newData = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for ( i = 0; i < 45; i++ ) {
    id x = [NSNumber numberWithDouble:i * 0.2];
    id y = [NSNumber numberWithDouble:i * rand() / ((double)RAND_MAX*5.0) ];
    [newData addObject:[NSDictionary dictionaryWithObjectsAndKeys:
      x, @"x",y, @"y",nil]];
}
NSMutableArray *newData1 = [NSMutableArray arrayWithCapacity:100];
for ( i = 0; i < 45; i++ ) {
    id x =[NSNumber numberWithDouble:i * rand() / ((double)RAND_MAX*5.0) ];
    id y2 = [NSNumber numberWithDouble:i * 0.2];
    [newData1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                        x, @"x",y2, @"y2",nil]];
}
self.plotData = newData;
self.plotData2=newData1;

A: If you want the two y-axes to have different scales, you need to add another plot space. Use the same xRange for the second plot space, but use a different yRange, e.g.,
CPTXYPlotSpace *plotSpace2 = [[[CPTXYPlotSpace alloc] init] autorelease];
plotSpace2.xRange = plotSpace.xRange;
plotSpace2.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(ymin)
                                                 length:CPTDecimalFromFloat(ymax2 - ymin)];
[graph addPlotSpace:plotSpace2];
y2.plotSpace = plotSpace2;

Use the majorIntervalLength to control the location of the ticks and grid lines:
y.majorIntervalLength = CPTDecimalFromFloat((ymax - ymin) / 10.0f);
y2.majorIntervalLength = CPTDecimalFromFloat((ymax2 - ymin) / 10.0f);


text:
Q: Warning: include(Mage/Core/Model/Domainpolicy.php) I'm getting blank product pages on my Magento website. When i check the system.log it gives the following error:
Warning: include(`Mage/Core/Model/Domainpolicy.php`) [function.include]: failed to open stream: No such file or directory

What to do?!

A: That is because the file is missing. You need to download the version of Magento from https://magento.com/download and then add the file /app/code/core/Mage/Core/Model/Domainpolicy.php to your Magento site.


text:
Q: Show precise result of math expression I want to do a mathematical operation in Tcl with precise result and e.g. two digits after dot. Example: 1/100 = 0.01. I tried with puts "[format "%.2f" [expr 1/100]]", but that did not work out.
Can someone solve my puzzle?
Thanks!

A: Tcl's division expr operator only does floating point division if at least one of the arguments is a floating point number. If both are integers, you get integer division.
% expr {1/100}
0
% expr {1.0/100}
0.01
% expr {1/double(100)}
0.01

As you can see above, the double cast-function may help here.

A: You could pass a float value instead of integers to the expression:
puts "[format "%.2f" [expr 1/100.0]]"

Or...
puts "[format "%.2f" [expr 1.0/100]]"

Also, it is advised to brace your expressions, for example:
puts "[format "%.2f" [expr {1/100.0}]]"


text:
Q: When you open the Popover [bootstrap] the screen loses focus and goes to top I have a query where fill an html table with the records from the database. In one of the columns of each row, there are some options how to edit, delete, add photos and another option that opens the Popover.
This Popover is Bootstrap 3 and is happening every time I click these buttons popover the screen loses focus on where it is and goes to the top of the page, I do not want that to happen, how to proceed?
Follows the code:

  <form class="marcarComoVendido">

        Anúncio: <%=rsAnuncios("id")%>

        <input <%=checkVendido%> type="checkbox" id="marcarComoVendido<%=rsAnuncios("id")%>" onclick="alugadoVendido('src/rotinas/rotinas.asp?acao=Vendido&id=<%=rsAnuncios("id")%>&tipo=vendido&idInput=marcarComoVendido<%=rsAnuncios("id")%>&outroInput=marcarComoAlugado<%=rsAnuncios("id")%>', 'marcarComoVendido<%=rsAnuncios("id")%>', 'marcarComoAlugado<%=rsAnuncios("id")%>');" /> Marcar anúncio como VENDIDO

        <input data-rel="tooltip" title="Republicar Anúncio" <%=checkAlugado%> type="checkbox" id="marcarComoAlugado<%=rsAnuncios("id")%>" onclick="alugadoVendido('src/rotinas/rotinas.asp?acao=Vendido&id=<%=rsAnuncios("id")%>&tipo=alugado&idInput=marcarComoAlugado<%=rsAnuncios("id")%>&outroInput=marcarComoVendido<%=rsAnuncios("id")%>', 'marcarComoAlugado<%=rsAnuncios("id")%>', 'marcarComoVendido<%=rsAnuncios("id")%>');" /> Marcar anúncio como ALUGADO

  </form>

And here javascript:
$('body').popover({
    selector: '[data-popover]',
    title: 'Alugado ou Vendido <button type="button" id="close" class="close" onclick="$("[data-original-title]").popover("hide");">×</button>',
    placement : 'left',
    trigger: 'click',
    html: true,
    delay: {show: 50, hide: 400},
    content: function(ele) {
        console.log(ele,this);
        return $(this).next(".popover-content").html();
    }
});

$('body').on('click', function(e) {
    if (typeof $(e.target).data('original-title') == 'undefined' &&
  !$(e.target).parents().is('.popover.in')) {
        $('[data-original-title]').popover('hide');
    }
});

A: I had to take off the tag href:


text:
Q: Save every computation without making MatLab run slowly I have main.m and other tens of m-files associated with that main m-file. In total they are more than 5000 lines.
Because of this big size of the program, it's really hard to debug.
If I eliminate every ";" then MatLab prints everything so that I can track back what this program is doing more easily.
However, MatLab runs slowly when it prints everything (because it takes time to print them all).
To be concrete, if I do
diary 'out.txt'
a=1
diary off

then out.txt has "a=1" in it, but if I do
diary 'out.txt'
a=1;
diary off

then out.txt doesn't have anything.
I just want to see/save every variable that MatLab computed until it hit an error to an output file like out.txt (so that I can easily track where the error has come from), while at the same time not slowing down the program execution. Is there a way to make this possible?


text:
Q: Cannot resize stack of type template Im trying to resize my stack but my program keeps terminating after the 'cout'.
On the output terminal it displays 1 and then the program terminates. In this case T is an int and size is set to 10 by default. Any help will be much appreciated.
#include <iostream>
#include <fstream>

using namespace std;

template <typename T>
class stack {

public:

    int topStack;
    T* stack1;
    int size;
    void copy(const stack& other);
    void move(stack&& other);
  // constructor
  stack ();
  // destructor
  ~stack()
  {
        delete[] stack1;
  };
    // copy constructor
    stack (const stack&);
    // copy assignment
    stack& operator= (const stack&);
    // move constructor
    stack (stack&&);
    // move assignment
    stack& operator= (stack&&);

    T& top() const;  // return the top element
    void pop ();  // remove the top element
    void push(const T&); // add element on top of stack
    void push (T&&); // add element on top of stack
    bool empty() const; // is the stack empty?
    void clear(); // remove all elements
    ostream& print(ostream&, stack&);
    void resize();
};

//Default Constructor
template <typename T>
stack<T>::stack()
{
        size=10;
        stack1= new T[size];
        for(int b =0; b < size; b ++)
        {
            stack1[b] = T();
        }
        topStack =-1;

}

//Copy Constructor
template <typename T>
void stack<T>::copy(const stack& other)
{
        topStack = other.topStack;
        stack1= new T[other.size];
        size =other.size;
        for(int i=0; i< other.size ; i++)
        {
            stack1[i]=other.stack1[i];
        }

}

//Copy assignment
template <typename T>
stack<T>& stack<T>::operator =(const stack& other)
{
    if (this == &other) return *this;

    T* store = new T[other.size];
    for(int g =0; g < other.size ; g++)
    {
        store[g]= other.stack1[g];
    }
    delete[] stack1;
    this->stack1 = store;
    this->size = other.size;
    this-> topStack = other.topStack;

    return *this;
}
//Move Constructor
template<typename T>
void stack<T>::move(stack && other)
{
    topStack = other.topStack;
    other.topStack = 0;
    stack1 = other.stack1;
    for(int u =0; u < other.size ; u++)
    {
        other.stack1[u]=0;
    }
    size = other.size;
    other.size=0;
}

//Move assignment
template <typename T>
stack<T>& stack<T>::operator= (stack&& other)
{
    this->size = other.size;
    other.size=0;
    this->topStack = other.topStack;
    other.topStack=0;
    this->stack1 = other.stack1;
    for(int u =0; u < this->size ; u++)
    {
        other.stack1[u]=0;
    }
    return *this;

}
//Checks if stack is empty
template <typename T>
bool stack<T>::empty() const
{
    return topStack == -1;

}

//Resize array
template<typename T>
void stack<T>::resize()
{
    cout << "DAYYYY55UM";
    T* storage = new T[this->size*2];
    cout << "DAYYYYUM";
    for(int r=0; r < this->size ; r++)
    {
            storage[r]= this->stack1[r];
    }
    delete[] this->stack1;
    this->stack1= storage;
    this->size = size*2;

    cout << "DAYYYYUM";

}
//Returns top
template <typename T>
T& stack<T>::top() const
{
    if(empty())
    {
        cout << "ERROR: Stack is empty. "<< endl;
        return;
        //Make a throw catch statement here
    }
    return stack1[topStack];
}
//Pop
template <typename T>
void stack<T>::pop()
{
    if(empty())
    {
        cout << "ERROR: Stack is empty." << endl;
        return;
    }
    stack1[topStack] =0;
    topStack--;

}
//Push
template <typename T>
void stack<T>::push(const T& q)
{
    if(topStack < size)
    {
        topStack++;
        stack1[topStack] = q;
    }else{
    resize();
    }

}
//Push
template <typename T>
void stack<T>::push(T&& q)
{
    if(topStack < size)
    {
         topStack++;
         stack1[topStack] = q;
    }else{
    resize();
    }
}

//Print Function
template <typename T>
ostream& stack<T>::print(ostream& os, stack& other)
{
    os << other.stack1 ;
}

template <typename T>
void stack<T>::clear()
{
    for(int g=0; g < size; g++ )
    {
        stack1[g]=0;
    }
}

int main()
{
    stack<int> world;
    world.push(9);
    world.push(40);
    world.push(40);
     world.push(9);
    world.push(40);
    world.push(40);
     world.push(9);
    world.push(40);
    world.push(40);
     world.push(9);
    world.push(40);
    world.push(40);

    cout << world.stack1[12] << endl;

    return 0;
}

A: That error means that you have an out of bounds array access somewhere that is corrupting malloc's data structures.
The error is in your push function:
template <typename T>
void stack<T>::push(T&& q)
{
    if(topStack < size)
    {
         topStack++;
         stack1[topStack] = q;
    }else{
    resize();
    }
}

When you write the last item before resize, topStack is one less than size, which is a valid index (the last one, indeed), but then you increment it to size, and write the item in that position, and that's not a valid index.
By the way, you have a lot of errors with the indexes al over your class. My advice woulbe to take into account that c++ arrays start at 0 and end at size-1, and revise your code.
And have you noticed that when you resize the array you don't add the new item?


text:
Q: Avatars/Images in a Buefy Table How would we get images in to a table cell. The database has the URL to the image, but not sure how to get into a regular Buefy table row lets say the second cell for example?

A: You can get the desired outcome by customizing your own buefy table.
Notice how I wrap the columns inside a slot-scope named props
<b-table :data="banners" paginated per-page="5">
      <template slot-scope="props">
        <b-table-column field="id" label="ID" width="40" numeric>{{ props.row.id }}</b-table-column>
        <b-table-column field="image" width="90">
          <img :src="props.row.image" alt />
        </b-table-column>
        <b-table-column field="name" label="Name">{{ props.row.name }}</b-table-column>
        <b-table-column field="date_creted" label="Date created">{{ props.row.date_created }}</b-table-column>
        <b-table-column field="status" label="Status">{{ props.row.status }}</b-table-column>
      </template>
</b-table>

Script
banners: [
        {
          id: 1,
          image: "https://picsum.photos/200",
          name: "Sample banner",
          date_created: "2016-10-15 13:43:27",
          status: "Active"
        },
        {
          id: 2,
          image: "https://picsum.photos/200",
          name: "Banner the great",
          date_created: "2016-12-15 06:00:53",
          status: "Active"
        },
        {
          id: 3,
          image: "https://picsum.photos/200",
          name: "Awesome Banner",
          date_created: "2016-04-26 06:26:28",
          status: "Inactive"
        },
        {
          id: 4,
          image: "https://picsum.photos/200",
          name: "Hellp Banner",
          date_created: "2016-04-10 10:28:46",
          status: "Active"
        },
        {
          id: 5,
          image: "https://picsum.photos/200",
          name: "Dating Banner",
          date_created: "2016-12-06 14:38:38",
          status: "Inactive"
        }
      ]

Working example here


text:
Q: Report server data driven subscription render format We are using data driven subscription for reports. Reports with PDF as attachment is working, but reports with Excel as attachment is not working.

A: Use EXCELOPENXML as the render format for Excel.  This works for me with Data Driven subscriptions.
https://learn.microsoft.com/en-us/sql/reporting-services/report-builder/exporting-to-microsoft-excel-report-builder-and-ssrs?view=sql-server-ver15
The EXCELOPENXML extension defines the Excel renderer for current (.xlsx) Excel files. The EXCEL extension defines the Excel 2003 version. Visible = "false" indicates the Excel 2003 renderer is hidden.


text:
Q: Substitution in ODE A tutorial (page 17) on ODE scaling takes the equation $m\ddot{u}+c\dot{u}+ku=F_0sin(\omega t)$, with $u$ a function of $t$, and substitutes $\eta=u/a$, $\tau=t/b$ to get:
$$\frac{ma}{b^2}\ddot{\eta}+\frac{ca}{b}\dot{\eta}+ka\eta=F_0sin(\omega\tau)$$
Now, when I differentiate $\eta=u/a$, I get $\dot{\eta}=t\dot{u}/a=\tau b\dot{u}/a$. Substituting, the final result is:
$$\frac{ma}{\tau^2b^2}\ddot{\eta}+\frac{ca}{\tau b}\dot{\eta}+ka\eta=F_0sin(\omega\tau b)$$
That's not the same. What am I missing?

A: Differentiating $\eta=u/a$ gives $\eta'=u'/a$, not $\eta'=tu'/a$, no?

A: Gerry has already explained the differences on the left-hand side. On the right-hand side, this is a typo in the book. The next equation has $\sin\omega'\tau$ instead of $\sin\omega\tau$, with $\omega'=\omega\sqrt{m/k}$ and $b=\sqrt{m/k}$, so this is $\sin\omega\tau b$ as you expected. So it should be either $\sin\omega t$ or $\sin\omega'\tau$ on the right-hand side.


text:
Q: What i need to know to understand augmented reality First off let me say that i can use AR SDK(like artoolkits) to build an AR app. But now i want to know more about how it works(like the detector,tracking...) because it's kind of annoying when you use something but don't understand it(of course it have something to do with my study as well).
So basically lets assume that i want to do AR without using SDK, what knowledge i need to know to do that. Any help would be greatly appreciated.
p/s:sorry for my bad english.

A: Here are some thoughts which may help you:
MUST (Wikipedia's entries)

*

*Virtual reality.

*Augmented reality (french version available here)

They provide links pointing to many relevant references.
FORUMS (Picked at random)

*

*AR Augmented Reality Forum

*The International Augmented Reality Meetup Groups Forum

*Forum La réalité augmentée (in french)

To keep up with the state of the art.
COURSE SYLLABUS (Picked at random)

*

*University of Illinois
To have a glimpse of what is actually taught.
OPENSOURCE PROJECTS (Picked at random)

*

*Google code

*Sourceforge
To get involved hands-on in down-to-the-metal coding.


text:
Q: BackboneJS - interfering with normal hash behaviour I'm serving a simple page using BackboneJS with its router.
On one of my DOM elements, I have

Content

and when I go to
http://www.myhomepage.com/page#1234
I want the page to scroll to where that DIV is located (which is the expected behaviour).
But since I'm using Backbone, it must be interfering with it because it isn't working properly. I read the backbone document and it seems like it's not recognizing the hash value, and I suppose I can set up "Catch all" route for all un-matched ones (Is there a way to catch all non-matched routes with Backbone?)
But how do I actually make this behave the way I would like (i.e. make the page scroll to the right div)?

A: Ok, first a little background.  In the early days of the web, browsers had these things called anchors, or as you now know them, a tags:

Anchors let you "bookmark" a part of a page, so that you could then link to that part specifically:

Eventually, browsers added ID attributes as anchors also.
Then modern JS and Backbone came along, and that's where the trouble started, because the Backbone router hijacks that system.  This means that if you want to use Backbone's router, you lose the ability to have normal anchors.
However, all is not lost.  One option is to make Backbone not use the URL hash for it's router, and instead rely on the browser's "push state".  You can do this by passing an extra option when you start the router:
 Backbone.history.start({pushState: true})

You can read more about the limitations of that approach here:
http://backbonejs.org/#History
but the short version is that it will only work for the browsers marked in green here:
http://caniuse.com/#search=pushstate
Another approach would be to re-create your own anchor system, using jQuery.  Basically you can create a fallthrough for when none of your routes match:
 if (!Backbone.history.start() {

and then in that fallthrough you can use jQuery to manually scroll to the desired point:
     $('html, body').animate({
         scrollTop: $('#' + window.location.hash).offset().top
     }, 1000);

You could also get fancy and define custom routes instead of using a fallthrough, but I'll leave that up to you.
In addition to these options @Pramod linked to a question with answers containing still other options you could also consider (like modifying the Backbone router to build scrolling functionality in).


text:
Q: How to change from CoNLL format into a sentences list? I have a txt file in, theoretically, CoNLL format. Like this:
a O
nivel B-INDC
de O
la O
columna B-ANAT
anterior I-ANAT
del I-ANAT
acetabulo I-ANAT

existiendo O
minimos B-INDC
cambios B-INDC
edematosos B-DISO
en O
la O
medular B-ANAT
(...)

I need to convert it into a list of sentence, but I don't find a way to do it. I tried with the parser of  conllu library:
from conllu import parse
sentences = parse("location/train_data.txt")

but they give the error: ParseException: Invalid line format, line must contain either tabs or two spaces.
How can I get this?
["a nivel de la columna anterior del acetabulo", "existiendo minimos cambios edematosos en la medular", ...]

Thanks

A: for NLP Problems, the first starting point is Huggingface - always for me - :D
There is a nice example for your problem: https://huggingface.co/transformers/custom_datasets.html
Here they show a function that is exactly doing what you want:
from pathlib import Path
import re

def read_wnut(file_path):
    file_path = Path(file_path)

    raw_text = file_path.read_text().strip()
    raw_docs = re.split(r'\n\t?\n', raw_text)
    token_docs = []
    tag_docs = []
    for doc in raw_docs:
        tokens = []
        tags = []
        for line in doc.split('\n'):
            token, tag = line.split('\t')
            tokens.append(token)
            tags.append(tag)
        token_docs.append(tokens)
        tag_docs.append(tags)

    return token_docs, tag_docs

texts, tags = read_wnut("location/train_data.txt")

A: Simplest thing is to iterate over the lines of your file and then to retrieve the first column. No imports required.
result=[[]]
with open(YOUR_FILE,"r") as input:
    for l in input:
        if not l.startswith("#"):
            if l.strip()=="":
                if len(result[-1])>0:
                    result.append([])
            else:
                result[-1].append(l.split()[0])
result=[ " ".join(row) for row in result ]

In my experience, writing these from hand is the most effective way, because CoNLL formats are terribly diverse (but usually in trivial ways, such as order of columns) and you don't want to bother with other people's code for anything that can be so simply solved. The code quoted by @markusodenthal will, for example, maintain CoNLL comments (lines starting with #) -- which may not be what you want.
The other thing is that writing the loop yourself allows you to process sentence by sentence rather than first reading everything into an array. If you don't need processing en bloc, this will be both faster and more scalable.

A: You can use the conllu library.
Install using pip install conllu.
A sample use-case is shown below.
>>> from conllu import parse
>>>
>>> data = """
# text = The quick brown fox jumps over the lazy dog.
1   The     the    DET    DT   Definite=Def|PronType=Art   4   det     _   _
2   quick   quick  ADJ    JJ   Degree=Pos                  4   amod    _   _
3   brown   brown  ADJ    JJ   Degree=Pos                  4   amod    _   _
4   fox     fox    NOUN   NN   Number=Sing                 5   nsubj   _   _
5   jumps   jump   VERB   VBZ  Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin   0   root    _   _
6   over    over   ADP    IN   _                           9   case    _   _
7   the     the    DET    DT   Definite=Def|PronType=Art   9   det     _   _
8   lazy    lazy   ADJ    JJ   Degree=Pos                  9   amod    _   _
9   dog     dog    NOUN   NN   Number=Sing                 5   nmod    _   SpaceAfter=No
10  .       .      PUNCT  .    _                           5   punct   _   _

"""
>>> sentences = parse(data)
>>> sentences
[TokenList<The, quick, brown, fox, jumps, over, the, lazy, dog, .>]


text:
Q: Warning: "Variables with usage in documentation object 'FANG' but not in code:" On R-devel (>3.6.1 at the time), a new warning has popped up in my package when running R CMD Check that looks like:
"Variables with usage in documentation object 'FANG' but not in code:"
'FANG'

FANG is a data set that I include in my package.
You can see the exact error at:
https://travis-ci.org/business-science/tibbletime/jobs/568639099#L3163
You can see the frozen state of this package at:
https://github.com/business-science/tibbletime/blob/305e80ee3f6eecd728eb06937650dae03c94320c/R/data.R#L18
Below, I answer my own question about what this error means, and why it occurred.

A: This is a new check introduced in R-devel here:
https://github.com/wch/r-source/commit/c9adb21c2e37cbc6dccd4c1eceec1873c10e3d9e#diff-4882a8c8e173bda109ed98da485e1428
While the error message is confusing, the fix for me was to set LazyData: true in my DESCRIPTION file.
The problem was that in my data.R file, I use roxygen2 to generate the Rd file. The data.R file looks like:
#' Stock prices for Facebook, Amazon, Netflix and Google from 2013-2016
#'
#' A dataset containing the date, open, high, low, close, volume, and adjusted
#' stock prices for Facebook, Amazon, Netflix and Google from 2013-2016.
#'
#' @format A tibble with 4,032 rows and 8 variables:
#' \describe{
#'   \item{symbol}{stock ticker symbol}
#'   \item{date}{trade date}
#'   \item{open}{stock price at the open of trading, in USD}
#'   \item{high}{stock price at the highest point during trading, in USD}
#'   \item{low}{stock price at the lowest point during trading, in USD}
#'   \item{close}{stock price at the close of trading, in USD}
#'   \item{volume}{number of shares traded}
#'   \item{adjusted}{stock price at the close of trading adjusted for stock splits, in USD}
#' }
#' @source \url{http://www.investopedia.com/terms/f/fang-stocks-fb-amzn.asp}
"FANG"

And the generated Rd looks like:
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{FANG}
\alias{FANG}
\title{Stock prices for Facebook, Amazon, Netflix and Google from 2013-2016}
\format{A tibble with 4,032 rows and 8 variables:
\describe{
\item{symbol}{stock ticker symbol}
\item{date}{trade date}
\item{open}{stock price at the open of trading, in USD}
\item{high}{stock price at the highest point during trading, in USD}
\item{low}{stock price at the lowest point during trading, in USD}
\item{close}{stock price at the close of trading, in USD}
\item{volume}{number of shares traded}
\item{adjusted}{stock price at the close of trading adjusted for stock splits, in USD}
}}
\source{
\url{http://www.investopedia.com/terms/f/fang-stocks-fb-amzn.asp}
}
\usage{
FANG
}
\description{
A dataset containing the date, open, high, low, close, volume, and adjusted
stock prices for Facebook, Amazon, Netflix and Google from 2013-2016.
}
\keyword{datasets}

The issue is in the \usage{} section. I have LazyData: false implicitly, which means that \usage{FANG} is incorrect and should really be \usage{data(FANG)}. There is nothing that I could have changed in my data.R file to generate this, as roxygen2 essentially assumes you have LazyData: true when it generates the data Rd file.
So, this is a true error picked up by R CMD Check, but the message is a bit confusing. Luckily, the fix is fairly easy, and non-invasive.


text:
Q: Why my components are Rerender and how can I prevent this? I have a list of users. When I longpress a Modal is opening. While I longpress, I dispatch an userID.
So the modal is open, the user id is set. It works fast.
But if I add useSelector in my app, and I want to again open my modal, then its slow/ a little delay and my react.memo component is rerender. How can I prevent this ?
import * as React from 'react';
import { StyleSheet, Text, View, Pressable, Image, Dimensions, Animated } from 'react-native';
import BottomSheet, { BottomSheetFlatList } from '@gorhom/bottom-sheet';
import { chatMockFlat } from '../utils/mockChat';
import { useSelector } from 'react-redux';
import { ChatPeopleSetting } from '../components/modal/chat/chatPeopleSetting';
import { Portal } from 'react-native-portalize';
import { useDispatch } from 'react-redux';
import { setCurrentUserID } from '../redux/slice/chat/chatSlice';

const { width } = Dimensions.get('window');

const chatSearchValue = state => state.chatSlice.headerSearchChats;
const currentUserID = state => state.chatSlice.currentUserID;

const Item = React.memo(({ name, date, image, id, text, modal }) => {
  console.log('rerender')
  return (
    <Pressable style={s.chatItem}>

      <View style={s.viewLeftImage}>
        <Pressable delayLongPress={100} onLongPress={() => modal(id)} style={s.imagePress}>
          <Image source={{uri: image}} style={s.profile_image} resizeMode='contain' />
          <View style={s.onlineStatus}></View>
        </Pressable>
      </View>

      <View style={s.viewMidText}>
        <View style={s.viewHeaderText}>
          <Text style={s.name}>{name}</Text>
          <Text style={s.date}>{date}</Text>
        </View>
        <Text style={s.text}>{text}</Text>
      </View>

    </Pressable>
  )
});

const Messages = (props) => {
  const modals = Array.from({ length: 8 }).map(_ => React.useRef(null).current);
  const userID = useSelector(currentUserID);

  const dispatch = useDispatch();

  const bottomSheetRef = React.useRef(null);

  const handleOpenModalSetting = React.useCallback((e) => {
    modals[1]?.open();
    dispatch(setCurrentUserID(e));
  });

  const handleCloseModal = React.useCallback(() => modals[1].close()
  // variables
  const snapPoints = React.useMemo(() => ['25%', '100%'], []);

  const renderItem = ({ item }) => (
    <Item name={item.name} date={item.date} image={item.image} id={item.id} text={item.text} />
  )

  return (
    <View style={s.container}>
      <BottomSheet
        ref={bottomSheetRef}
        index={1}
        style={s.sheetContainer}
        snapPoints={snapPoints}
        handleStyle={{borderTopLeftRadius: 16, borderTopRightRadius: 16,}}
      >
        <BottomSheetFlatList
          data={chatMockFlat}
          keyExtractor={i => i.id}
          renderItem={renderItem}
        >

        </BottomSheetFlatList>
      </BottomSheet>
      <Portal>
          <ChatPeopleSetting ref={el => (modals[1] = el)} onPressExit={handleCloseModal} />
        </Portal>
    </View>
  )
};

Modals constant console log first click
Array [
  null,
  Object {
    "close": [Function close],
    "open": [Function open],
  },
  null,
  null,
  null,
  null,
  null,
  null,
]

second click (when its not opening)
Array [
  null,
  null,
  null,
  null,
  null,
  null,
  null,
  null,
  null,
]

A: Follow the bottom instructions and fix reasons causing re-rendering your component:

*

*Add shallowEqual as second argument to useSelector

*Add dependencies as second argument to handleOpenModalSetting and handleCloseModal functions. (if you want generally the functions don't be re-render just set empty array)

Update:
Update following code pieces into your code and try once.
//Imported packages
import {shallowEqual} from 'react-redux'

...
const userID = useSelector(currentUserID, shallowEqual);
...
const handleOpenModalSetting = React.useCallback((e) => {
  modals[1]?.open();
  dispatch(setCurrentUserID(e));
}, [modals, dispatch])
...
const handleCloseModal = React.useCallback(() => {
  modals[1].close();
}, [modals]);
...


text:
Q: Getting error number returned by recv function How can I get the error number or error string returned by the recv() in socket communication, recv() returns -1 as read size which means some error has occurred. I want to know the specific reason for the error. so how can I get that.

A: You can make use of the errno variable from errno.h header file.
From the man page (emphasis mine)

Return Value
Upon successful completion, recv() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.

Alternatively, you can also call perror() / strerror() to get a human-readable string related to the error.

A: You need to include errno.h and use the errno global variable to check the last error code. Also, you can use strerror() to print a locale aware string explaining the error.
Example
#include <errno.h>

ssize_t size;

if ((size = recv( ... )) == -1)
{
    fprintf(stderr, "recv: %s (%d)\n", strerror(errno), errno);
}


text:
Q: How to put measures on x-axis with date and time combine in python using tkinter and matplotlib and numpy I have a small GUI application using tkinter, matplotlib and numpy. Here user will upload an excel file and get multi line graph. But the main problem is I couldn't put the measures on x-axis. Here date and time combination will be the measure of x-axis. But only year is coming as measure. Here I am sharing my code:
import tkinter as tk
from tkinter import filedialog
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import pandas as pd
import matplotlib.dates
import numpy as np
from datetime import datetime

root= tk.Tk()

canvas1 = tk.Canvas(root, width = 1000, height = 300)
canvas1.pack()

label1 = tk.Label(root, text='Data Analyser')
label1.config(font=('Arial', 20))
canvas1.create_window(400, 50, window=label1)

def getExcel1 ():
      global df

      import_file_path = filedialog.askopenfilename()
      df = pd.read_excel (import_file_path)
      daytime=df.apply(lambda r : pd.datetime.combine(r['Day'],r['Time']),1)
      global bar1
      x = daytime
      y1 = df['Count']
      y2 = df['Month']

      figure1 = Figure(figsize=(8,3), dpi=100)
      subplot1 = figure1.add_subplot(111)
      subplot2 = figure1.add_subplot(111)
      bar1 = FigureCanvasTkAgg(figure1, root)
      bar1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=0)
      subplot1.plot(x, y1, color='green', linestyle='solid', linewidth = 2, marker='o',
                    markerfacecolor='green', markersize=8, label='y1')
      subplot2.plot(x, y2, color='red', linestyle='solid', linewidth = 2, marker='o',
                    markerfacecolor='red', markersize=8, label='y2')

def clear_charts():
      bar1.get_tk_widget().pack_forget()

browseButton_Excel1 = tk.Button(text='Load File...', command=getExcel1, bg='green', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(400, 180, window=browseButton_Excel1)

button2 = tk.Button (root, text='Clear Chart', command=clear_charts, bg='green', font=('helvetica', 11, 'bold'))
canvas1.create_window(400, 220, window=button2)

button3 = tk.Button (root, text='Exit!', command=root.destroy, bg='green', font=('helvetica', 11, 'bold'))
canvas1.create_window(400, 260, window=button3)

root.mainloop()

The measure of x-axis should look like '2021-09-06 16:35:00', but it is only comes with '2021'.
Here is my excel file date:

And also please suggest me how to put legend, axis label and figure name. Please help me out for this problem.

A: It's because it's issue in lambda  functon. Simply concat with plus operator instead
import tkinter as tk
from tkinter import filedialog
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import pandas as pd
import matplotlib.dates
import numpy as np
from datetime import datetime

root= tk.Tk()

canvas1 = tk.Canvas(root, width = 1000, height = 300)
canvas1.pack()

label1 = tk.Label(root, text='Data Analyser')
label1.config(font=('Arial', 20))
canvas1.create_window(400, 50, window=label1)

def getExcel1 ():
      global df

      import_file_path = filedialog.askopenfilename()
      df = pd.read_excel (import_file_path)
      df['Day'] = pd.to_datetime(df['Day'])

      daytime=df['Day'].astype(str) + ' ' + df['Time'].astype(str)

      global bar1
      x = daytime
      y1 = df['Count']
      y2 = df['Month']

      figure1 = Figure(figsize=(8,3), dpi=100)
      subplot1 = figure1.add_subplot(111)
      subplot2 = figure1.add_subplot(111)
      bar1 = FigureCanvasTkAgg(figure1, root)
      bar1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=0)
      subplot1.plot(x, y1, color='green', linestyle='solid', linewidth = 2, marker='o',
                    markerfacecolor='green', markersize=8, label='y1')
      subplot2.plot(x, y2, color='red', linestyle='solid', linewidth = 2, marker='o',
                    markerfacecolor='red', markersize=8, label='y2')

def clear_charts():
      bar1.get_tk_widget().pack_forget()

browseButton_Excel1 = tk.Button(text='Load File...', command=getExcel1, bg='green', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(400, 180, window=browseButton_Excel1)

button2 = tk.Button (root, text='Clear Chart', command=clear_charts, bg='green', font=('helvetica', 11, 'bold'))
canvas1.create_window(400, 220, window=button2)

button3 = tk.Button (root, text='Exit!', command=root.destroy, bg='green', font=('helvetica', 11, 'bold'))
canvas1.create_window(400, 260, window=button3)

root.mainloop()

Gives #


text:
Q: PHP executable path in Adobe Brackets I am running Adobe Brackets on a 2017 iMac (Retina - 27 inch) with macOS Monterey 12.2
I want to point the path to PHP inside of MAMP. What is the correct json format and code to do this in Bracket's brackets.json file?
I've seen this code for someone using XAMP on a PC:
"php": {
    "executablePath": "C:\\xampp\\php\\php.exe"
}

I tried this in my brackets.json file:
"php": {
    "executablePath": "/applications/MAMP/bin/php/php7.4.21/bin/"
}

but apparently that is not correct JSON formatting. I've tried using the double forward slashes to no avail.
It IS the correct path to the PHP 7.4.21 php executable file within my MAMP directory though.
This is what is currently in my brackets.json file:
{
    "brackets-eslint.gutterMarks": true,
    "brackets-eslint.useLocalESLint": false,
    "fonts.fontSize": "12px",
    "fonts.fontFamily": "'SourceCodePro-Medium', MS ゴシック, 'MS Gothic', monospace",
    "externalApplications": {
        "jpg": "Adobe Photoshop 2021",
        "jpeg": "Adobe Photoshop 2021",
        "png": "Adobe Photoshop 2021",
        "svg": "Brackets",
        "psd": "Adobe Photoshop 2021",
        "ai": "Adobe Photoshop 2021"
    }

}

Any suggestions?
Thanks.
Dennis

A: had exactly the same problem and for me - running a MacBook Pro with M1 Processor and Monterey and MAMP - worked the following:
{
    "brackets-eslint.gutterMarks": true,
    "brackets-eslint.useLocalESLint": false,
    "fonts.fontSize": "12px",
    "fonts.fontFamily": "'SourceCodePro-Medium', MS ゴシック, 'MS Gothic', monospace",
    "linting.collapsed": true,
    "externalApplications": {
        "jpg": "Preview",
        "jpeg": "Preview",
        "png": "Preview",
        "svg": "inkscape",
        "psd": "gimp"
    },
    "php": {
        "executablePath": "/Applications/MAMP/bin/php/php7.4.21/bin/php"
    }
}


text:
Q: 403 Forbidden Here is my Nginx config:
user pass users;

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    passenger_root /usr/lib64/ruby/gems/1.8/gems/passenger-3.0.7;
    passenger_ruby /usr/bin/ruby;
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
      listen 80;
      server_name some.another.ru;
      root /www/public/redmine;
      passenger_enabled on;
      rails_env development;
   }
}

Here is Nginx log:
2011/06/02 12:53:57 [error] 45986#0: *1 directory index of "/www/public/redmine/" is forbidden, client: **.*.**.***, server: some.another.ru, request: "GET / HTTP/1.1", host: "some.another.ru"
2011/06/02 12:53:59 [error] 45986#0: *1 open() "/www/public/redmine/favicon.ico" failed (2: No such file or directory), client: **.*.**.***, server: some.another.ru, request: "GET /favicon.ico HTTP/1.1", host: "some.another.ru"

What is the reason of this error and how can I fix it?

A: You need to point root directive to public sub-folder of redmine installation. In your case you should write root /www/public/redmine/public; instead of root /www/public/redmine;.


text:
Q: Bootbox javascript confirm dialog box I have a problem with this line of code :

How to apply the bootbox.js here. i hate the old javascript dialog box. how can i change this?
i already did this line :

still not working.

A: Just do this :
Suppose you have button for delete
<button class="delete-it">Delete</delete>

Write the this under click event of class delete-it
 $(".delete-it").click(function(){
    bootbox.confirm("Are you sure?", function(result) {
      if(result)
          window.location = 'delete.php?id=' + id;
    });
  });

As per comments below :
Using onclick is considered as bad practice. If you have $id value wrap it on data-attribute like this
Delete
And change JS in to this :
 $(".delete-it").click(function(){
    var id = $(this).data('id');
    bootbox.confirm("Are you sure?", function(result) {
      if(result)
          window.location = 'delete.php?id=' + id;
    });
  });

A: You can display the confirm dialog box in bootbox as follows
bootbox.confirm("Are you sure you want to Delete?", function(result) {
  if(result)
      window.location = 'delete.php?id=' + id;
});

You will get the result either as True or False depending on clicking on Yes or No in the Dialog Box.
For further information on bootbox confirm dialog box, you can look into here

A: Try this:


text:
Q: Issue when selecting desired elements from dict_keys in Python I have a list of dictionary keys ['A_report1', 'A_report2', ..., 'A_report10','B_report1', 'B_report2', ..., 'B_report10',]. I want to extract all 'report1' from this dict_keys. In other words, I should only get 'A_report1' and 'B_report1'.
Here's the code I tried:
[report for report in list(dictionary.keys()) if 'report1' in report]

Issue: It'll return 'A_report10' and 'B_report10' as well, I only want report1's. Anyway to fix this?

A: How about using a regular expression?
import re
rx = re.compile(r'report1\b')
items = [report for report in df if rx.search(report)]

A: here is a simple but non-robust solution based on the assumption that all your report names follow the format .*report<any int number>:
x = ['A_report10', 'B_report1', 'B_report2', 'B_report10']

report_1s = []

for i in x:
    if i[-7:]=='report1':
        report_1s.append(i)
        print(i)


text:
Q: pyspark get value counts within a groupby I have a dataframe df with a few columns. I want to groupby using one (or more) column and for every group, I want the count of values of another column(s).
Here's the df:
col1 col2  col3  col4
1     1      a    2
1     1      b    1
1     2      c    1
2     1      a    3
2     1      b    4

I want to groupby 'col1' and 'col2' and then for every group, the count of unique values in a column and then sum/mean/min/max of other column. I also want to maintain the grouped columns. the result should be:
col1 col2  count_a count_b count_c col4_sum
1     1      1        1      0       3
1     2      0        0      1       1
2     1      1        1      0       7

how do I achieve this?

A: You have two solutions
First, you can use pivot on col3 to get your count of unique values, and then join your pivoted dataframe with an aggregated dataframe that compute the sum/mean/min/max of other column.
Your code would be as follows:
from pyspark.sql import functions as F

result = df \
    .groupBy('col1', 'col2') \
    .pivot('col3') \
    .agg(F.count('col3')) \
    .fillna(0) \
    .join(
        df.groupby('col1', 'col2').agg(F.sum('col4').alias('col4_sum')),
        ['col1', 'col2']
    )

And with your input dataframe, you will get:
+----+----+---+---+---+--------+
|col1|col2|a  |b  |c  |col4_sum|
+----+----+---+---+---+--------+
|1   |1   |1  |1  |0  |3       |
|1   |2   |0  |0  |1  |1       |
|2   |1   |1  |1  |0  |7       |
+----+----+---+---+---+--------+

However, you can't choose the name of columns extracted from pivot, it will be the name of the value.
If you really want to choose the name of the columns, you can retrieve all distinct values first and then build your aggregation column from each of them, as follows:
from pyspark.sql import functions as F

values = map(lambda x: x.col3, df.select("col3").distinct().collect())

count_of_distinct_values = [F.sum((F.col('col3') == i).cast('integer')).alias('count_' + i) for i in values]
other_column_aggregations = [F.sum('col4').alias('col4_sum')]
aggregated = count_of_distinct_values + other_column_aggregations

result = df.groupBy('col1', 'col2').agg(*aggregated)

You then get the following dataframe:
+----+----+-------+-------+-------+--------+
|col1|col2|count_a|count_b|count_c|col4_sum|
+----+----+-------+-------+-------+--------+
|1   |1   |1      |1      |0      |3       |
|1   |2   |0      |0      |1      |1       |
|2   |1   |1      |1      |0      |7       |
+----+----+-------+-------+-------+--------+


text:
Q: keyword extraction by using KEA or other python library I am now working for a keyword extraction project. Basically, I use python to do that.
Let me talk about what my project is first.
My goal in this project is going to find out the key word (key-phrase is not that preferable) from a paragraph or a webpage.
I assume that I can crawl a pretty well structure of content from a website.
Let say I got lots of paragraph and all the paragraph are from the same industry. Here is one of the example paragraph:

About us
We are the greatest bank in the world, which provide the most safe service in the world. Our bank is providing FX, security trading and saving services. Over the past few years, we successfully build up a reliable reputation.

Secondly, I have labeled the keyword from these paragraph in other to have a supervised learning model.
Finally, I have tried to use KEA, which is a JAVA program ( I use python to call JAVA program), to have a model.
However, the result finally is damn bad. The accuracy rate is only about 15%. It means that if I give a paragraph to my KEA program, KEA will output 10 keywords to me and nearly 85% that all these keyword are actually not a desirable keyword.
Here I got few questions:

*

*This question is about the preparing material for KEA. Is it that the keyword should be include in the .txt file in training data? or I should delete it from the paragraph? Because it is about confused in the readme file from KEA :

'Delete the author-assigned keyphrases from those documents
and put them into separate ".key" files. For example, if
your document file is called doc1.txt, move the keyphrases
into a new file called "doc1.key". It is important that
you put each keyphrase on a separate line in this file!'
So let say I have the last example paragraph for my training data and assume that 'safe' and 'reliable' . Should I delete these two words from the paragraph??

*As KEA can apply SKOS vocabularies, does it mean that if I use a appropriate SKOS vocabularies in a certain kind of topic ( Let's say financial industry), my model result will be better? If yes, where can I find these SKOS vocabularies, for example I want SKOS vocabularies about financial industry.

*Are there suggestion library from python that can be powerful in this topic? can anyone share to me?
Thanks a lot.

A: Actually, I tried to use this (https://www.kaggle.com/c/word2vec-nlp-tutorial/details/part-1-for-beginners-bag-of-words) kaggle example to do that. However, it is just too simple.
Somehow, I wanna know more practice case. Like how netfix or facebook detects people's comment.  Will anyone shall much more about this text mining information to me?


text:
Q: Change multidimensional array to a single dimensional array I have query which will return id, but instead of returning a single dimensional array it returns a multidimensional array
This is the query
$query_select_id= "SELECT `id` FROM `sub_pages` WHERE `page_id`=3";
$sub_category_id = mysqli_query($id_mysql, $query_select_id);
while($row=  mysqli_fetch_assoc($sub_category_id)){
    $sub_category_id_array[]=$row;
}
print_r($sub_category_id_array);

I am looking to change my array format from
Array ( [0] => Array ( [id] => 13 ) [1] => Array ( [id] => 14 ) [2] => Array ( [id] => 15 ) [3] => Array ( [id] => 16 ) [4] => Array ( [id] => 17 ) [5] => Array ( [id] => 18 ) )

To the following
Array ( [0] => 13 [1] => 14 [2] => 15 [3] => 16 [4] => 17 [5] => 18 )

A: Your query returns a row as an array, to just use a vlaue in that array change your line to:
 $sub_category_id_array[]=$row['id'];

A: $single = arrary();
foreach($sub_cat as $val) {
  $single[] = $val['id'];
}

So, go through, append to array.
On second read through of your code, just change this line
 $sub_category_id_array[]=$row['id'];

A: For future googlers, if you want to extract a specific key from a multidimensional array and make an array out of it you can use array_column.
so in OP's case, he could have proceeded as follows to achieve his desired result.
$result_array = array_column($sub_category_id_array, 'id');

A: multi_dimensional_array = [1,[9,[[[[[2]]]]]],[[[2],[12,[2]],[10]]]
change to :
answer: [1, 9,2,2,12,2,10]


text:
Q: How to use pad left method in C++/CLI I'm trying to pad '0' to the left of an unsigned int in C++ using CLI.
This is what I tried,
unsigned int pSz = 65; // This pSz value can range from 0 to 9999
String^ sizeOfPkt(pSz.ToString());
sizeOfPkt->PadLeft(4, L'0');

If the value of pSz is 65 then I'm expecting 0065 to be the sizeOfPkt value.
If the value of pSz is 350 then I'm expecting 0350 to be the sizeOfPkt value.
Can someone pls. suggest any ways to achieve this?
Thanks.

A: You always get a new string. The function in the string class usually never modify an existing string. They create a new one and return the result.
unsigned int pSz = 65;
String^ sizeOfPkt(pSz.ToString()->PadLeft(4,L'0'));


text:
Q: if elseif statement in a do/while statement infinite looping javascript I'm trying to get my head round do/while loops and logical operators in js. My problem is when embedding a if/ else if/ else statement into the do section as it keeps looping the alerts. Also, if i type anything other than rare, medium or well-done it goes into the else if statement rather than the else statement even though I've specified medium or well-done for the else if statement. Where am I going wrong? Any help would be appreciated.
Thanks.
var food;
var steak;

food = prompt("Hey what type of food do you want to eat? We have steak,                  chicken, legumes, kangaroo or pufferfish?","Select your choice   here.").toUpperCase();

switch (food) {
    case 'STEAK':
        alert ("Sure no problem, how would you like your steak done?");
        steak = prompt("Would you like your steak done rare, medium or well-done?").toUpperCase();
            do {
                if (steak === "RARE") {
                    alert ("You eat the rare steak");
                }
                else if (steak === "MEDIUM"||"WELL-DONE") {
                    alert("You eat your steak and it's good.");
                }
                else {
                    alert("Sorry didn't catch that.");
                    steak = prompt("Choose rare, medium or well-done.");
                }
            } while (steak !== "RARE" || "MEDIUM" || "WELL-DONE");
        break;
}

A: You have to do each comparison individually, so
else if (steak === "MEDIUM"||"WELL-DONE") {
    alert("You eat your steak and it's good.");
}

should be
else if (steak === "MEDIUM"|| steak === "WELL-DONE") {
    alert("You eat your steak and it's good.");
}

and so on.
This is also the cause of your infinite do/while loop.

A: It is going in infinite loop because of the condition you have in the 'while' construct always equates to "true".
What you have is as follows:
while (steak !== "RARE" || "MEDIUM" || "WELL-DONE")

Change it to
while (steak !== "RARE" && steak !== "MEDIUM" && steak !== "WELL-DONE")

Also, you have a similar problem in one of the 'else if' statements.
else if (steak === "MEDIUM"||"WELL-DONE") {

Change it to
else if (steak === "MEDIUM"|| steak === "WELL-DONE") {

There are still a few logical problems in your script. Try something like following instead:
var food;
var steak;

food = prompt("Hey what type of food do you want to eat? We have steak,                  chicken, legumes, kangaroo or pufferfish?","Select your choice   here.").toUpperCase();

switch (food) {
case 'STEAK':
    alert ("Sure no problem, how would you like your steak done?");

    steak = prompt("Would you like your steak done rare, medium or well-done?").toUpperCase();
    while (steak !== "RARE" && steak !== "MEDIUM" && steak !== "WELL-DONE") {
        alert("Sorry didn't catch that.");
        steak = prompt("Choose rare, medium or well-done.").toUpperCase();
    }

    if (steak === "RARE") {
        alert ("You eat the rare steak");
    }
    else if (steak === "MEDIUM"|| steak === "WELL-DONE") {
        alert("You eat your steak and it's good.");
    }
    break;
}

Let me know if it still doesn't work.

A: As pointed above, the conditions have to be separately tested i.e
    if (a == n || a == m)
Also your last statement isn't correct. You might want to do something like

var food;
var steak;

food = prompt("Hey what type of food do you want to eat? We have steak,                  chicken, legumes, kangaroo or pufferfish?","Select your choice   here.").toUpperCase();

switch (food) {
    case 'STEAK':
        alert ("Sure no problem, how would you like your steak done?");
        steak = prompt("Would you like your steak done rare, medium or well-done?").toUpperCase();
        console.log('steak', steak);
            do {
                console.log('steak inside do', steak);
                if (steak === "RARE") {
                    alert ("You eat the rare steak");
                }
                else if (steak === "MEDIUM"|| steak ==="WELL-DONE") {
                    alert("You eat your steak and it's good.");
                }
                else {
                    alert("Sorry didn't catch that.");
                    steak = prompt("Choose rare, medium or well-done.").toUpperCase();
                }
            } while (steak !== "RARE" && steak !== "MEDIUM" && steak !== "WELL-DONE");
        break;
}

Worked for me .


text:
Q: How to push key value of element to array_push using PHP I have created empty array and want to push all values and its key to the new created array but I am getting error array_push() expects at least 2 parameters I know array_push needs two parameter and here I am passing only one but what I ant is all keys and values to be pushed directly to array
//   Here 'userid' is just text or can say sample key and
 //  Here $userid is getting from table so expected output

 //   'userid'=>$userid

$temp = array();

  array_push($temp['userid'] = $userid);

A: To push to an array using a key - value pair, you do not need to use array_push.
array_push expects the array, and the value (no key) that you're pushing.
To push to an array using a key - value pair simply do :
$temp['user_id'] = $userid;

A: To use array_push you must give it the original array (modified by reference) and the new entry (value) for it. In this case since you have a key as well, you'd need to merge your arrays:
$temp = array_merge($temp, ['userid' => $userid]);

However, you can use simple array syntax instead to achieve the same thing:
$temp = array();
$temp['userid'] = $userid;


text:
Q: search array ID with 2 tables relacional with Jquery I've tried to make the codes and nothing success.
I would like some help and if some code is missing.
If I type the input which is the brand name (from REGISTER table) and get the result of the product type element (TYPE from Product List table).

$(btn_search).click(function() {
  var search = $("search").val();
  var data = "op=list of product&name=" + search;
  $.get('prod.php', data, function(response) {
    console.log(response);
    var line = "";
    $.each(result.data, function(i, item) {
      var value = $(this).val();
      $("table tbody tr").each(function(index) {
        if (item !== 0) {
          $row = $(this);
        }
      });
    });
  });
});
<button class="btn-primary" id="btn_search">SEARCH</button>

      NAME OF PRODUTS:
      BRAND:

public function list of product
$id = $_GET['id'];
$name = $_GET['name'];

$data = q_pdo("SELECT prod.id, prod.name, prod.description, prod.type,reg.id as registrationid, reg.brand as namebrand
FROM List Of Product
JOIN IN reg.id as registrationid, reg.brand as namebrand");

public function registration
$id = $_GET['id'];
$name = $_GET['name'];

$data = q_pdo("SELECT reg.id  reg.brand, reg.qtde FROM Registration");


text:
Q: convert list to xml string in python I have following list in Python:
list = ["one", "two", "three", "four", "five"]

and would like to convert it to following string:
<field>one</field><field>two</field><field>three</field><field>four/field><field>five</field>

what is the most efficient way?

A: One way to do this would be:
"".join("<field>{}</field>".format(x) for x in list)

This uses a "list comprehension" to iterate through your list and apply a string format to each element. Then, the elements created that way are joined together into one big string to get the final result.


text:
Q: Keyframe no css para efeito de background Olá, tudo bem?
Eu tentei fazer uma mudança de background usando keyframe, porém as imagens quando mudam piscam na primeira vez, como se estivesse carregando. Isso é normal ou fiz algo errado?
Aqui está a página no github pages. Estou tentando fazer para celulares primeiro e depois para desktop.
https://frazaovitor.github.io/Projeto-AVIX/
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@700&display=swap" rel="stylesheet">
    <title>AVIX CAMISARIA</title>

Desfazendo

 Padrões

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Open Sans", sans-serif;
}

.logo {
  display: flex;
  background-color: #000;
  color: #fff;
  font-size: 0.5rem;
  justify-content: center;
  align-items: center;
  width: 100%;
}
.carrossel {
  height: 92vh;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  animation: background 40s infinite alternate;
}

@keyframes background {
  0% {
    background-image: url("../img/background1.jpg");
  }
  25% {
    background-image: url("../img/background2.jpg");
  }
  50% {
    background-image: url("../img/background3.jpg");
  }
  100% {
    background-image: url("../img/background4.jpg");
  }
}

Desde já, muito obrigado.

A: Sim, é normal, elas não piscam, na verdade a area esta com fundo branco, a próxima imagem ainda não foi carregada, se você estive-se em uma internet lenta, tipo um 3G lento, talvez nem visse a foto, o que você pode fazer é talvez trocar por  ou usar um sistema de carrousel "melhor", ou então para ajudar no código que já tem você poderia usar o https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
Exemplo:

  ...

  <link rel="preload" href="../img/background1.jpg" as="image">
  <link rel="preload" href="../img/background2.jpg" as="image">
  <link rel="preload" href="../img/background3.jpg" as="image">
  <link rel="preload" href="../img/background4.jpg" as="image">

Lembrando que o Firefox não suporta isso, pois houve diversos problemas anteriormente e por enquanto tal recurso está desabilitado no navegador.
Recomendo realmente que use  ou um sistema de carousel pronto.


text:
Q: Callback as an option in node.js I am working with node.js and how can I set callback as an option of a specific function?
For example:
    function sum(a, b, callback) {
      return callback(a+b)
    }

    var result = sum(a,b) // this seems to cause error: callback is not a function

    sum(a, b, function(sum) {
      // this works fine
    })

Is there any way to make both of the above (with and without callback) work?
Thanks!

A: Simply check that the callback argument is a function.
if(typeof callback === 'function'){
    return callback(a+b);
}

Thus, your sum function can be written as :
function sum(a, b, callback) {
    if(typeof callback === 'function'){
        return callback(a+b)
    }
    else {
      return a+b;
    }
}

(Demo JSFiddle)

A: Hi you can have your code as below
function sum(a, b, callback) {
    if(typeof callback === 'function'){
        return callback(a+b)
    }
    else {
      return a+b;
    }
}

which is also mentioned in the above post


text:
Q: PL/SQL Reg Exp found last number and split How do I use reg expression to found last number in a string and then everything on the right hand side in to column c1 and from the last number everything on the left + 1 character go into column c2 ?
e.g 1
string = 1234john4345 this is a test.

Result
c1 = 1234john4345
c2 = this is a test.

e.g 2
string = 1234john4345a this is a test.

Result
c1 = 1234john4345a
c2 = this is a test.

A: select test
    --Group 1: Match everything up to the last digit, and one other character
    --Group 2: Everything after group 1
    ,regexp_replace(test, '(.*[[:digit:]].)(.*)', '\1') c1
    ,regexp_replace(test, '(.*[[:digit:]].)(.*)', '\2') c2
from
(
    select '1234john4345 this is a test.' test from dual union all
    select '1234john4345a this is a test' test from dual
);


text:
Q: What's the most efficient way to marshal C++ structs to C#? I am about to begin reading tons of binary files, each with 1000 or more records. New files are added constantly so I'm writing a Windows service to monitor the directories and process new files as they are received. The files were created with a c++ program. I've recreated the struct definitions in c# and can read the data fine, but I'm concerned that the way I'm doing it will eventually kill my application.
using (BinaryReader br = new BinaryReader(File.Open("myfile.bin", FileMode.Open)))
{
    long pos = 0L;
    long length = br.BaseStream.Length;

    CPP_STRUCT_DEF record;
    byte[] buffer = new byte[Marshal.SizeOf(typeof(CPP_STRUCT_DEF))];
    GCHandle pin;

    while (pos < length)
    {
        buffer = br.ReadBytes(buffer.Length);
        pin = GCHandle.Alloc(buffer, GCHandleType.Pinned);
        record = (CPP_STRUCT_DEF)Marshal.PtrToStructure(pin.AddrOfPinnedObject(), typeof(CPP_STRUCT_DEF));
        pin.Free();

        pos += buffer.Length;

        /* Do stuff with my record */
    }
}

I don't think I need to use GCHandle because I'm not actually communicating with the C++ app, everything is being done from managed code, but I don't know of an alternative method.

A: Using Marshal.PtrToStructure is rather slow. I found the following article on CodeProject which is comparing (and benchmarking) different ways of reading binary data very helpful:

Fast Binary File Reading with C#

A: For your particular application, only one thing will give you the definitive answer: Profile it.
That being said here are the lessons I've learned while working with large PInvoke solutions.  The most effective way to marshal data is to marshal fields which are blittable.  Meaning the CLR can simple do what amounts to a memcpy to move data between native and managed code.  In simple terms, get all of the non-inline arrays and strings out of your structures.  If they are present in the native structure, represent them with an IntPtr and marshal the values on demand into managed code.
I haven't ever profiled the difference between using Marshal.PtrToStructure vs. having a native API dereference the value.  This is probably something you should invest in should PtrToStructure be revealed as a bottleneck via profiling.
For large hierarchies marshal on demand vs. pulling an entire structure into managed code at a single time.  I've run into this issue the most when dealing with large tree structures.  Marshalling an individual node is very fast if it's blittable and performance wise it works out to only marshal what you need at that moment.

A: In addition to JaredPar's comprehensive answer, you don't need to use GCHandle, you can use unsafe code instead.
fixed(byte *pBuffer = buffer) {
     record = *((CPP_STRUCT_DEF *)pBuffer);
}

The whole purpose of the GCHandle/fixed statement is to pin/fix the particular memory segment, making the memory immovable from GC's point of view. If the memory was movable, any relocation would render your pointers invalid.
Not sure which way is faster though.

A: This may be outside the bounds of your question, but I would be inclined to write a little assembly in Managed C++ that did an fread() or something similarly fast to read in the structs. Once you've got them read in, you can use C# to do everything else you need with them.

A: here's a small class i made a while back while playing with structured files. it was the fastest method i could figure out at the time shy of going unsafe (which was what i was trying to replace and maintain comparable performance.)
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;

namespace PersonalUse.IO {

    public sealed class RecordReader<T> : IDisposable, IEnumerable<T> where T : new() {

        const int DEFAULT_STREAM_BUFFER_SIZE = 2 << 16; // default stream buffer (64k)
        const int DEFAULT_RECORD_BUFFER_SIZE = 100; // default record buffer (100 records)

        readonly long _fileSize; // size of the underlying file
        readonly int _recordSize; // size of the record structure
        byte[] _buffer; // the buffer itself, [record buffer size] * _recordSize
        FileStream _fs;

        T[] _structBuffer;
        GCHandle _h; // handle/pinned pointer to _structBuffer

        int _recordsInBuffer; // how many records are in the buffer
        int _bufferIndex; // the index of the current record in the buffer
        long _recordPosition; // position of the record in the file

        /// <overloads>Initializes a new instance of the <see cref="RecordReader{T}"/> class.</overloads>
        /// <summary>
        /// Initializes a new instance of the <see cref="RecordReader{T}"/> class.
        /// </summary>
        /// <param name="filename">filename to be read</param>
        public RecordReader(string filename) : this(filename, DEFAULT_STREAM_BUFFER_SIZE, DEFAULT_RECORD_BUFFER_SIZE) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="RecordReader{T}"/> class.
        /// </summary>
        /// <param name="filename">filename to be read</param>
        /// <param name="streamBufferSize">buffer size for the underlying <see cref="FileStream"/>, in bytes.</param>
        public RecordReader(string filename, int streamBufferSize) : this(filename, streamBufferSize, DEFAULT_RECORD_BUFFER_SIZE) { }

        /// <summary>
        /// Initializes a new instance of the <see cref="RecordReader{T}"/> class.
        /// </summary>
        /// <param name="filename">filename to be read</param>
        /// <param name="streamBufferSize">buffer size for the underlying <see cref="FileStream"/>, in bytes.</param>
        /// <param name="recordBufferSize">size of record buffer, in records.</param>
        public RecordReader(string filename, int streamBufferSize, int recordBufferSize) {
            _fileSize = new FileInfo(filename).Length;
            _recordSize = Marshal.SizeOf(typeof(T));
            _buffer = new byte[recordBufferSize * _recordSize];
            _fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None, streamBufferSize, FileOptions.SequentialScan);

            _structBuffer = new T[recordBufferSize];
            _h = GCHandle.Alloc(_structBuffer, GCHandleType.Pinned);

            FillBuffer();
        }

        // fill the buffer, reset position
        void FillBuffer() {
            int bytes = _fs.Read(_buffer, 0, _buffer.Length);
            Marshal.Copy(_buffer, 0, _h.AddrOfPinnedObject(), _buffer.Length);
            _recordsInBuffer = bytes / _recordSize;
            _bufferIndex = 0;
        }

        /// <summary>
        /// Read a record
        /// </summary>
        /// <returns>a record of type T</returns>
        public T Read() {
            if(_recordsInBuffer == 0)
                return new T(); //EOF
            if(_bufferIndex < _recordsInBuffer) {
                // update positional info
                _recordPosition++;
                return _structBuffer[_bufferIndex++];
            } else {
                // refill the buffer
                FillBuffer();
                return Read();
            }
        }

        /// <summary>
        /// Advances the record position without reading.
        /// </summary>
        public void Next() {
            if(_recordsInBuffer == 0)
                return; // EOF
            else if(_bufferIndex < _recordsInBuffer) {
                _bufferIndex++;
                _recordPosition++;
            } else {
                FillBuffer();
                Next();
            }
        }

        public long FileSize {
            get { return _fileSize; }
        }

        public long FilePosition {
            get { return _recordSize * _recordPosition; }
        }

        public long RecordSize {
            get { return _recordSize; }
        }

        public long RecordPosition {
            get { return _recordPosition; }
        }

        public bool EOF {
            get { return _recordsInBuffer == 0; }
        }

        public void Close() {
            Dispose(true);
        }

        void Dispose(bool disposing) {
            try {
                if(disposing && _fs != null) {
                    _fs.Close();
                }
            } finally {
                if(_fs != null) {
                    _fs = null;
                    _buffer = null;
                    _recordPosition = 0;
                    _bufferIndex = 0;
                    _recordsInBuffer = 0;
                }
                if(_h.IsAllocated) {
                    _h.Free();
                    _structBuffer = null;
                }
            }
        }

        #region IDisposable Members

        public void Dispose() {
            Dispose(true);
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator() {
            while(_recordsInBuffer != 0) {
                yield return Read();
            }
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        #endregion

    } // end class

} // end namespace

to use:
using(RecordReader<CPP_STRUCT_DEF> reader = new RecordReader<CPP_STRUCT_DEF>(path)) {
    foreach(CPP_STRUCT_DEF record in reader) {
        // do stuff
    }
}

(pretty new here, hope that wasn't too much to post... just pasted in the class, didn't chop out the comments or anything to shorten it.)

A: It seems this has nothing to do with neither C++ nor marshalling. You know the structure what else do you need.
Obviously you need a simple code which will read group of bytes representing one struct and then using BitConverter to place bytes into corresponding C# fields..


text:
Q: Teamcity build trigger exclude all but some I'm using teamcity to perform my builds.
within my repository there are multiple projects that uses different folders. e.g. like this:
└root
  ├project1
  │  └files
  ├project2
  │  └files
  └project3
     └files

I have 3 lanes that should all here just on there own folder.
The current trigger configuration for project2 looks like this:
-:*/project1/*
-:*/project3/*
+:*/project2/*

but I don't want to explicit add all projects to the trigger configuration of every project. therefore I would like to say s.th. like
-:IGNORE_EVERYTHING
+:*/project2/*

which means I just want to list the folder that SHOULD get monitored but not exclude all others. When I just use the last line of the above the two other folders gets monitored as well.
How do I do that?

A: According to documentation Configuring VCS Triggers:

When entering rules, please note that as soon as you enter any "+" rule, TeamCity will remove the default "include all" setting. To include all the files, use "+:." rule.

You don't need any exclusion rule. Just insert:
+:*/project2/*

in Trigger Rules and you should be good.