text:
Q: Function not found in custom module - VueJS I write two functions in a module to use on some sections of an hybrid mobile app. The module name is "functs.js":
module.exports = {
    TRUNCATE_LETTERS (txt,max) {
        const limit = max || 15;
        const text = (txt && txt.trim()) ? txt.trim() : '';
        const dots = '...';
        let resp = '';

        if ( txt.length > limit )
        {
            resp = txt.substring(0, limit) + ' ' + dots;
        } else {
            resp = text + ' ' + dots;
        }

        return resp;
    },

    TRUNCATE_WORDS (txt,max) {
        const limit = max || 10;
        const text = (txt && txt.trim()) ? txt.trim() : '';
        const dots = '...';
        let resp = '';

        const arr = text ? text.split(' ') : [];
        let newArr = [];

        if ( arr.length > limit )
        {
            for ( let i = 0; i < limit; i++ )
            {
                newArr.push( arr[i] );
            }

            resp = newArr.join(' ') + ' ' + dots;
        } else {
            resp = text + ' ' + dots;
        }

        return resp;
    }
}

When I call TRUNCATE_LETTERS and comment TRUNCATE_WORDS all goes fine but on uncomment it I get this error on the CLI:
warning  in ./src/views/Offers.vue?vue&
type=script&lang=js&

"export 'TRUNCATE_LETTERS' was not found
 in '@/components/functs'

I tested the two functions in a separate HTML file and did not receive any errors.
Is there something that I don't saw? I need to truncate for words, not for letters.
Thanks any help.

A: Here is the right syntax:
module.exports = {
  TRUNCATE_LETTERS: function(txt,max) { ... },
  TRUNCATE_WORDS: function(txt,max) { ... }
}

Use :
    const { TRUNCATE_LETTERS, TRUNCATE_WORDS } = require("/path/mymodule");

    or

    const TRUNCATE_LETTERS = require("/path/mymodule").TRUNCATE_LETTERS ;

With export default/import in VueJs :
const truncate = {
  TRUNCATE_LETTERS: function(txt,max) { ... },
  TRUNCATE_WORDS: function(txt,max) { ... }
}

export default truncate;

Use:
  import truncate from "/path/mymodule";
  truncate.TRUNCATE_LETTERS(...);

  or

  import { TRUNCATE_LETTERS, TRUNCATE_WORDS } from "/path/mymodule";


text:
Q: Async generator in Nodejs for recursively fetching promises I am trying to recursively scan a mysql table and process rows in batches.
ids is equivalent to array of rows and promise1 fetch a chunk of rows and promise2 process them. This is what I've implemented so far. This is working as expected. How can I improve it to simplify further?
const ids=[]
for(let i=0;i<50;i++){
    ids.push(i)
}
const promise1=(limit,after=-1)=>new Promise(r=>setTimeout(()=>r(ids.slice(after+1,after+limit+1)),1000))
const promise2=a=>new Promise(r=>setTimeout(()=>r(a.map(b=>b*2)),1000))
async function* promiseGen(){
    let limit=10
    let after=-1
    while(true){
        let pr1=await promise1(limit,after)
        if(pr1.length==0){
            break
        }
        yield pr1
        console.log(pr1)
        after=pr1[pr1.length-1]
    }
}
async function processor(){
    let pr1=promiseGen()
    let result=[]
    while(true){
        let data=await pr1.next()
        if(data.done){
            break
        }
        let res=await promise2(data.value)

        result.push(res)

    }
    return result
}

processor().then(res=>console.log(res))

A: Use a for await … of loop:
async function processor() {
    const result = [];
    for await (const val of promiseGen()) {
        result.push(await promise2(val))
    }
    return result;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to integrate number in to a grid Background:
I have written up some code that creates a grid layout, so that it can be used to practice some Katakana/Hiragana characters.
Question:
How can I add a numbering system across the grids in the x and y direction with relatively small font size?
MWE:
\documentclass[a4paper]{article}
\pagestyle{empty}  % suppress page numbering
\usepackage{geometry}
\geometry{hmargin=1cm,vmargin=1cm}
\usepackage{tikz}
\def\mycolumns{18}
\def\myrows{25}

\begin{document}

\hspace{2cm}
\begin{center}
    \line(1,0){125}
\end{center}
\hspace{1cm}

\begin{tikzpicture}[x=1cm, y=1cm, semitransparent]
\draw[step=5mm, line width=0.2mm, black!40!white] (0,0) grid (\mycolumns,\myrows);
\draw[step=1cm, line width=0.3mm, black!90!white] (0,0) grid (\mycolumns,\myrows);
\end{tikzpicture}

\end{document}

Current Output:

Ideal Output:
The numbering should start from the top left as 1, and should align with the center-line of the boxes

Bonus Points:
If I can define the color of the numbers as "red" it would be awesome!

A: The following adds your numbers. To change the way they appear, you can alter the mynums style (e.g., to change the font size, you could add font=\small to the style).
\documentclass[a4paper]{article}
\pagestyle{empty}  % suppress page numbering
\usepackage{geometry}
\geometry{hmargin=1cm,vmargin=1cm}
\usepackage{tikz}
\def\mycolumns{18}
\def\myrows{25}

\begin{document}

\hspace{2cm}
\begin{center}
    \line(1,0){125}
\end{center}
\hspace{1cm}

\begin{tikzpicture}[x=1cm, y=1cm, semitransparent, mynums/.style={inner sep=0, text=red}]
\draw[step=5mm, line width=0.2mm, black!40!white] (0,0) grid (\mycolumns,\myrows);
\draw[step=1cm, line width=0.3mm, black!90!white] (0,0) grid (\mycolumns,\myrows);
\foreach\x in {1,...,\mycolumns}
  \node[anchor=south, mynums] at (\x-0.5, \myrows+0.25) {\x};
\foreach\x in {1,...,\myrows}
  \node[anchor=east, mynums] at (-0.25, \myrows - \x + 0.5) {\x};
\end{tikzpicture}

\end{document}


text:
Q: Out of two functions, one can access variable's value, the other can't The data fetched from API contains two types of elements: cycles which are objects of few attributes, and last_update object, which contains ID and last_update: <date>.
I'm processing them in the following way:
<script>
  export default {
    data: () => ({
      jsonData: [],
      lastUpdate: '',
      items: [
        {
          action: 'mdi-calendar',
          active: false,
          items: [{ title: '' }],
          title: 'Last Update',
        }
      ]
    }),
    methods: {
      async parseData() {
        const response = await fetch("http://127.0.0.1:5012/api/v3/cycles", {
          headers: {
            "Content-Type": "application/json",
            "mode": "cors"
          }
        })
        let cycles = await response.json();
        if (cycles.length < 1) {
          console.error("Couldn't fetch cycles from DB...")
        }
        const last_update = cycles.filter(cycle => cycle.last_update);
        this.lastUpdate = last_update[0].last_update;
        console.log('Inside parseData:', this.lastUpdate);

        cycles = cycles.map(({source, revision, elements}) => ({source, revision, elements}));
        this.jsonData = cycles
      },
      setLastUpdate() {
        this.items[0].items.title = this.lastUpdate;
        console.log('Inside setLastUpdate:', this.items[0].items.title);
        console.log('Inside setLastUpdate:', this.lastUpdate);
      }
    },
    created() {
      this.parseData();
      this.setLastUpdate();
    }
  }
</script>

Now, the console shows the following outputs:
Inside setLastUpdate: <empty string>
Inside setLastUpdate: <empty string>
Inside parseData: 2023.01.24 08:44:32

The value gets read and updates the lastUpdate in data section. Why it can't be read by the setLastUpdate() function?
I was thinking that there may be something with async setting, so I made setLastUpdate() function async just for testing, but the asynchronous action in parseData() function only refers to fetching the data from API. After the data is there, all processing happens on the same set of data for both reading cycles and last_update.
How to refactor the code so that the lastUpdate is available for setLastUpdate() function and possibly update the data.items object?

A: As per looking at the console statement, function setLastUpdate is calling before the parseData function.
So, to make the lastUpdate property available for setLastUpdate, you need to call those functions asynchronously. You can create a single async function that will call both functions one by one and wait for the first to be executed. For example-
created() {
  this.init();
},

methods: {
  async init() {
    await this.parseData();
    await this.setLastUpdate();
  },
},

One more thing-
instead of-
this.items[0].items.title = this.lastUpdate;

It should be-
this.items[0].items[0].title = this.lastUpdate;

Because inner items is having an array of objects structure.


text:
Q: Set multiple wifi access points in Ubuntu 20.04 I am trying to configure the network in Ubuntu 20.04. I would like to set up several wifi access points under the same interface.
I am using the following configuration right now:
# This file is generated from information provided by the datasource.  Changes
# to it will not persist across an instance reboot.  To disable cloud-init's
# network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
    ethernets:
        eth0:
            dhcp4: true
            addresses: [x.y.z.w/24]
            optional: true
    version: 2
    wifis:
      wlan0:
        dhcp4: false
        gateway4: x.y.z.w
        addresses: [x.y.z.w/24]
        access-points:
          "SSID":
            password: "pass"

But only one access point can be specified. Is it possible to set up a list of wifi networks with corresponding credentials?

A: May be you already found answer for this, still posting, make sure that both HotSpots are 2.4GHz.
Just append bold line to /etc/netplan/50-something.yaml fileL
wifis:
      wlan0:
        dhcp4: false
        gateway4: x.y.z.w
        addresses: [x.y.z.w/24]
        access-points:
          "SSID1":
            password: "pass1"
          "SSID2":
            password: "pass2"

A: The sample code is as follow.
# This file is generated from information provided by the datasource.
# Changes to it will not persist across an instance reboot.  To disable
# cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the
# following: network: {config: disabled}
network:
    ethernets:
        eth0:
            dhcp4: true
            addresses: [x.y.z.w/24]
            optional: true
    version: 2
    wifis:
        wlan0:
            access-points:
                "first-network-ssid":
                    password: 'first-network-password'
            dhcp4: true
            optional: true
        wlan0:
            access-points:
                "second-network-ssid":
                    password: 'second-network-password'
            dhcp4: true

The

first-network-ssid

should be replace with your first network ssid, then the

first-network-password

should be replace with your first network password, so with the

second-network-ssid

second-network-password

If another wifi need to added, add a wlan config as the children node to  wifis.
The header must be wlan0.
Finally update netplan.
To select the wifi, first show the wifi list
sudo wpa_cli -i wlan0 list_networks

it will show you the network_id and network_ssid,
then select by network_id.
 sudo wpa_cli -i wlan0 select_network network_id


text:
Q: Task has long Schedule Delay on Spark UI and it failed because of GC overhead limit exceeded I'm running a Spark application which load 1 million rows of data from a database into 201 partitions and then write as parquet files. The application code may look like:
dataframe = spark.read.format('jdbc').options(...).load()
dataframe_over_range = dataframe.filter("date >= '2017-01-01 00:00:00'")
if dataframe_over_range.head(1):
    for date in dates: # dates was a list of date
        dataframe_daily = dataframe_over_range.filter(f"date >= '{date} 00:00:00'").filter(f"date <= '{date} 23:59:59'")
        dataframe_daily.write.parquet('s3://...', mode='overwrite')

But Spark always ends up with 200 task SUCCESS and 1 task FAILED:

The failed task got an java.lang.OutOfMemoryError: GC overhead limit exceeded in executor, and it had a long Scheduler Delay in Spark UI:

What may be the reason of this problem ?
==========Update==========
As @walking said, I change my code to this format:
from pyspark.sql.functions import date_format
dataframe = spark.read.format('jdbc').options(...).load()
dataframe_over_range = dataframe.filter("date >= '2017-01-01 00:00:00'")
if dataframe_over_range.head(1):
    datafram_over_range.withColumn('partition_date', date_format(tb_config['date_col'], 'yyyy-MM-dd')).write.partitionBy('partition_date').parquet('s3://...')

But the problem was still the same, there's one task failed with long Scheduler Delay. But what makes me curious is that I found all parquet files were actually written to file system. What does Spark do after finish writing ?
==========Update 2==========
I've check the GC log of Spark, and I found the number of FinalReference and WeakReference grows after the failed task start, and also number of promoted grows too. This would lead to Full GC after few minutes, and finally too many Full GC leads to java.lang.OutOfMemoryError: GC overhead limit exceeded

A: I've solved this problem. I'm using the jdbc options lowerBound and upperBound in a wrong way. This two options are only for data partition but not for filtering data from database, you should filter data via using subquery in dbtable option or query option.
For example, I want to load data which id between 0 and 1000000, and seperate into 10 partitions, the wrong way is:
spark.read.format('jdbc').options(
  ...,
  dbtable='my_table',
  partitionColumn='id',
  lowerBound=0,
  upperBound=1000000,
  numPartitions=10
  ...
).load()

This would cause the query of the last partition be like select * from my_table where id >= 900000 which doesn't have upper bound. The right way should be:
spark.read.format('jdbc').options(
  ...,
  dbtable='(select * from my_table where id between 0 and 1000000) t',
  partitionColumn='id',
  lowerBound=0,
  upperBound=1000000,
  numPartitions=10
  ...
).load()


text:
Q: What is the preferred way to read data from kernel space devices into user space processes? I am currently querying my sensors by first opening a file descriptor of the device node, calling read() on it and closing the file descriptor again. For dynamic sensor data I would repeat this procedure endlessly in a loop.
I wonder if there is a more economical way to mirror or symlink data, that already lies in a file-like structure in the device tree instead of creating a copy of this data that is already present in memory.

A: One option would be to create a custom filesystem, and expose your data by mounting that. Perhaps a clean solution is a user-space filesystem, or some userspace-only option like the ancient mtools(1) to read/write FAT filesystems.
In any case, it strongly depends on the use of said data. Unless performance is truly critical, a pure userland solution is probably easiest to build and most flexible/future proof. Futzing around in the kernel's space is guaranteed to leave you high and dry very soon by the furious development rate, unless you manage to get your stuff included in the official kernel, or adhere strictly to only using officially exported interfaces in your modules.


text:
Q: Restore corrupted partition table in emergency mode without fdisk command When I manage a VPS, I used fdisk to adjust partitions. But when I reboot, the server complained that the block count 2780624 exceeds size of device (2441472 blocks) and entered emergency mode.
I have backed up the partition but the emergency mode did not have a fdisk command for restoring partitions.
Currently, I could either enter the emergency terminal or before it enter the grub terminal via VNC. In the emergency mode, available commands include:
/bin commands screenshot, /sbin commands screenshot
It's my first time dealing with such issue, so if you need any further information, I would provide it asap.
Edit:

*

*The system is CentOS 7.

*I have backed up the privious partition. Partition screenshot

*No tools fdisk, gpart, cfdisk, sfdisk available.

*What I concern most is retrieving some important data in the disk.

Edit: I found that the server snapshot can be captured and downloaded. Is it easier to restore data locally?

A: Even using fdisk you will need the partition layout that you had before.
As you did not specify the linux distribution you use, we can only guess: some possibilities are:

*

*gpart

*cfdisk

*sfdisk

There probably exist others I don't know about.
Beside: fdisk usually is in /sbin, so it should be available. Did you check your PATH environment?
And if your VPS provider does not offer a rescue environment with proper tools, you should consider changing the provider ...

A: Based on the information posted, I can't make up a way forward, in case your problem is really the partition table.
You could bring up network (ip an dhclient are there) but there is no tool to get something from the web or another server.
Still I doubt that fdisk shown on your screenshot is what is saved, as the blocks indicate that sda2 should be within the disk limits (except you shrunk your disk somehow). In order to dig deeper on that it would be helpful to see the dmesg & mount output. Typically / is mounted during initrd stage on /sysroot when CentOS is booting, and with chroot inside the initrd it is often possible to use utilities in the root disk for recovery purposes.
Still this way forward, would require beeing able to mount the root partition.
As long as the partition start sectors in the partition table are correct it could be possible.

A: If it is really important to recover that data, a way forward could also be to use vi as hex editor and fix the partition table with it. This will not be easy, and requires to (fully) understand the binary format of the MBR & its partition table section.


text:
Q: Populate UITableView with youtube thumbnail I have an app that has a video section, the idea is to have a tableview that will display a youtube thumbnail and infos about the video on each row. I know how to get the videos on a regular view with UIWebView but how can i have that on a cell?

A: Use the gdata-objective-c client. It supports the YouTube data API so you can get thumbnail and other info about a video using this library.


text:
Q: how to implement own error function while using neuralnet package in R? I am trying to implement a customized error function in package neuralnet in R.
Normally 'sse' and 'ce' which stand for the sum of squared errors and the cross-entropy are used to calculate error.Can anyone provide me details about how to implement own error function. Though the package says we can use customized error function,there is no help in the user Manuel about this.

A: I had the same Problem. This is the solution/help I received.
You can use the usual definition of R functions (function(x,y){...}). Hence, the error function must be of the type function(x,y) where x is the fitted value and y is the true value.
Please refer to the following example.
library(neuralnet)

AND <- c(rep(0,7),1)
OR <- c(0,rep(1,7))
binary.data <- data.frame(expand.grid(c(0,1), c(0,1), c(0,1)), AND, OR)
set.seed(3)
print(net <- neuralnet(AND+OR~Var1+Var2+Var3,  binary.data, hidden=0, rep=10, err.fct="sse", linear.output=FALSE))

#Call: neuralnet(formula = AND + OR ~ Var1 + Var2 + Var3, data = binary.data,     hidden = 0, rep = 10, err.fct = "sse", linear.output = FALSE)
#
#10 repetitions were calculated.
#
#Error Reached Threshold Steps
#7  0.04043122185    0.008248439644   116
#5  0.04426319054    0.009619409680   124
#8  0.04698485282    0.007947430014   117
#2  0.04931335384    0.008792873261    88
#1  0.04965332555    0.009631079320    89
#4  0.05396400022    0.009092193542    96
#6  0.05488395412    0.009990028287   124
#3  0.06383087672    0.009964206587    94
#10 0.51657348285    0.008602371325    51
#9  0.52514202592    0.007890927099    40

set.seed(3)
custom <- function(x,y){1/2*(y-x)^2}
print(net <- neuralnet(AND+OR~Var1+Var2+Var3,  binary.data, hidden=0, rep=10, linear.output=FALSE, err.fct=custom))

#Call: neuralnet(formula = AND + OR ~ Var1 + Var2 + Var3, data = binary.data,     hidden = 0, rep = 10, err.fct = custom, linear.output = FALSE)
#
#10 repetitions were calculated.
#
#Error Reached Threshold Steps
#7  0.04043122185    0.008248439644   116
#5  0.04426319054    0.009619409680   124
#8  0.04698485282    0.007947430014   117
#2  0.04931335384    0.008792873261    88
#1  0.04965332555    0.009631079320    89
#4  0.05396400022    0.009092193542    96
#6  0.05488395412    0.009990028287   124
#3  0.06383087672    0.009964206587    94
#10 0.51657348285    0.008602371325    51
#9  0.52514202592    0.007890927099    40

You can use basically every error function that can be differentiated.


text:
Q: Using "as" or "than" in comparison constructions
1- It turns out that someone in the high risk group has twice the risk
  as those in the low risk group
2- It turns out that someone in the high risk group has twice the risk
  than those in the low risk group

Do these two sentences mean the same thing?

A: I agree with the above answer. I am also English and to me 'twice the risk as' seems grammatically correct to me.
In the case of using 'than', this is used when we want to measure something along a scale. You could rephrase the sentence and say 'It turns out that someone in the high risk group has a risk two times higher than those of the lower risk group'.
You can also use 'of': a risk twice the size of those in the lower risk group.

A: Possibly UK and US English speakers will have different opinions about this - I'm from the UK. This discussion of  "different from" and "different than" usages might be interesting, if not directly relevant to your question.
Twice is a numeric comparator, we say
twice as many

not
twice than many

So I prefer
It turns out that someone in the high risk group has twice the risk as those in the low risk group

using "than" feels completely wrong to me. However I'm not quite comfortable with that phrasing. My first problem is that someone is singular and those is plural. Secondly, and this may well just be my preference, we have a has in the first clause, so I feel that we need a verb in the second.
It turns out that someone in the high risk group has twice the risk as does someone in the low risk group


text:
Q: Compute $\lim_{x\rightarrow0}\frac{e^{x^2} - \cos x}{\sin^2 x}$ Find the limit as $x$ approaches $0$ of
$\dfrac{e^{x^2} - \cos x}{\sin^2 x}$
What I tried is as $x$ approaches $0$, $e^{x^2}$ tends to $1$ and so the numerator tends to $1-\cos x$ and after doing some trigonometric simplifications I got the answer as $\frac 12$.
Is this right? Any help would be appreciated.

A: Using l'Hospital:
$$\lim_{x\to 0}\frac{e^{x^2}-\cos x}{\sin^2 x}\stackrel{\text{l'H}}=\lim_{x\to 0}\frac{2xe^{x^2}+\sin x}{2\sin x\cos x}\stackrel{\text{l'H}}=\lim_{x\to 0}\frac{2e^{x^2}+4x^2e^{x^2}+\cos x}{2\cos^2x-2\sin^2x}=\frac{2+0+1}{2}=\frac32$$

A: HINT:
$$\frac{e^{x^2}-\cos x}{\sin^2x}=\cdots=\frac{\dfrac{e^{x^2}-1}{x^2}}{\left(\dfrac{\sin x}x\right)^2}+\frac{1-\cos x}{1-\cos^2x}$$
Use $\lim_{h\to0}\dfrac{e^h-1}h=1=\lim_{u\to0}\dfrac{\sin u}u$ for the first part
and as $x\to0,\cos x\to1\implies\cos x-1\ne0$ for the second

A: Use Taylor expansion. As $x\rightarrow0$, you have
$$e^{x^2}=1+x^2+O(x^4)$$
$$\cos x=1-\frac12x^2+O(x^4)$$
$$\sin^2x=x^2+O(x^4)$$
Thus
$$\frac{e^{x^2}-\cos x}{\sin^2 x}=\frac{1+x^2-1+\frac12x^2+O(x^4)}{x^2+O(x^4)}=\frac{\frac32+O(x^2)}{1+O(x^2)}\underset{x\rightarrow 0}{\longrightarrow} \frac32$$

A: As Jean-Claude Arbaut showed, Taylor expansions are extremely useful for this kind of problems.
But, using them with a few more terms, you also see how is the limit approached $$A=\frac{e^{x^2}-\cos x}{\sin^2 x}=\frac{\Big(1+x^2+\frac{x^4}{2}+O\left(x^6\right)\Big)-\Big(1-\frac{x^2}{2}+\frac{x^4}{24}+O\left(x^6\right)\Big)}{x^2-\frac{x^4}{3}+O\left(x^6\right)}$$ $$A\approx\frac{\frac{3 x^2}{2}+\frac{11 x^4}{24}+O\left(x^6\right)}{x^2-\frac{x^4}{3}+O\left(x^6\right)}=\frac{\frac{3 }{2}+\frac{11 x^2}{24}}{1-\frac{x^2}{3}}$$ Performing the long division, we have $$A\approx \frac{3}{2}+\frac{23 }{24}x^2$$ If you plot on the same graph the function and the above approximation, you will probably be amazed to see how close to each other are the two curves for $-\frac 12\leq x \leq \frac 12$.

A: You can use Taylor series as

$$\dfrac{e^{x^2} - \cos x}{\sin^2 x} \sim_{x\sim 0}  \dfrac{(1+x^2) - (1-x^2/2)}{x^2} =\frac{3}{2}. $$


text:
Q: VMware ESX Linux Guest Customization I am interested in deploying several RHEL 4 Update 8 virtual machines for creation of a test environment.
Here are the steps I am taking:

*

*In off hours, P2V/V2V the production machines and convert them to templates

*Deploy the virtual machines with a customization specification that changes hostname, IP address

I am interested in how these processes are done and if there are any options for further customization.

*

*Are the machines brought on the network when they are powered on, before they are reconfigured? Is there a potential IP address conflict?

*Is there an option to run additional scripts which reside on the guest as a part of the reconfiguration? For example, restoring an Oracle Database. This is an option with Windows guests and sysprep, but I have been unable to locate anything showing a RHEL equivalent.
I am dealing with a multi tier application. The main issue I am attempting to mitigate is that the application servers reference database servers by hostname and in tnsnames files. I am interested in scripting the reconfiguration of the application in the deployment so that the app/db servers are pointing to the test environment.
I am OK with placing the 'cleanup' script on the source and executing it after the machine has been brought up. I am interested in the automation of the script's execution post clone/boot, as well as if there could be an IP address conflict.
(cross posted to VMTN's ESX 4 community)

A: My experience is mostly with Windows, but the process is pretty much the same:

Are the machines brought on the
  network when they are powered on,
  before they are reconfigured?

The machines are powered on, and the setup scripts to change the configuration are run before the network and rest of the system is brought online. The machine then reboots if required, and the 2nd time around it boots fully, with the new configuration.

Is there
  a potential IP address conflict?

Regarding the network and duplicate IP addresses, you should be safe, however if you're really concerned, create a 2nd network and don't bind any NICs to it. After the customisation wizard you can choose not to boot the machine immediately. If you make sure it doesn't boot, you then have the option of changing the network the VM is attached to to the dummy network. After you've booted it up and the configuration script has run, double-check the IP settings of the network to make sure they're not conflicting (you'll have to do the check manually, of course) and then just flick the network over to the live network.

Is there an option to run additional
  scripts which reside on the guest as a
  part of the reconfiguration?

Can't help with this one I'm afraid.


text:
Q: basil.js scripts taking minutes to run I'm trying to create an InDesign script using basil.js but the scripts take minutes before running. InDesign just freezes in the meanwhile. Other JS samples (not using basil) work fine. I'm using InDesign 2021 and the MacOS Big Sur 11.2. Could that be it? I'm afraid, for me, the solution cannot be downgrading. Any other thoughts?
Thanks a lot, Daniel
#includepath
"Users/danifslopes/Documents";
#include
"basiljs/bundle/basil.js";

function draw() {
    b.doc(); //with or without, the same result (I have a page opened)
    b.text("hello", 100, 100, 200, 200);
}

b.go();

A: I followed the instructions in github.com/trych/MuTypo to use the new version of basil and it seems to work great. Also, this version seems to be much simpler and practical to use.
Thanks a lot, mdomino and fabianmoronzirfas.


text:
Q: why does UINT_MAX + 3 always equal 2? Can someone help me, I've written a small C program to output the value of UINT_MAX + 3, and tested it on both a mac, and ubuntu, and it keeps giving me 2
Thank you

A: It is the way it is defined in th C standard. Unsigned integers have modular arithmetic. Incrementing the largest unsigned integer of any type by 1 results in 0. Incrementing by 2 yields 1. And so on.
By the same token, subtracting 1 from 0 gives you the largest value of that unsigned integer type.

A: If you actually want to add 3 to UINT_MAX and obtain a larger value, then you need to use a larger integer type than the type for which UINT_MAX is defined for your compiler.  Unfortunately, the way that you do that depends on your compiler.  For example using Visual C++ on Windows, an int is 32 bits, so UINT_MAX is 4,294,967,295.  In Visual C++, you specify a 64-bit integer using the type __int64, so writing:
unsigned __int64 n;
n=(unsigned __int64)UINT_MAX+3;
printf("%I64i\n",n);

...will print the desired value, 4,294,967,298.


text:
Q: Issue connecting GoogleApiClient in multiple activities I was, for the first time, trying to implement a google play services leader board but have some issue.
I have the show leaderboard button in the main activity, so I initialize an GoogleApiClient in MainActivity, all good so far - google connects, and a blank leaderboard.
The score that actually fills the leaderboard is obtained from second activity, the GameActivity.
I create yet another instance of GoogleApiClient and try connecting it.
But.. it always fails, even after calling apiClient.connect()
Am I doing something wrong? Is only 1 client allowed throughout the program?
I use this code in both of the activities to initialize:
apiClient = new GoogleApiClient.Builder(this)
            .addApi(Games.API)
            .addScope(Games.SCOPE_GAMES)
            .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                    Toast.makeText(LevelSelector.this, "Failed to connect to google play", Toast.LENGTH_LONG).show();
                }
            })
            .build();

I call leaderboard from the main activity
    leaderboardTextView = (TextView) findViewById(R.id.leaderboard_button);
    leaderboardTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivityForResult(
                    Games.Leaderboards.getLeaderboardIntent(apiClient,
                            getString(R.string.leaderboard_most_stars)), 0);
        }
    });

And the score is submitted to leaderboard from a different activity
private void updateScore(){
    if(!apiClient.isConnected()){
        apiClient.connect();
    }
    //Always returns false.
    if(apiClient.isConnected()) {
        Games.Leaderboards.submitScore(apiClient,
                getString(R.string.leaderboard_most_stars),
                totalStars);
    }
}

A: Only one API client is allowed in an app. Make your apiClient public static and access it from any class using MainActivity.apiClient


text:
Q: Python Code to Detect Greetings and Acknownledgments I am currently coding a program using NLP in Python to analyze the sentiment of a quarterly earnings call by public companies. I calculate the sentiment based on a dictionary approach, meaning that I count the number of positive/ negative words in the call and put that into relation to the total number of words to calculate a sentiment score for each call.
In the Q&A part of the call, some analysts from banks ask questions to the management team of the company.
And usually before asking the analysts say something like "Good Morning." and after they got the answer from the management team they say something like "Perfect, thank you." or "Great, thank you."
But the dictionary approach does count these words like "Good" or "Great" as positive, but they do not belong to the content of the call.
So my goal is to have a program/ algorithm that detects these kinds of non-relevant answers, so that I can remove them from the text. But I have never done something in this kind of direction. So, I don't know at all on how to approach this problem and I also could not find anything like this here on Stackoverflow nor somewhere else.
I was thinking about taking maybe 50 of these kind of sentences that I want to delete and label them with 1, and take 50 sentences that actually contain content and then label them as 0 and train an algorithm to differentiate these two types, but I have no idea how to implement something like this in Python?
Does anybody have an idea? That would be much appreciated!


text:
Q: is there a way to code a product recommendation system on RStudio using svm or knn? (Without using recommenderlab) I want to code a product recommendation system on RStudio, using KNN or SVM. But i dont wanna use recommenderlab.
Is there an easy way to code it? I have variables such as name, gender, price, product type, product brand etc etc.
I tried running SVM and KNN. I got the confusion matrixes with the product type.
But i don't know how to get a list of recommended products for a particular user.


text:
Q: how to deal with 3-byte addresses in shellcode I'm following the directions in the this tutorial:
http://technicalanarchy.blogspot.com/2013/06/stack-based-buffer-overflow-tutorial_20.html
When I get to the "p system"
part, I can get an address, but it's a 3-byte address 0xffffff.  The tutorial shows 4-byte addresses, and the resultant shellcode requires 4-byte.
Now I've added the \x90 nop code to the end of that 3-byte address in my shellcode and at the beginning but neither helped.
OS is 32 bit Centos 6ish

A: You can use the address you got. If you found 0x123456, use \x00\x12\x34\x56.


text:
Q: Align Contact Info in HTML CSS this is what I neet to build: Mockup
At the moment I stuck at sidebar. I need to align the contact info of the phone numbers so that they are aligned vertically.
Here you see what I have right know, the text is not aligned in one height with the phone numbers: Site Link
CSS:
@charset "utf-8";
/* CSS Document */

body { background: #1c1b17 url(bg.jpg) repeat-x; margin: 0; padding: 0; height: 1800px;         font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px;}

p {
color: #22222b;
line-height: 16px;
padding: 0;
font-size: 12px;
font-weight: 600;
}

#wrapper { width: 1000px; margin: 0 auto; }
#header { height: 400px; width: 1000px; display: block; position: relative; }
#header .logo { position: absolute; width: 374px; height: 221px; display: block; float:     left; cursor: pointer; background: url(logo.png) 0 0 no-repeat transparent; top: 55px;     left: 10px; }
#header .contact-info { position: absolute; width: 293px; height: 133px; display:     block; float: left; cursor: pointer; background: url(contact-info.png) 0 0 no-repeat     transparent; top: 100px; left: 700px; }

ul.mn { position: absolute; float: left; top: 316px; width: 978px; margin: 0; padding:     0; list-style-type: none; }
ul.mn li { float: left; }
ul.mn li a { display: block; float: left; height: 73px; }
ul.mn li a.mn1 { width: 104px; background-image: url('mn1.png'); background-position: 0     0; }
ul.mn li a.mn2 { width: 212px; background-image: url('mn2.png'); }
ul.mn li a.mn3 { width: 142px; background-image: url('mn3.png'); }
ul.mn li a.mn4 { width: 128px; background-image: url('mn4.png'); }
ul.mn li a.mn5 { width: 117px; background-image: url('mn5.png'); }
ul.mn li a.mn6 { width: 147px; background-image: url('mn6.png'); }
ul.mn li a.active, ul.mn li a:hover { background-position: 0 73px; }

#content { height: 1100px; width: 1000px; display: block; position: relative; }

#top { height: 300px; width: 1000px; display: block; position: relative; margin-bottom:     100px;}
#top .foto1 { width: 452px; height: 339px; float: left; margin-top: 30px; }
#top .foto2 { width: 253px; height: 338px; float: left; margin-top: 30px; margin-left:     100px; }

#leftcolumn { height: 200px; width: 300px; display: block; position: relative; }
#leftcolumn .text { height: 10px; width: 300px; display: block; position: relative;     margin-bottom: 200px; }
#leftcolumn .text2 { height: 10px; width: 50px; display: block; position: relative; }
#leftcolumn .text3 { height: 10px; width: 130px; display: block; position: relative;      padding-left: 80px; }
#leftcolumn .face { height: 300px; width: 300px; display: block; position: relative; }

#rightcolumn

#footer

HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>RW-Fliesen</title>
    <link rel="stylesheet" type="text/css" href="style.css" />

RW-Fliesen

Ludwig-Thoma-Str. 36

82008 Unterhaching

Telefon:

Fax:

Mobil:

089 - 358 557 88

089 - 358 557 89

0179 - 673 77 41

                    <iframe id="f580fdad4" name="f83387924" scrolling="no" style="border: none; overflow: hidden; height: 690px;     width: 262px;" class="fb_ltr" src="http://www.facebook.com/plugins/likebox.php?api_key=&locale=de_DE&sdk=joey&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter.php%3Fversion%3D18%23cb%3Dfe1e61258%26origin%3Dhttp%253A%252F%252Fwww.rw-fliesen.com%252Ff21318bbdc%26domain%3Dwww.rw-    fliesen.com%26relation%3Dparent.parent&height=290&header=true&show_faces=true&stream=false&width=262&href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FRW-Fliesen%2F115860578491339&colorscheme=light">

How can we solve it?

A: use display: inline-block; with text2 and text3 class.
#leftcolumn .text2 {
height: 10px;
width: 50px;
display: inline-block;
position: relative;
}

#leftcolumn .text3 {
height: 10px;
width: 130px;
display: inline-block;
position: relative;
padding-left: 80px;
}

A: On #leftcolumn .text3 add this style rule:
top:-22px;

A: You could revise that block HTML like this:

Telefon 089 - 358 557 88

Fax 089 - 358 557 88

Mobil 0179 - 673 77 41

A: Fix your display css by changing display:block to display:inline-block. This should solve your issue.


text:
Q: Azure Performance - Ping Test - Inconsistent values between Availability and Performance In Azure you can create simple ping test of your app. It's call ping but it is Get request of a url.
By default, the url is your root url.
The thing is the responses times of thes results are in the range of 2 to 10ms. However, I can never reach these response times nor with Fiddler or Postman. My range is more 100 to 400ms. And I'm closer to the datacenter than the computers running the ping tests in Azure.
It is a bit as if the ping tests where not downloading the content page.
Does anyone know?
UPDATE
I have setup my ping test in the Availability section. The responses times I mention above appear in the Performance section. Back in the Availability section, average response time is 1,6 sec. These two sections show inconsistent values.

A: UPDATED ANSWER:
The Performance section lists how long it took from your server receiving the request to sending something back to the client, it doesn't count network latency at all.

I believe they only check the response status without downloading the content if you don't require a content match.
Below is an example of the configuration for my blog.
If you wish, you can make sure the test downloads the content by ticking the Content match checkbox, and specifying that the content must contain the text that is somewhere near the end of your index page (like in a footer).


text:
Q: Mute Button C# Metro App I'm using Visual Studio 2013 and have almost created an Windows 8.1 Metro application, but I can't seem to find a way to make a button that mutes sound of the app.
I tried several ways to do this but nothing worked.
Thanks in Advance :)

A: Perhaps just use a button that sets each individual soundfile to 0 volume? I know I can set the volume of a wav file in WP8; haven't tried Windows 8.


text:
Q: GTIN can not be converted to system string I retrieve some foods from the usda api and want te list them in a listview, it retrieves the products fine, also lists them but the listitems are empty and in the console there is shown:
[0:] Binding: Sunshine Cheez-It Crackers Original 3oz, UNPREPARED, GTIN: 00024100219131 can not be converted to type 'System.String'
[0:] Binding: Sunshine Cheez-It Crackers Hot & Spicy 7oz, UNPREPARED, GTIN: 00024100705849 can not be converted to type 'System.String

problem: listitems are empty and i don't know what the problem is with my string conversion.
good to know: for this project i imported newtonsoftJSON and system.http
xaml.cs:
public partial class MainPage : ContentPage
    {
        public int start = 0;
        public MainPage()
        {
            InitializeComponent();
            LoadFood(start);
        }
        private async void LoadFood(int start)
        {
            lvwFoods.ItemsSource = await VoedselManager.GetFoodListAsync(start, start + 10);
        }

        private async void btnLoad_Clicked(object sender, EventArgs e)
        {
            start += 10;
            lvwFoods.ItemsSource = await VoedselManager.GetFoodListAsync(start, start + 10);
        }
    }
    public class Voedsel
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        public override string ToString()
        {
            return Name;
        }

    }
    public class VoedselManager
    {
        public static async Task<List<Voedsel>> GetFoodListAsync(int offset, int number)
        {
            try
            {
                String apikey = "";
                String url = string.Format("https://api.nal.usda.gov/ndb/list?format=json&lt=f&sort=id&api_key={0}&offset={1}&max={2}", apikey, offset, number);

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");

                String result = await client.GetStringAsync(url);
                JObject fullObject = JsonConvert.DeserializeObject<JObject>(result);
                JToken data = fullObject.SelectToken("list.item");

                return data.ToObject<List<Voedsel>>();
            }
            catch (Exception ex)
            { throw ex; }
        }

    }

xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:VoedselDemo"
             x:Class="VoedselDemo.MainPage">

    <StackLayout Margin="16">
        <Label Text="Choose a food" FontSize="Large" TextColor="Gray" />
        <!-- lijst van voedingsmiddelen (naam) -->
        <ListView x:Name="lvwFoods" ItemSelected="lvwFoods_ItemSelected" VerticalOptions="FillAndExpand" />
        <!-- knop die bij elke klik een aantal records extra toevoegt aan lvwFoods -->
        <Button x:Name="btnLoad" Clicked="btnLoad_Clicked" Text="load more..." />
    </StackLayout>
</ContentPage>


text:
Q: call awakeFromNib from another controller I have class TableViewCell1: UITableViewCell with the following code:
override func awakeFromNib() {
        super.awakeFromNib()

            if (gender[0] == true){
                let origImage = UIImage(named: "maleP");
                let tintedImage = origImage?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
                genderButton[0].setImage(tintedImage, forState: .Normal)
                genderButton[0].tintColor = UIColor(hex: "d8006c")
            }
            else{
                let origImage = UIImage(named: "maleP");
                let tintedImage = origImage?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
                genderButton[0].setImage(tintedImage, forState: .Normal)
                genderButton[0].tintColor = UIColor(hex: "333333")

        }
        if (gender[1] == true){
            let origImage = UIImage(named: "femaleP");
            let tintedImage = origImage?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
            genderButton[1].setImage(tintedImage, forState: .Normal)
            genderButton[1].tintColor = UIColor(hex: "d8006c")
        }
        else{
            let origImage = UIImage(named: "femaleP");
            let tintedImage = origImage?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
            genderButton[1].setImage(tintedImage, forState: .Normal)
            genderButton[1].tintColor = UIColor(hex: "333333")

        }
    }

and I got left view controller, which have tableview controller, the problem is that I want clear the value inside the cell, to back what was before like reload it ..
 @IBAction func clearSelection(sender: AnyObject) {
         staticlink = ""
         attribute1 = [String]()
         values1 = [String]()

         gender = [false,false]
         seasons = [false,false,false,false]

        clickedsection = 10

         cliedkarry = [false,false,false,false,false,false,false,false]

      tableView.reloadData()
}

how I can apply my inaction to the tableview cell or all the tableview !?
I tried tableView.reloadData() but it didn't work, I guess because I register nibs in this way
tableData = [
    ["title": "Gender", "height": "120", "cellID": "cell1"]]

tableView.registerNib(UINib(nibName: "TableViewCell1", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "cell1")

this is my cellForRowAtIndexPath:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let record = tableData[indexPath.section];
    let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(record["cellID"] as! String)!
    cell.hidden = !(CBool(expandSections[indexPath.section] as! NSNumber))
    return cell
}

so how I can reload the data inside tableview cell

A:
I want clear the value inside the cell, to back what was before like reload it

Okay you have that chance inside prepareForReuse method. It's called each time the cell will be re-cycled.
However what seems wrong with your code is that you are making some checks that obviously need to stay in the controller instead of cell's awakeFromNib. Simply use cellForRowAtIndexPath and provide data to the cell and update it's UI over there. awakeFromNib will be called only once.

A: Yes,you register nibs so tableView can reuse the cells which leads to "awakeFromNib" is not always called.You should update UI stuff elsewhere. And you should never call "awakeFromNib" manually.
In your tableViewCell
func updateUI() {
    //do the UI stuff
}

In your controller
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let record = tableData[indexPath.section];
    let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(record["cellID"] as! String)!
    cell.hidden = !(CBool(expandSections[indexPath.section] as! NSNumber))
    if(!cell.hidden) cell.updateUI()
    return cell
}


text:
Q: Why is Log4J (jul) attempting to MessageFormat a String message from Supplier Using Java 1.8 and the Log4J 2.4 JUL adapter (log4j-jul-2.4.jar, log4j-core-2.4.jar, log4j-api-2.4.jar)
public class SimpleTest {

  public static void main(String[] args) throws Exception {

    // writing the configuration file on the fly
    try (java.io.PrintStream p = new java.io.PrintStream("./log4j-jul-test.xml")) {
      p.println("<Configuration>");
      p.println("  <Appenders>");
      p.println("    <Console name='Console' target='SYSTEM_OUT'>");
      p.println("      <PatternLayout pattern='JUL: %d %t %-5level %m%n' />");
      p.println("    </Console>");
      p.println("  </Appenders>");
      p.println("  <Loggers>");
      p.println("    <Root level='debug'>");
      p.println("      <AppenderRef ref='Console' />");
      p.println("    </Root>");
      p.println("  </Loggers>");
      p.println("</Configuration>");
    }
    System.setProperty("log4j.configurationFile", "log4j-jul-test.xml");

    // specifying the java.util.logging.LogManager implementation
    // COMMENT THE LINE BELOW TO SEE HOW THE STANDARD JAVA LOGGER REACTS
    System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");

    // getting the plain Java logger
    java.util.logging.Logger logger = java.util.logging.Logger.getLogger("test");

    // works with both standard and JUL loggers
    logger.info(() -> "This 1st line will be logged");

    // works only with standard Java logger. JUL is attempting to MessageFormat it but shouldn't
    logger.info(() -> "This 2nd line will {NOT} be logged by JUL");
    // JUL will report that An exception occurred processing Appender Console
    // java.lang.IllegalArgumentException: can't parse argument number: NOT
    //     at java.text.MessageFormat.makeFormat(MessageFormat.java:1429)
    //     at java.text.MessageFormat.applyPattern(MessageFormat.java:479)

    // works with both standard and JUL logger
    logger.log(java.util.logging.Level.INFO, "This 3rd line will {0} be logged", "successfully");
  }
}

The code above is very simple and can be run quickly. Give it a try!
Does anyone know why the Log4J JUL is attempting to MessageFormat the String supplied when it clearly shouldn't since the standard Java logger doesn't? (and there's now way to pass any parameters anyway)
Note that the method signature is:
java.util.logging.Logger.info(Supplier<String>)

A: The Javadoc for java.util.logging.Logger says

Most of the logger output methods take a "msg" argument. This msg argument may be either a raw value or a localization key. During formatting, if the logger has (or inherits) a localization ResourceBundle and if the ResourceBundle has a mapping for the msg string, then the msg string is replaced by the localized value. Otherwise the original msg string is used. Typically, formatters use java.text.MessageFormat style formatting to format parameters, so for example a format string "{0} {1}" would format two parameters as strings.

Because of this Log4j anticipates that code written for jul expects this and so converts the supplied String to a MessageFormatMessage. However, in looking at the Formatters supplied by the JDK, none of them actually seem to support MessageFormat formatting. This would be worth discussing on the Log4j users list.


text:
Q: Split array in C# How to split an array of string type equally into several array.eg.string[] input={"a","b","c","","d","e","f"} dynamically set{ string[] output="a","b","c",""//first time
string[] output="d","e","f",""//second timetime }

A: String[] splitString(int len, string input)
{
  int idx = 0;
  List<string> ret = new List<string>();
  while(idx < input.Length)
  {
    if (idx+len > input.Length)
      ret.Add(input.Substring(idx));
    else
      ret.Add(input.Substring(idx,len));
    idx+=len;
  }
  return ret.ToArray();
}

A: Some time ago I implemented the Enumerable#each_slice from Ruby in C# and it seems you could use that to get what you want.
static class ExtentionsMethods
{
    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> seq, int size)
    {
        while (seq.Any())
        {
            yield return seq.Take(size);
            seq = seq.Skip(size);
        }
    }
}

Then you just
var str = "1234567890";
var res = str.Split(5);

but since the result is an IEnumerable of IEnumerable<char> you might want to also
var arr = res.Select(c => String.Join("", c)).ToArray();

to get a

arr {string[2]}
      [0]: "12345"
      [1]: "67890"


text:
Q: Abstract the same method parameters which are called everytime I have one method that helps responding to requests. Its signature is as follows:
function render(req, res, data, kind, route)
It is being called dozens of times with different parameters. I would like to have a cleaner code where I would call
render(data, kind, route) knowing that req and res are always there in the context when calling.
As the following
router.get('/', async function (req, res, next) {
   // some logic
   // render({}, 'kind', 'route') instead of
   render(req, res, {}, 'kind', 'route')

A: Following @deceze advice. I ended up using a middleware that is attaching a closure as the following
const makeRenderer = (req, res, next) => {
  res.locals.renderer = (data, kind, route) => renderer(req, res, data, kind, route)
  next()
}

router.get('/', makeRenderer, async function (req, res, next) {
  const listings = await mongoQueries.getDocumentsSince(
    20, '', req.body.pagination)
  const { page, perPage } = req.body.pagination
  const data = {
    listings: listings.documents,
    addressPoints: [],
    current: page,
    pages: Math.ceil(listings.count / perPage)
  }
  res.locals.renderer(data, 'listings', 'listings')
})


text:
Q: Is there an option to do a bulk/automated data backfill in big query? I'm using "super metrics for big query" for pulling my account(s) performance which would use, super metrics for the data fetch and google big query for storing the data.
The challenge is that, I would have to do a data backfill for the last 3 years for 100+ accounts. Is there a way to automate the process for all the accounts? Or can we send a backfill request for 180days/6months for multiple accounts simultaneously?
Note: BigQuery supports a maximum of 180 days per backfill request.


text:
Q: Recenter plot after set_xdata and set_ydata I can use the set_xdata and set_ydata functions to update an existing matplotlib plot. But after updating I want to recenter the plot so that all the points fall into the "view" of the plot.
In the below example, the y data keeps getting bigger but the zoom level of the plot remains same so the data points quickly get out of the scope.
import time

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.ion()

figure, ax = plt.subplots(figsize=(10, 8))
(line1,) = ax.plot(x, y)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")

for i in range(1000):
    new_y = np.sin(x - 0.5 * i) * i
    line1.set_xdata(x)
    line1.set_ydata(new_y)
    figure.canvas.draw()
    figure.canvas.flush_events()
    time.sleep(0.1)

A: Adding ax.relim() and ax.autoscale() fixes the issue
import time

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.ion()

ax: plt.Axes
figure, ax = plt.subplots(figsize=(10, 8))
(line1,) = ax.plot(x, y)
ax.autoscale(True)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")

for i in range(1000):
    new_y = np.sin(x - 0.5 * i) * i
    line1.set_xdata(x)
    line1.set_ydata(new_y)

    # Rescale axes limits
    ax.relim()
    ax.autoscale()

    figure.canvas.draw()
    figure.canvas.flush_events()
    time.sleep(0.1)

A: np.sin(x - 0.5 * i) has multiplied by i, which can be 1000. One alternative is to make the y-axis have a limit greater than 1000. So, you can include plt.ylim([-1100,1100]):
import time
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.ion()

figure, ax = plt.subplots(figsize=(10, 8))
(line1,) = ax.plot(x, y)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.ylim([-1100,1100])

for i in range(1000):
    new_y = np.sin(x - 0.5 * i) * i
    line1.set_xdata(x)
    line1.set_ydata(new_y)
    figure.canvas.draw()
    figure.canvas.flush_events()
    time.sleep(0.1)


text:
Q: Calculate Date But Result (return) Still Nan This is my HTML
<input type="text" class="dateofbirthpicker">
<input type="text" id="usia">

Script
$(function() {
    $('.dateofbirthpicker').datepicker({
        dateFormat: 'yyyy/mm/dd'
    });
});

window.onload=function() {
    $('.dateofbirthpicker').on('change', function() {
        var dob = new Date(this.value);
        var today = new Date();

        var age = Math.floor((today-dob) / (1000 * 60 * 60 * 24 * 360));
        ages = parseInt(age);
        $('#usia').val(ages);
    });
}

I have the above script to calculated age from date. It is returning age in Firefox but returns NaN in Chrome.
I was doing this Jquery Date.parse returning NaN in Chrome browser?
Result was invalid date when i ran the following...
var dob = new Date(this.value);

A: Change your dateformat as dateFormat: 'yy/mm/dd'
From specs,

*

*y - year (two digit)

*yy - year (four digit)

$(function() {
  $('.dateofbirthpicker').datepicker({
    dateFormat: 'yy/mm/dd',
    onSelect: function() {
      var dob = new Date(this.value);
      var today = new Date();
      var age = Math.floor((today - dob) / (1000 * 60 * 60 * 24 * 360));
      ages = parseInt(age);
      $('#usia').val(ages);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js"></script>
<link href="http://code.jquery.com/ui/1.8.21/themes/base/jquery-ui.css" rel="stylesheet" />
<input type="text" class="dateofbirthpicker">
<input type="text" id="usia">

JSFiddle Demo

A: Thanks all for discussion and suggest .. i get my answer, from here
New Date() returns invalid date
  $(function() {
    $('.dateofbirthpicker').datepicker({
            dateFormat: 'dd/mm/yy'
          });
  });
  window.onload=function(){
    $('.dateofbirthpicker').on('change', function() {
          var dselect = $(".dateofbirthpicker").val();
          var match = /(\d+)\/(\d+)\/(\d+)/.exec(dselect);
          var dob = new Date(match[3], match[2], match[1]);
          var today = new Date();

          var age = Math.floor((today-dob) / (1000 * 60 * 60 * 24 * 360));
      $('#usia').val(age);
    });
  }


text:
Q: MacOS: Could not find Headers in Gstreamer 1.14.2 Framework I just installed the 1.14.2 on my mac using the pkg. There's no Headers folder!
/Library/Frameworks/GStreamer.framework/Headers links to  Versions/Current/Headers. But there nothing there!
To be clear, Current is a symlink to 1.0/ in the same directory
This is what the directory structure of the framework looks like
/Library/Frameworks/GStreamer.framework/
├── Commands -> Versions/Current/Commands
├── Libraries -> Versions/Current/Libraries
├── Resources -> Versions/Current/Resources
└── Versions
    ├── 1.0
    │   ├── Commands -> bin
    │   ├── Libraries -> lib
    │   ├── Resources
    │   ├── bin
    │   ├── etc
    │   │   └── fonts
    │   │       └── conf.d
    │   ├── lib
    │   │   ├── gio
    │   │   │   └── modules
    │   │   ├── girepository-1.0
    │   │   ├── gst-validate-launcher
    │   │   │   └── python
    │   │   │       └── launcher
    │   │   │           ├── apps
    │   │   │           └── testsuites
    │   │   └── gstreamer-1.0
    │   │       └── validate
    │   ├── libexec
    │   │   └── gstreamer-1.0
    │   └── share
    │       ├── fontconfig
    │       │   └── conf.avail
    │       ├── glib-2.0
    │       │   └── schemas
    │       ├── gstreamer
    │       ├── gstreamer-1.0
    │       │   └── validate
    │       │       └── scenarios
    │       └── locale
    │           ├── af
    │           │   └── LC_MESSAGES
    │           ├── am
    │           │   └── LC_MESSAGES

A: There are two packages - one with the runtime (which you probably have installed) and the developer package which installs on top of the runtime. Make sure you have both.


text:
Q: google app engine - datastore filtering not retrieving as expected Doing gql.query and not getting any results when I KNOW from looking at the datastore that there is a matching entry -- anyone ?  maybe it has to do with the format of my variables?

for each in leveloneAdd:
    new = tuple(each[1:-1].split(','))
    tag = new[0]
    htype = new[1]

    q1 = Level_1_Headings.all().filter("name1 =",tag).filter("heading_type =",htype).get()

So in my logs: have confirmed that values of variables are as follows:
INFO     2013-01-14 20:28:38,370 main.py:293] new is (u"'english'", u" 'subject'")
INFO     2013-01-14 20:28:38,370 main.py:295] tag is 'english'
INFO     2013-01-14 20:28:38,370 main.py:297] heading type is  'subject'

Also have confirmed that entry does exit (both name1 and heading_type are indexable)

A: Looking at your tuple, you appear to have strings that contain quotes:
(u"'english'", u" 'subject'")

Therefore when you try to query them, you are querying 'english' instead of english, which I'm assuming you want. Try stripping out the quotes from your original string if possible to see if the result returns as expected. You can see the difference here:
In [61]: t = (u"'english'", u"'subject'")

In [62]: a, b = t

In [63]: print a, b
'english' 'subject'

In [64]: t = (u"english", u"subject")

In [65]: a, b = t

In [66]: print a, b
english subject

To fix it, you could try something like this (note: you have a leading space in front of subject, so you may need to adjust for that):
In [68]: a, b = [i.strip("'") for i in t]

In [69]: a, b
Out[69]: (u'english', u'subject')

In [70]: print a, b
english subject


text:
Q: unable to load data in azure sql using azure databricks I am new to azure databricks . I have written a sample spark program in scala to load in azure sql via below query . I am getting an error . can someone please help me in this
Error Message ----
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host b63da5ce2d2d.tr27.northeurope1-a.worker.database.windows.net, port 65535 has failed. Error: "connect timed out. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall."
Scala code -
import com.microsoft.azure.sqldb.spark.config.Configimportcom.microsoft.azure.sqldb.spark.connect._// Aquire a DataFrame collection (val collection)valconfig=Config(Map("url"->"mysqlserver.database.windows.net","databaseName"->"MyDatabase","dbTable"->"dbo.Clients""user"->"username","password"->"xxxxxxxx"))importorg.apache.spark.sql.SaveModecollection.write.mode(SaveMode.Append).sqlDB(config)

A: It sounds like you have the firewall enabled on the SQL DB. Try disabling that first to confirm the problem.
If it works then you have two choices if you want the firewall enabled:
1) vnet attach your databricks and sqldb to the same vnet. https://docs.azuredatabricks.net/administration-guide/cloud-configurations/azure/vnet-inject.html
2) on the sqldb whitelist all the azure ips for the location you are. These are available for download. Note that some locations have more than 128 which is the maximum number of firewall rules available. https://www.microsoft.com/en-gb/download/details.aspx?id=41653

A: Why your port number is "65535" not 1433?
SQL Database communicates over port 1433. I think this is the reason why you can not connect to the Azure SQL DB.

Please reference: Server-level IP firewall rules.
We cannot change the port in Azure SQL Server. Your database is hosted on load balanced cloud server instances which are out of 'customer' control.
Reference: Change port in azure sql server.
Port 1433 is the only port that must be open on your desktop computer that hosts your SQL Database client application.
If you don't how to open the port 1433 on your computer,
please see: How To Open Firewall Port 1433 for SQL Server Database Engine.
About how to load data in Azure SQL Database, Azure provides many methods.

*

*Load data from CSV into Azure SQL Database (flat files).

*Loading files from Azure Blob storage into Azure SQL Database.
For more details, you can see Load data into SQL Server or Azure SQL Database with SQL Server Integration Services.
Both of them can help you load data in Azure SQL Database.
Hope this helps.


text:
Q: Нужно получить исходный код HTML страницы Для большинства страниц задача простая
string url = "somthing Uri";
            HttpClient client = new HttpClient();
            using (HttpResponseMessage response = client.GetAsync(url).Result)
            {
                using (HttpContent content = response.Content)
                {
                    string result = content.ReadAsStringAsync().Result;
                    Console.WriteLine(result);
                }
            }

Но в моем случае я получаю на выходе следующее:

Видимо страница содержит много джаваскрипта. Подскажите, можно ли как-нибудь получить код страницы с уже выполненными скриптами(нужно получить значение "Blocks Mined")?
Адрес необходимой страницы


text:
Q: Apache crashes running the controller's index page I'm trying CakePHP for the first time so I'm trying to run the blog tutorial located on CakePHP's website (Here). My CakePHP is installed correctly because when run the index page I get everything in green. But when I added my first controller, model and view and ran the index function of my controller, Apache crashes and I cannot continue.
I have already created the database called "blog" on my MySql.
This is my model class: (located in app/Model/Post.php)
<?php
class Post extends AppModel {
}

This is my controller: (located at app/Controller/PostsController.php)

class PostsController extends AppController {
    public $helpers = array('Html', 'Form');

    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }
}

And this is my view: (located at app/View/Posts/index.ctp)

Blog posts

        Id
        Title
        Created

    <?php foreach ($posts as $post): ?>

        <?php echo $post['Post']['id']; ?>

            <?php echo $this->Html->link($post['Post']['title'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>

        <?php echo $post['Post']['created']; ?>

    <?php endforeach; ?>
    <?php unset($post); ?>

This is the url I'm trying to run:
http://[lclhost]/blog/posts/
And http://[lclhost]/blog/ gives the correct output of the main CakePhp page.
This is the Apache error log I get:
[Mon Sep 09 17:32:28 2013] [notice] Parent: child process exited with status 3221225477 -- Restarting.
[Mon Sep 09 17:32:34 2013] [warn] pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?
[Mon Sep 09 17:32:34 2013] [notice] Digest: generating secret for digest authentication ...
[Mon Sep 09 17:32:34 2013] [notice] Digest: done
[Mon Sep 09 17:32:35 2013] [notice] Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i mod_autoindex_color PHP/5.2.8 configured -- resuming normal operations
[Mon Sep 09 17:32:35 2013] [notice] Server built: Dec 10 2008 00:10:06
[Mon Sep 09 17:32:35 2013] [notice] Parent: Created child process 10516
[Mon Sep 09 17:32:35 2013] [notice] Digest: generating secret for digest authentication ...
[Mon Sep 09 17:32:35 2013] [notice] Digest: done
[Mon Sep 09 17:32:36 2013] [notice] Child 10516: Child process is running
[Mon Sep 09 17:32:36 2013] [notice] Child 10516: Acquired the start mutex.
[Mon Sep 09 17:32:36 2013] [notice] Child 10516: Starting 250 worker threads.
[Mon Sep 09 17:32:36 2013] [notice] Child 10516: Starting thread to listen on port 443.
[Mon Sep 09 17:32:36 2013] [notice] Child 10516: Starting thread to listen on port 81.

OS: Windows 7
Apache/2.2.11 (Win32)
PHP Version 5.2.8
Does anyone know what I'm doing wrong?

A: Search for Parent: child process exited with status 3221225477 and try solutions you find.
A common one seems to be copying some .dll files.
I've personally run into a segfault myself that I have not found a solution for (tried everything). I think it's something to do with regular expressions. In any case. PHP on Apache/Windows is kinda wonky. Consider switching to Linux if you can't figure it out, it runs much more stable.


text:
Q: How to copy values from previous row and increasing numeric value? My SQL table AgeBand has
Age     Value
95      1
96      1
97      1
98      1
99      1
100     1

I would like to expand this table to
Age     Value
95      1
96      1
97      1
98      1
99      1
100     1
101     1
102     1
103     1
...
115     1

Goes up to 115 and keep copying the value above.
How should I code this?
Please help! Thank you@

A: Assuming SQL Server.....
Declare @age int = 101

while @age <= 116
BEGIN
  INSERT INTO AgeBand
    (Age, Value)
  VALUES
    (@age, 1)

  SET @Age = @Age + 1
END


text:
Q: Doctrine generate-migrations-diff and migrate I have tried to execute the cli command ./doctrine generate-migrations-diff and a version file has been created correctly in the right folder.
The message is: generate-migrations-diff - Generated migration classes successfully from difference
Then I try to execute another cli command ./doctrine migrate and a message appears to me saying: migrate - migrated successfully to version #1 but when I open the class any modification have been done. Why?
This is the version1 file:
<?php

class Version1 extends Doctrine_Migration_Base
{
public function up()
{
    $this->removeColumn('addresses', 'address_test');
}

public function down()
{
    $this->addColumn('addresses', 'address_test', 'string', '', array(
         'fixed' => '0',
         'unsigned' => '',
         'primary' => '',
         'notnull' => '1',
         'autoincrement' => '',
         ));
}
}

?>

This is the YAML. I have deleted the field: address_test
Addresses:
  connection: doctrine
  tableName: addresses
  columns:
    address_id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    address:
      type: string()
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    city:
      type: string(150)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    code:
      type: string(20)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    country_id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    base:
      type: integer(1)
      fixed: false
      unsigned: false
      primary: false
      default: '0'
      notnull: true
      autoincrement: false
    latitude:
      type: string(20)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    longitude:
      type: string(20)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    customer_id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false

This is the BaseAddresses class generated by the migrate command:
    bindComponent('Addresses', 'doctrine');
/**
 * BaseAddresses
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property integer $address_id
 * @property string $address
 * @property string $city
 * @property string $code
 * @property integer $country_id
 * @property integer $base
 * @property string $latitude
 * @property string $longitude
 * @property integer $customer_id
 * @property Countries $Countries
 * @property Customers $Customers
 *
 * @package    ##PACKAGE##
 * @subpackage ##SUBPACKAGE##
 * @author     ##NAME## <##EMAIL##>
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseAddresses extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->setTableName('addresses');
        $this->hasColumn('address_id', 'integer', 4, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => true,
             'autoincrement' => true,
             'length' => '4',
             ));
        $this->hasColumn('address', 'string', null, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => '',
             ));
        $this->hasColumn('city', 'string', 150, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => '150',
             ));
        $this->hasColumn('code', 'string', 20, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => '20',
             ));
        $this->hasColumn('country_id', 'integer', 4, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => '4',
             ));
        $this->hasColumn('base', 'integer', 1, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'default' => '0',
             'notnull' => true,
             'autoincrement' => false,
             'length' => '1',
             ));
        $this->hasColumn('latitude', 'string', 20, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => '20',
             ));
        $this->hasColumn('longitude', 'string', 20, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             'length' => '20',
             ));
        $this->hasColumn('customer_id', 'integer', 4, array(
             'type' => 'integer',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => false,
             'notnull' => true,
             'autoincrement' => false,
             'length' => '4',
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $this->hasOne('Countries', array(
             'local' => 'country_id',
             'foreign' => 'country_id'));

        $this->hasOne('Customers', array(
             'local' => 'customer_id',
             'foreign' => 'customer_id',
             'onDelete' => 'CASCADE'));
    }
}

In some website I have read that I have to execute the command: build-all in order to generate a version updated of the class addresses but I get this error:
SQLSTATE[HY000]: General error: 1005 Can't create table 'web63db1.#sql-3e6_11d' (errno: 121). Failing Query: "ALTER TABLE addresses ADD CONSTRAINT addresses_customer_id_customers_customer_id FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE". Failing Query: ALTER TABLE addresses ADD CONSTRAINT addresses_customer_id_customers_customer_id FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE

What have I do? Thanks in advance.

A: Migrations are only for changing your Database, not your model classes. You need to build your model classes afterwards.
So your normal way of working will be:

*

*Change your schema.yml

*Create your Migration file (generate-migrations-diff)

*Run your migration against the database (migrate), your database should be changed now

*Update your model-classes (build-all)

A: As I can't comment, let me modify Timo's answer:

*

*Change Your schema.yml

*Create Migration File (doctrine:generate-migrations-diff) (Note: this is comparing schema against Class files)

*Run your Migration (doctrine:migrate)(this runs the migrations based on the migration version number in your database)

*Build your class files. (doctrine:build --all-classes OR doctrine:build-model & doctrine:build-forms & doctrine:build-filters) (Note: this will build all your class files but will not try to update your database.)

I highly recommend backing up your database before running any migrations for the first time. If a migration fails (i.e. because you typoed your schema), you can end up with a database that is stuck between migrations and will need to be scrapped. I usually, backup my test-db and then import the live db to test the migration on. I'm more than slightly terrified of failing a migration on the live server.
Its important to note that the 'doctrine:generate-migrations-diff' compares the schema.yml to your currently generated class files. Don't build your classes before generating your migration
To deploy on a server, you will need to upload your schema.yml and your new migration files. Then just do steps 3 & 4 (and then clear your cache as a matter of habit) and you're good to go.


text:
Q: Analysing annual deforestation for multiple polygons in google earth engine I want to analyse and extract the total annual deforestation between 2001-2021 using the Hansen forest change dataset in Google Earth Engine.
For that, I use a feature collection containing (let's say) sub-national boundaries. The code has referred to as Shape, which has about 8-9k polygons.
The code that analyses annual deforestation (area in km2) for each shape (subset of Feature Collection Shapes) and saves it as an array is pasted below (this part works fine):
var annualforestloss = function(ID)
{
  // Get a feature collection with just the custom shapefile feature.
  // Shape contains multiple features (polygons)
 // Use any shapefile, if mine doesn't work
  var geometry = Shape.filter(ee.Filter.eq('ID', ID));
  //print(geometry);
  Map.addLayer(geometry);

  // Get the loss image.
  // This dataset is updated yearly, so check for the latest version.
  var gfc2021 = ee.Image('UMD/hansen/global_forest_change_2021_v1_9');
  var lossImage = gfc2021.select(['loss']);

  //Converting m2 to km2
  var lossAreaImage = lossImage.multiply(ee.Image.pixelArea()).divide(1000000);

  var lossYear = gfc2021.select(['lossyear']);
  var lossByYear = lossAreaImage.addBands(lossYear).reduceRegion({
    reducer: ee.Reducer.sum().group({
      groupField: 1
      }),
    geometry: geometry,
    scale: 30,
    maxPixels: 1e9
  });
  //print(lossByYear);

  var statsFormatted = ee.List(lossByYear.get('groups'))
    .map(function(el) {
      var d = ee.Dictionary(el);
      return [ee.Number(d.get('group')).format("20%02d"), d.get('sum')];
    });
  var statsDictionary = ee.Dictionary(statsFormatted.flatten());
  //print(statsFormatted)
  //print(statsDictionary)

  // Since there has been no forest loss for some years, the code above does not include those years.
  // To remedy that, we use another dictionary with values as zero and later combine them without overlap
  var dict1 = ee.Dictionary({
  "2001": 0, "2002": 0, "2003": 0,   "2004": 0,   "2005": 0,   "2006": 0,   "2007": 0, "2008": 0,
  "2009": 0,   "2010": 0,   "2011": 0,  "2012": 0,  "2013": 0,  "2014": 0,  "2015": 0,  "2016": 0,
  "2017": 0,  "2018": 0,  "2019": 0,  "2020": 0,  "2021": 0,});

  statsDictionary = statsDictionary.combine(dict1, false);
  //print(statsDictionary)

  // Platting chart
  /*
  var chart = ui.Chart.array.values({
    array: (statsDictionary.values()),
    axis: 0,
    xLabels: statsDictionary.keys()
  }).setChartType('LineChart')
    .setOptions({
      title: 'Yearly Forest Loss (ID-'+ID+')',
      hAxis: {title: 'Year', format: '####'},
      vAxis: {title: 'Area (square kilometer)'},
      legend: { position: "none" },
      lineWidth: 1,
      pointSize: 3
    });
    print(chart)
    */

    // Adding 'ID' for seamless data analysis in python
    return statsDictionary.values().add(ID)
};

However, the problem I am facing is: Looping through the features in Shapes: Although I know that 'for loops' are not recommended, I am limited by my ability to use map() function in GEE, which returns some client/server error.
// This function combines results from arrays in a loop
var combinearray = function(array1, array2)
{
  var arraynew =   (ee.Array.cat([array1, array2], 0))
  return arraynew
}

// Size of the features (total shapes about 8664)
print(Shape.size())

//**Limited by skill to run it with 'map' function. ##########  Please help!**!!!!!!!############

// Works fine for less loops. Hangs for double digit loops
var list = (annualforestloss(0))
for (var ID = 1; ID <= 6; ID++) {
  var listnew = (annualforestloss(ID))
  var list = (combinearray(list, listnew))
}
print(list)

//reshaping the array for export
var combinedarray = (list.reshape([7,22]))

print('--')
print(combinedarray)

Any help is greatly appreciated.
The following link can be used to see the code editor: https://code.earthengine.google.com/cd335cd1356dc69e3c9adc4ba9710bcb

A: I think using ReduceRegions() should do the trick. Here is a sample code (https://code.earthengine.google.com/?scriptPath=users%2Fdvps95%2Fdefault%3AHansen_Annual_ForestLoss)
The reduceRegion() maps the functions across multiple polygons. I hope this answers your question. I would suggest you follow the tutorials from "Spatial thoughts"- Ujwal gandhi does an excellent job in breaking down the concepts.
Good luck!


text:
Q: How to search and display names of file in a textbox and open the file by selecting it? I am searching for files in a folder and displaying the names of file in a textbox but now there is a problem. I would like to open a specific file by selecting it from the textbox. How can I achieve that? This is what I tried so far.
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

<!DOCTYPE html>

    <title></title>
    <link href="Styles/Site.css" rel="stylesheet" type="text/css" />

    <form id="form1" runat="server">

         <telerik:RadScriptManager ID="RadScriptManager1" runat="server" />

                <asp:HiddenField ID="hdoperatorid" runat="server" />
                <asp:HiddenField ID="hdbankid" runat="server" />
                <asp:HiddenField ID="hdCountry" runat="server" />

                                        <asp:Label ID="Label12" runat="server"
                                            Text="File Logs"></asp:Label>

                                                    <asp:Label ID="Label16" Width="100%" runat="server" Text="Enter Details"> </asp:Label>

                                    <asp:Label ID="lblCountry" runat="server" Text="Select Country" Width="200px" CssClass="LableText"></asp:Label>

                                    <asp:DropDownList id="ddlCountry" runat="server" AutoPostBack="True"  Width="200px">
                                     </asp:DropDownList>

                                    <asp:Label ID="lblLogType" runat="server" Text="Select Log Type" Width="200px" CssClass="LableText"></asp:Label>

                                    <asp:DropDownList id="ddlLogType" runat="server" AutoPostBack="True"  Width="200px">
                                     </asp:DropDownList>
                                    <%--<asp:DropDownList id="ddlLogType" runat="server"  Width="200px">
                                        <asp:ListItem>ElmaCore</asp:ListItem>
                                       <asp:ListItem>ElmaCore</asp:ListItem>
                                     </asp:DropDownList>--%>

                                    <asp:Label ID="lblDate" runat="server" Text="Date" Width="200px" CssClass="LableText"></asp:Label>

                                    <telerik:RadDatePicker ID="dtDate"  Width="200px" runat="server">
                                        <Calendar ID="Calendar1" runat="server" UseColumnHeadersAsSelectors="False" UseRowHeadersAsSelectors="False"
                                            ViewSelectorText="x">
                                        </Calendar>
                                        <DateInput ID="DateInput1" runat="server" DateFormat="dd/MMM/yyyy" DisplayDateFormat="dd/MMM/yyyy">
                                        </DateInput>
                                    </telerik:RadDatePicker>

                                    <asp:Label ID="lblReference" runat="server" Text="Reference" Width="200px" CssClass="LableText"></asp:Label>

                                   <asp:TextBox ID="txtReference" ReadOnly="false" Width="200px" runat="server" CssClass="textboxbook"></asp:TextBox>

                                        <asp:Label ID="lblMessageLine" Width="100%" Height="20px" runat="server" CssClass="BottomDisplayMsg" />

                                        <asp:Label ID="Label7" runat="server" Text="File Contents"></asp:Label>

                                        <asp:TextBox id="txtContents" runat="server"  Width="1200px" CssClass="textboxbook" TextMode="MultiLine" Height="300" />
                                        <%--<telerik:RadGrid ID="grdContents" runat="server" Height="180px" AutoGenerateColumns="true"
                                            GridLines="None">
                                            <ClientSettings EnablePostBackOnRowClick="true">
                                                <Selecting AllowRowSelect="true" />
                                                <Scrolling AllowScroll="True" UseStaticHeaders="true" />
                                            </ClientSettings>
                                            <%--<MasterTableView DataKeyNames="Country,BankID,FirstName,MiddleName,LastName,Mobile,Email,Address,City,Account,Title,IDNO">
                                                <Columns>
                                                    <telerik:GridBoundColumn DataField="Country" HeaderText="Country" UniqueName="Country" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="BankID" HeaderText="BankID" UniqueName="BankID" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="FirstName" HeaderText="FirstName" UniqueName="FirstName" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="MiddleName" HeaderText="MiddleName" UniqueName="MiddleName" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="LastName" HeaderText="LastName" UniqueName="LastName" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="Mobile" HeaderText="Mobile" UniqueName="Mobile" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="Email" HeaderText="Email" UniqueName="Email" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="Address" HeaderText="Address" UniqueName="Address" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="City" HeaderText="City" UniqueName="City" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="Account" HeaderText="Account" UniqueName="Account" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="Title" HeaderText="Title" UniqueName="Title" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                    <telerik:GridBoundColumn DataField="IDNO" HeaderText="IDNO" UniqueName="IDNO" DefaultInsertValue="">
                                                    </telerik:GridBoundColumn>
                                                </Columns>
                                            </MasterTableView>-%>
                                        </telerik:RadGrid>--%>

                                                <asp:Button ID="cmdAdd" Width="100px"  runat="server" Text="Submit" CssClass="button"
                                                    OnClick="cmdAdd_Click" />

                                <%--

                                                <asp:Button ID="cmdSend" Width="100px"  runat="server" Text="Send" CssClass="button"
                                                    OnClick="cmdSend_Click" />

--%>

                                                <asp:Button ID="btnClear" Width="100px"   runat="server" Text="Clear" CssClass="button"
                                                    OnClick="btnClear_Click" />

                                                <asp:Button ID="btnCancel" Width="100px"  runat="server" Text="Cancel" CssClass="button"
                                                     OnClick="btnCancel_Click" />

    </form>

c# code:-
 private void ProcessFile(string filename, string filePath)
    {
        try
        {
            DataRow dr;

            string line;

            string content = "";

            dr = tblFileContent.NewRow();

            // Read the file and display it line by line.
            //using (StreamReader file = new StreamReader(@"C:\Upload.txt"))
            using (StreamReader file = new StreamReader(filePath))
            {
                /*while ((line = file.ReadLine()) != null)
                {
                    content = line + "\n";

                }*/

                txtContents.Text += filename+"\n";

                file.Close();
            }

        }
}

A: From your current snippets you can open file like this:-
string strfullPath = System.IO.Path.Combine(filepath, filename);
using (StreamReader steamReader = new StreamReader(strfullPath))
{
    string content = steamReader.ReadToEnd();
}

Update1
If you want to open it with Notepad you need
System.Diagnostics.Process.Start()
Like:
Process.Start("notepad.exe", strfullPath);
If you want to open with its own editor than:
Process.Start(strfullPath);
Some how like this:-
//Process.Start(@"c:\myfile.txt");
Update2
If files are located at remote server then You would need to be authenticated on the share folder before you can access the files. For remote server this Link is worthy.


text:
Q: How can i --"Start Intent by GridView item Click" (not image) I want to start every Intent that remains under my src. They are named as One.java, Two.java and so on.
Here is my java code, but after clicking on a GridView item, it is opening the same Intent window, not the One.java or Two.java activity.

*

*MyActivity.java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
public class MyActivity extends Activity {

static final String[] numbers = new String[] { "One", "Two", "Three", "Four", "Five", "Six",  "Seven"  };

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myactivity);

        GridView gv = (GridView) findViewById(R.id.gridView1);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, numbers);

        gv.setAdapter(adapter);
        gv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
                Intent i = new Intent(getApplicationContext(), MyActivity.class);
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    }
}

This will help:
http://www.mkyong.com/android/android-gridview-example/ and
Android Gridview - Need to open different intents

A: Here is an example how you can start intent for every position in the grid view :
gv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View v,int position, long id) {

                switch (position) {
                case 0:

                    Intent i = new Intent(getApplicationContext(), MyActivity.class);
                    i.putExtra("id", position);
                    startActivity(i);
                    break;

                case 1:
                    //Use some different intent here
                    Intent j = new Intent(getApplicationContext(), MyActivity.class);
                    j.putExtra("id", position);
                    startActivity(j);
                    break;
                case 2:
                    //Use some different intent here
                    Intent k = new Intent(getApplicationContext(), MyActivity.class);
                    k.putExtra("id", position);
                    startActivity(k);
                    break;
                case 3:
                    //Use some different intent here
                    Intent l = new Intent(getApplicationContext(), MyActivity.class);
                    l.putExtra("id", position);
                    startActivity(l);
                    break;

                default:
                    break;
                }

            }
            });

I hope this is what you are looking for.


text:
Q: How do I convert binary to ASCII in python without it giving me output in another language? I am trying to make a program that converts text to binary and from binary to text. English to binary works perfectly fine, converting binary back always gives me another language.
    x = input("Encrypt: ")
    y = ''.join(format(ord(i), 'b') for i in x)
    print("Encrypted message: " + str(y))
    encryptDecrypt()

def converttotext():
    a = input("Decrypt: ")
    a = a.split(" ")
    b = ""
    for binary_value in a:
        c = int(binary_value, 2)
        d = chr(c)
        b += d
    print(b)
    encryptDecrypt()

def encryptDecrypt():
    e = input("Encrypt or decrypt(e/d): ")
    if e == "e":
        converttobinary()
    elif e == "d":
        converttotext()
    else:
        print("Enter 'e' or 'd'.")
        encryptDecrypt()

def main():
    encryptDecrypt()

if __name__ == '__main__':
    main()```
Here is the run log:
Encrypt or decrypt(e/d): e
Encrypt: hi
Encrypted message: 11010001101001
Encrypt or decrypt(e/d): d
Decrypt: 11010001101001
㑩
Encrypt or decrypt(e/d):

A: you are missing putting a space between each 8 bit output for each char you encrypt, your join in convert to binary should be with a space not with an empty string. Your decryption method is splitting the input by space expecting each char to be a separate 8 bit string. However your encrypt message just joins all the bits together giving you a 16 bit string by joining the 2 8 bit strings of "H" and "I" together. Decryption that 16 bit will give you a different result to decrypting the two 8 bit chars.
change
    y = ''.join(format(ord(i), 'b') for i in x)

to
    y = ' '.join(format(ord(i), 'b') for i in x)

CODE I AM RUNNING
def converttobinary():
    x = input("Encrypt: ")
    y = ' '.join(format(ord(i), 'b') for i in x)
    print("Encrypted message: " + str(y))

def converttotext():
    a = input("Decrypt: ")
    a = a.split(" ")
    b = ""
    for binary_value in a:
        c = int(binary_value, 2)
        d = chr(c)
        b += d
    print(b)

def encryptDecrypt():
    e = input("Encrypt or decrypt(e/d): ")
    if e == "e":
        converttobinary()
    elif e == "d":
        converttotext()
    else:
        print("Enter 'e' or 'd'.")

def main():
    while True:
        encryptDecrypt()

if __name__ == '__main__':
    main()

OUTPUT
Encrypt or decrypt(e/d): e
Encrypt: hi
Encrypted message: 1101000 1101001
Encrypt or decrypt(e/d): d
Decrypt: 1101000 1101001
hi

Encrypt or decrypt(e/d): e
Encrypt: How's the weather today
Encrypted message: 1001000 1101111 1110111 100111 1110011 100000 1110100 1101000 1100101 100000 1110111 1100101 1100001 1110100 1101000 1100101 1110010 100000 1110100 1101111 1100100 1100001 1111001
Encrypt or decrypt(e/d): d
Decrypt: 1001000 1101111 1110111 100111 1110011 100000 1110100 1101000 1100101 100000 1110111 1100101 1100001 1110100 1101000 1100101 1110010 100000 1110100 1101111 1100100 1100001 1111001
How's the weather today


text:
Q: How to add algorithm in beamer? i am trying to add algorithm pseudo code in my beamer presentation by simply copy and pasting the code which i have used in writing my paper as follows:
\documentclass{beamer}
\mode<presentation> {
\usetheme{Madrid}
}

\usepackage{graphicx} % Allows including images
\usepackage{booktabs} % Allows the use of \toprule, \midrule and \bottomrule in tables
\usepackage{biblatex}
\usepackage{xcolor}
\usepackage{algorithm,algorithmic}

\begin{document}
\begin{frame}[fragile]
\begin{algorithm}[H]
    \caption{Text Summarization Algorithm}\label{euclid}
    \begin{algorithmic}[1]
        \Procedure{Summary Construction}{}\newline
        \textbf{Input:} Text Document.\newline
        \textbf{Output:} Summary sentences.
        \State{Creating information table from a text document.}
        \State{Generate matrices.}
        \State {\textbf{Call Pocedure:} Reduct Construction \textbf{[Algorithm 2]}}
        \State {\textbf{Return:} Summary sentences}
        \EndProcedure
    \end{algorithmic}
    \label{alg_1}
\end{algorithm}
\end{frame}

\end{document}

The error i am getting is Undefined control sequence. \end{frame}. I would appreciate if someone can help me solving this issue.

A: Full minimal example please. This compiles just fine under TeX Live 2015.
\documentclass[a4paper]{beamer}
\usepackage{algorithm,algpseudocode}
\begin{document}

\begin{frame}
\begin{algorithm}[H]
    \caption{Text Summarization Algorithm}\label{euclid}
    \begin{algorithmic}[1]
        \Procedure{Summary Construction}{}\newline
        \textbf{Input:} Text Document.\newline
        \textbf{Output:} Summary sentences.
        \State{Creating information table from a text document.}
        \State{Generate matrices.}
        \State {\textbf{Call Pocedure:} Reduct Construction \textbf{[Algorithm 2]}}
        \State {\textbf{Return:} Summary sentences}
        \EndProcedure
    \end{algorithmic}
    \label{alg_1}
\end{algorithm}
\end{frame}

\end{document}