text:
Q: Remove tools button from Forge settingsTools Toolbar I'd like to remove some buttons from the Forge Toolbar.
So far I've used the code by @Philippe at PhilippeAnswer and I successfully removed all the buttons in the 'navTools' and 'modelTools'. When trying with the 'settingsTools' I can remove only the ModelBrowser button, not the Properties or Settings or Fullscreen button (in debug mode I see these controls as null values). Here is my code:
var viewerDiv = document.getElementById('MyViewerDiv');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(viewerDiv);
const onExtensionLoaded = (e) => {
    if (e.extensionId === 'Autodesk.DefaultTools.NavTools') {
        const settingsTools = viewer.toolbar.getControl('settingsTools')
        settingsTools.removeControl('toolbar-modelStructureTool') //That's ok!

        settingsTools.removeControl('toolbar-propertiesTool')  //NOT FUNCTIONING
        const settingsButton = settingsTools.getControl('toolbar-propertiesTool') //It remains as null when debugging
        settingsTools.removeControl(settingsButton)

        settingsTools.removeControl('toolbar-settingsTool') //NOT FUNCTIONING

        settingsTools.removeControl('toolbar-fullscreenTool') //NOT FUNCTIONING

        viewer.removeEventListener(
            Autodesk.Viewing.EXTENSION_LOADED_EVENT,
            onExtensionLoaded)
    }
}
viewer.addEventListener(Autodesk.Viewing.EXTENSION_LOADED_EVENT, onExtensionLoaded)
viewer.start(svfUrl, modelOptions, onLoadModelSuccess, onLoadModelError);

I know I can hide the entire settingsTool, but then I have the same problem when making visible to true for Property/Settings/Fullscreen button. It seems again the control remains null when debugging the code.
Please, can you help me facing with the 3 last buttons in the 'settingsTools' toolbar?
Essentially, I'm trying to understand the global customization of the viewer, removing everything in the UI is not my purpose :)
Thanks!!

A: When to remove a specific button depends on whether at all it's created by an extension, and if so, which extension.
The "toolbar-firstPersonTool" button that Philippe's answer talks about is created by "Autodesk.FirstPerson" extension so we can just listen to the loading of that extension.
However, the buttons you are interested in, like "toolbar-modelStructureTool" are "built-in" and not created by an extension. So you have to listen to another event, the "TOOLBAR_CREATED_EVENT" as shown by this blog post:
When to remove toolbar buttons


text:
Q: React fetch posting multiple values under same array I'm trying to post multiple values for tag inside an array of my fetch.
However, it is posting them connected in one array.
I would like it to always post it
how tag currently sent
tag:[{name: [null, null]}]
how tag should be sent
tag:[
{name: "value from field"},
{name: "next value from field"}
]
I also welcome suggestions on a more clean/efficient way to do this form.
here is my code:
class AddNew extends React.Component {
  constructor(props) {
    super(props);
    this.onTitleChange = this.onTitleChange.bind(this);
    this.onTagChange = this.onTagChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {
      options: []
    };
  }
  componentDidMount() {
    fetch(TAG_API, {
    })
      .then(response => response.json())
      .then(json => {
        this.setState({ options: json });
      });
  }
  onTitleChange(e) {
    this.setState({ [e.target.name]: e.target.value });
    console.log("the title has changed" + e);
  }
  onTagChange(value) {
    this.setState({ value: value });
    console.log("they look like this" + value);
  }
  handleSubmit(e, value) {
    e.preventDefault();
    return (
      fetch(CREATE_API, {
        method: "POST",
        body: JSON.stringify({
          title: this.state.itemtitle,
          tag: [
            {
              name: this.state.value.map(e => {
                e.name;
              })
            }
          ]
        })
      })
        .then(res => res.json())
        .catch(err => console.error(err))
    );
  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <textarea
            name="itemtitle"
            type="text"
            placeholder="Add new..."
            onChange={this.onTitleChange}
          />
          <button type="submit">Save</button>
        </form>
        <Select
          mode="tags"
          name="tagfield"
          onChange={this.onTagChange}
        >
          {this.state.options.map(e => (
            <Option value={e.name}> {e.name} ({e.taglevel}) </Option>
          ))}

        </Select>
      </div>
    );
  }
}

A: In your handleSubmit function, your mapping function over this.state.value is never returning a value (see longer explanation later). Even if it did return, you're only ever going to have an array with a single element with all the name values. Try changing the body composition into:
body: JSON.stringify({
  title: this.state.itemtitle,
  tag: this.state.value.map(e => ({ name: e.name })),
})

Longer explanation: Arrow functions implicitly return, unless you surround the body in curly brackets, which in that case are interpreted as a function block and you need to use explicit return. By surrounding a literal object in round brackets, you can implicitly return one.
The following two examples are equivalent:
const beep = () => {
   return { boop: 'bzzt' };
};

const beep = () => ({ boop: 'bzzt' });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hauppauge 610 Analog Video Capture Script or Command I have Xubuntu 14.04. The camcorder I am using is the Sony CCD-TRV16 NTSC 180x Digital Zoom. I am using the Hauppauge 610 USB-Live 2 Analog Video Digitizer and Video Capture Device to convert 8mm tapes to mp4. I am using VLC to convert the videos.
I will be converting quite a few tapes. It would be nice to have my exact same VLC GUI settings I use in a command or script. Also the ability to cut off recording after a certain time period would be great. I do not care what program I use to convert these. This customer said they were able to successfully use ffmpeg. However, I am fine with using any program that works. Much thanks in advance!
Here is the output of ffmpeg -f v4l2 -i /dev/video0 -f alsa -i hw:2,0.
Input #0, video4linux2,v4l2, from '/dev/video0':
  Duration: N/A, start: 8535.656468, bitrate: 165722 kb/s
    Stream #0:0: Video: rawvideo (YUY2 / 0x32595559), yuyv422, 720x480, 165722 kb/s, 29.97 fps, 29.97 tbr, 1000k tbn, 1000k tbc
Guessed Channel Layout for  Input Stream #1.0 : stereo
Input #1, alsa, from 'hw:2,0':
  Duration: N/A, start: 1450034548.361553, bitrate: 1536 kb/s
    Stream #1:0: Audio: pcm_s16le, 48000 Hz, 2 channels, s16, 1536 kb/s

A: Preliminary Steps
Launch VLC with vlc -vvv. This turns on verbosity to 2 (debug). This can also be seen in VLC GUI by going to Tools > Messages. Then follow the steps listed above in the screen shots to display the needed information for the command in the debug log. Then you can adjust the appropriate syntax by looking at the script below and online. You can also see the code and syntax by selecting Show more options. (The first screenshot in my question above.) However, this is only how I was able to create the cvlc command below. You may simply want to adjust the below script to your needs.
Initially, I was unable to get the audio to work with the one RCA audio port on my camcorder. I fixed this by going to Tools > Preferences > All (radio button, bottom left). Then I went to Input / Codecs > Access modules > ALSA. I changed the Sample rate to 48000 Hz. After changing this setting you will be able to stream your video. The other sample rates were causing an error.
Go to Media > Open Capture Device. Select Video device name and Audio device name (note that in the screen shot above it is default because I was using the microphone port instead. Yours will be different if you're using the RCA connection on your Hauppauge device.) Select NTSC (or whatever format your video tapes are). Click Play. While playing, go to Tools > Codec Information. You will want to adjust the below script according to the information given there. I adjusted the frame rate to 29.97 and sample rate to 48000 Hz. in my script because of the information given there.
About the Script
a. You are prompted to input the filename and metadata. Files are set to save to ~/Videos.
b. VLC (cvlc)

*

*I set the timeout to 122 minutes because my 8mm tapes are two hours. The --foreground option allows you to hit 'ctrl c,' and it will stop only this portion of the script and continue to the next part. (Some videos I have are shorter.)

*You can use VLC GUI to find the audio and video device names. (See the above screenshot.)

*Know whether your video is NTSC or another format.

*vcodec and acodec are set set to mpeg2 and mpga. The Amazon product page for the Hauppauge 610 states that it encodes to MPEG-2.

*For MPEG-2, VLC GUI only gave the option for .ts format. (See second screenshot above.) Therefore I am using mux=ts. Initially I was using vcodec=h264 acodec=mpga and mux=mp4. However, there were audio sync issues and the sound would drop out at certain places in the video. Also see the mux= section here.

*I needed samplerate=48000 for it to work.

*The frames per second given on the Codec Information were 29.97. This is standard for VHS / 8mm tapes. Therefore, I decided to match it.

*I chose to deinterlace. I thought this looked better.

*Using mux=ts will create a large file. My two hour videos are 5-7 GB.

c. FFmpeg compresses further with libx264 (from about 5 GB to about 1.5 GB) and adds in the metadata. There were additional handwritten notes about each 8mm tape and I wanted to include this additional information with the file. In the same command, FFmpeg moves left channel audio from only left to both left and right channels as a stream copy with no additional audio compression. My camcorder has only one RCA audio port. So this fixes the one speaker issue. Thanks to mondaugen for their answer on the one-channel audio issue.
d. Lastly, you are notified when the script finishes. For my personal script, I am actually using the following instead.
On my computer:
exo-open --launch WebBrowser $HOME/Videos/video-finished.htm

File contains:
VIDEO FINISHED

On my phone:
You can install gcalcli to receive a notification on your phone via Google Calendar when the script completes. Below, the date and time for two minutes in the future is put into a variable. Then a calendar entry is created for that time. A reminder is set for the start of that event. Google Calendar needs a two minute buffer. (I tried one minute.) So, you would be notified two minutes after the encode finishes.
new_date=`date --date="2min"`
gcalcli --calendar 'Name of Your Calendar' --title 'Video Finished' --where '' --when \'"$new_date"\' --duration 5 --description '' --reminder 0 add

End Product
The final result produces the larger .ts file and a further compressed .mp4.
CPU Usage
I have an AMD A8-6500B processor. cvlc runs at about 15% cpu usage. However, ffmpeg was running at about 97%. Therefore, in my script (not in the one below), I added the -threads 3 option to keep CPU usage at an overall 75%. I am able to do this because my processor is quad core.
#!/bin/bash

# Name:         Hauppauge 610 USB-Live 2 Analog Video Digitizer and Video Capture Device Conversion Script
# Author:       jbrock
# Dependencies: VLC media player; ffmpeg, in Ubuntu you will need to add a ppa to install.
# License:      GNU GPLv3 (http://www.gnu.de/documents/gpl-3.0.en.html)
# Usage:        Digitize analog tapes to .ts format. Then convert to mp4, add metadata, and make sound work on left and right channels.

# Enter the name of the file.
echo -n "Enter file name: "
read archivo

# This is for metadata. It will show up in the media player playlist or after clicking Properties (in OS X Info) on the file context.
echo -n "Enter a description: "
read comentarios

# Encode video and stop after 122 minutes. The foreground option allows you to hit 'ctrl c,' and it will only stop this portion of the script.
timeout --foreground 122m cvlc v4l2:///dev/video0 :input-slave=alsa://hw:2,0 :v4l2-standard=NTSC :live-caching=300 --sout '#transcode{vcodec=mpeg2,acodec=mpga,ab=128,channels=2,samplerate=48000,fps=29.97,deinterlace}:std{access=file{no-overwrite},mux=ts,dst='$HOME/Videos/$archivo.ts'}'

# Convert to H.264 to compress further, add in the metadata comments, and make output from the left speaker to both speakers.
ffmpeg -i $HOME/Videos/$archivo.ts -c:v libx264 -preset medium -crf 22 -metadata comment="$comentarios" -af "pan=mono|c0=FL" $HOME/Videos/$archivo.mp4

# Show the 'finished' message.
notify-send "VIDEO FINISHED"

A: Here's an example for ffmpeg
ffmpeg -f v4l2 -i /dev/video0 -f alsa -i default -t 02:02:00 \
-c:v libx264 -crf 23 -preset medium \
-c:a aac -strict experimental -ac 1 -b:a 96k \
-vf yadif,hqdn3d,format=yuv420p -movflags +faststart output.mp4

*

*-t is for duration. This example will make a 2 hr and 2 min output.

*See FFmpeg Wiki: H.264 Video Encoding Guide for the x264 -crf and -preset info.

*yadif is a deinterlacer. You should experiment with the settings to see what mode works best for your content. Alternatively, you could try w3fdif.

*hqdn3d is a denoiser. May be useful if your content is noisy, but too much denoising will cause obvious blurriness, and this filter may be slow.

*The format filter will ensure a chroma subsampling scheme that is widely compatible. Otherwise, ffmpeg will assume you want to avoid or minimize chroma subsampling and the output may not be playable by non-FFmpeg based players like QuickTime.

*-movflags +faststart will move some data after encoding is complete from the end of the file to the beginning. This allows playback to begin before the file is completely downloaded if your viewers are watching via progressive download.

*You can add -metadata title="Title" and other metadata if you feel like it.
Cutting out the extra junk
After watching the output and you want trim it, getting rid of any blue or black blank video for example, you can just re-mux without re-encoding. This will skip the first 10 seconds and make an output 600 seconds (10 minutes) long. It may not be frame exact, but it will probably be close enough.
ffmpeg -ss 10 -i input -c copy -t 600 output

A: I was also using a variation on the ffmpeg method when I first got this hardware, but I observed that vlc's default transcode gave better visual results on my system than ffmpeg, so I goofed about with the vlc command line (cvlc) and figured out the command line to request what the GUI example above is doing.
cvlc  v4l2:///dev/video1:standard=NTSC :input-slave=alsa://hw:3,0 :live-caching=1000 --sout "#transcode{vcodec=h264,acodec=mpga,vb=3000,fps=29.97,ab=128,audio-sync,channels=2,deinterlace}:file{dst=rec122015.mp4,no-overwrite}" --sout-keep


text:
Q: Evaluate comparison operator from table column Is it possible to expand a field value into a comparison operator? Something like this:
create table math (
    value1 int,
    value2 int,
    operator text
);
insert into math values(1,2,'>=');

select * from math where value1 operator value2;

PS: I know that it is possible to solve this use case by means of case when, but want to know if there is an alternative solution.

A: You can do this only using case statement, or using case in the function code
CREATE OR REPLACE FUNCTION check_values(pvalue1 integer, pvalue2 integer, pop text)
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
DECLARE
    v_count integer;
    v_ret bool;
begin

    case pop
       when '=' then
          return (pvalue1 = pvalue2);
       when '>' then
          return (pvalue1 > pvalue2);
       when '<' then
          return (pvalue1 < pvalue2);
       when '>=' then
          return (pvalue1 >= pvalue2);
       when '<=' then
          return (pvalue1 <= pvalue2);
       else
          return false;
       end case;

END;
$function$
;

Then you can use this function on your query:
select *
    from examples.math
where
    examples.check_values(value1, value2, "operator");

I think that this is only possible using the case operator


text:
Q: Show that $\lim_{R \to \infty} \int_0^\pi e^{-R \, \sin(t)}dt = 0$
Show that
$$\lim_{R \to \infty} \int_0^\pi e^{-R \, \sin(t)}dt = 0$$

I have to prove the integral from above. I tried the following,
$$
\lim_{R \to \infty} |\int_0^\pi e^{-R \, \sin(t)}dt| \leq \lim_{R \to \infty} \int_0^\pi |e^{-R \, \sin(t)}|dt,$$
and since $e^{-R\, \sin(t)} < e^{-R}$ we get
\begin{align}
\lim_{R \to \infty} \int_0^\pi |e^{-R \, \sin(t)}|dt &\leq \lim_{R \to \infty} |e^{-R}| \int_0^\pi dt\\
&=\lim_{R \to \infty} \pi \, e^{-R} = 0.&
\end{align}
From this we can conclude that $$\lim_{R \to \infty} \int_0^\pi e^{-R \, \sin(t)}dt = 0.$$
I am not sure if this is correct. I also heard that maybe I could do it with the dominated convergence theorem but am not sure how I would solve this, can someone help me with that?

A: Observe that $\sin t \ge \frac{2t}{\pi}$ for $0 \le t \le \frac{\pi}{2} $. Thus $$\left\lvert\int_0^\pi e^{-R\sin t}\, dt\right\rvert = 2\int_0^{\pi/2}e^{-R\sin t}\, dt \le 2\int_0^{\pi/2}e^{-2Rt/\pi}\, dt = \frac{\pi(1 - e^{-R})}{R}\to 0\quad \text{as}\quad R\to \infty$$

A: Hint: let $0 < a < \frac \pi 2$ and try writing
$$\int_0^\pi e^{-R \sin t} \, dt = \int_0^a e^{-R \sin t} \, dt + \int_a^{\pi - a} e^{-R \sin t} \, dt + \int_{\pi - a}^\pi e^{-R \sin t} \, dt$$ to obtain the estimate
$$0 \le \int_0^\pi e^{-R \sin t} \, dt \le 2a + \pi e^{-R \sin a}.$$

A: Let $ R> 1 $. Using the fact that $ \left(\forall x\in\mathbb{R}\right),\ \operatorname{e}^{x}\geq 1+x $, we have : \begin{aligned}\int_{0}^{\pi}{\operatorname{e}^{-R\sin{x}}\,\mathrm{d}x}\leq\int_{0}^{\pi}{\frac{\mathrm{d}x}{1+R\sin{x}}}&=2\int_{0}^{+\infty}{\frac{\mathrm{d}y}{\left(1+y^{2}\right)\left(1+R\frac{2y}{1+y^{2}}\right)}}\\ &=2\int_{0}^{+\infty}{\frac{\mathrm{d}y}{y^{2}+2Ry+1}}\\ &=2\int_{0}^{+\infty}{\frac{\mathrm{d}y}{\left(y+R\right)^{2}+1-R^{2}}}\\ &=\frac{1}{\sqrt{R^{2}-1}}\int_{0}^{+\infty}{\left(\frac{1}{y+R-\sqrt{R^{2}-1}}-\frac{1}{y+R+\sqrt{R^{2}-1}}\right)\mathrm{d}y}\\ &=\frac{1}{\sqrt{R^{2}-1}}\left[\ln{\left(\frac{y+R-\sqrt{R^2-1}}{y+R+\sqrt{R^{2}-1}}\right)}\right]_{0}^{+\infty}\\ &=\frac{1}{\sqrt{R^{2}-1}}\ln{\left(\frac{R+\sqrt{R^{2}-1}}{R-\sqrt{R^{2}-1}}\right)}\\ &=\frac{2}{\sqrt{R^{2}-1}}\ln{\left(R+\sqrt{R^{2}-1}\right)}\underset{R\to +\infty}{\sim}\frac{2\ln{\left(2R\right)}}{R}\underset{R\to +\infty}{\longrightarrow}0\end{aligned}

A: For all $R\geq0$ we have $0\leq e^{-R\sin(t)}\leq 1$ (which is integrable over $(0,\pi)$) and $\lim\limits_{R\to \infty} e^{-R\sin(t)} = 0$ a.e. $t.$ So the dominated convergence theorem gives the result.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\on}[1]{\operatorname{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\bbox[5px,#ffd]{\lim_{R \to \infty}\int_{0}^{\pi}\expo{-R\sin\pars{t}}\,\,\dd t} =
\lim_{R \to \infty}\int_{-\pi/2}^{\pi/2}\expo{-R\cos\pars{t}}\,\,\dd t
\\[5mm] = & \
2\lim_{R \to \infty}\int_{0}^{\pi/2}\expo{-R\cos\pars{t}}\,\,\dd t =
2\lim_{R \to \infty}\int_{0}^{\pi/2}\expo{-R\sin\pars{t}}\,\,\dd t
\\[2mm] = & \
2\lim_{R \to \infty}
\overbrace{\int_{0}^{\infty}\expo{-Rt}\,\,\dd t}
^{\ds{Laplace's\ Method}} =
2\lim_{R \to \infty}{1 \over R} = \bbx{\color{#44f}{\large 0}}
\end{align}


text:
Q: Product Classification Parent/Child Hierarchy - "A parent attribute must be related to the key attribute of the dimension." This is my first post on stackoverflow... I did some searching and could not find my answer, so I will ask here.
I have a need to report sales by Product Classification.

*

*FactTransactions have a reference to ProductID

*My DimProduct table has ProductID, ClassID, ProductName, ...

*My DimProductClass table has ClassID, ParentClassId, ClassName,...

*Product Classification is a parent child relationship... one to many

A Product can belong to a single class (one to many), but enter the hierarchy at different levels... for example:

*

*Pipe A (Product) -> Galvanized Pipe (Class) -> Pipe (Class)

*Pipe B (Product) -> Steel Pipe (Class) -> Pipe (Class)

*Pipe C (Product) -> Pipe (Class)

*Pipe D (Product) -> Galvanized Pipe (Class) -> Pipe (Class)

In SSAS, I have taken the following steps:

*

*Defined my relationships in the data source view

*

*Related Fact (f) to DimProduct (p)

*Related DimProduct (p) to DimProductCategory (pc1) on p.ClassID = pc1.ClassID

*Related DimProductCategory (pc1) to DimProductCategory (pc2) on pc1.ParentClassId = pc2.ClassId

*Defined a product dimension

*

*Pulled in the following attributes

*

*ProductName (ProductID Key Column; Key Field Attribute Usage)

*ClassName (ClassID Key Column)

*Classes (ParentClassID key column, Parent Attribute Usage)

*Related Attributes

*

*ProductName -> ClassName

*ClassName -> Classes

When I do the last step, I get an error "A parent attribute must be related to the key attribute of the dimension."
Here is a link to a screenshot of a similar mock up using AdventureWorks (I don't have enough reputation points to add a screenshot):
http://i.imgur.com/zwtFemH.png
What can I do to roll up the product transactions into their necessary product classifications?
Thanks,
BPlantes


text:
Q: Exporting module - ES6 & TypeScript In python, we import names from other modules, without exporting those names.

In the below code from ES6,
// exports a function declared earlier
export { myFunction };

In TypeScript & ES6, Why to export a name to import it from other module? How name without export qualifier different from a name with export qualifier?

A: Think of ES2015 modules as a language-level extension of the revealing module pattern. You normally don't want to expose everything in a module to the outside world, so you choose what to export on your own by prefixing it with the export keyword:
export function myFunction() {
  doMagic();
}

And someone importing from that file will be able to import { myFunction } from './module'. If you don't export your function, it will not be available to import.


text:
Q: Creating an object which contains unique item from a nested array I have an array of objects called employees. I need a solution that will return me a list of groups and respective employees present in the group along with the group properties.
The example is below, I have used an object but the result can also be an array that has a property called groupName within an object. [{groupName:"developer", employees:[],...}..] As long as the response returns a list of groups with their corresponding employees.
Below is the solution I did but I need a solution with a better time complexity that is O(n).
const employees = [
  { "name": "John Doe",
    "id": "1",
    "groups": [
      { "id": "developerId", "name": "developer", "color": "#fff" },
      { "id": "engineerId",  "name": "engineer", "color": "#fff" }
    ],
    "groupId":["developerId", "engineerId"]
  },
  { "name": "Jane Doe",
    "id": "2",
    "groups": [
      { "id": "developerId", "name": "developer", "color": "#fff" },
      { "id": "testerId",  "name": "tester", "color": "#fff" }
    ],
    "groupId":["developerId", "testerId"]
  }
]

//Solution O(m*n)
 let groups = {};
  employees.forEach((item) => {
    item.groups.forEach((group) => {
      if (!groups[group.name]) {
        groups[group.name] = {
          employees: [item.id],
          ...group,
        };
      } else {
        groups[group.name].employees = [...groups[group.name].employees, item.id];
      }
    });
  });

//result
{
    "developer":{
        "id":"developerId",
        "employee":[
           "1",
           "2"
        ],
        "color":"#fff"
    },
    "engineer":{
        "id":"employeeId",
        "employee":[
            "1",
         ],
         "color":"#fff"
    },
    "tester":{
        "id":"testerId",
        "employee":[
            "2",
         ],
         "color":"#fff"
    }
}

A: Using Array#reduce and Array#forEach:

const employees = [
  {
    "name": "John Doe",
    "id": "1",
    "groups": [
      { "id": "developerId", "name": "developer", "color": "#fff" },
      { "id": "engineerId", "name": "engineer", "color": "#fff" }
    ],
    "groupId": ["developerId", "engineerId"]
  },
  {
    "name": "Jane Doe",
    "id": "2",
    "groups": [
      { "id": "developerId", "name": "developer", "color": "#fff" },
      { "id": "testerId", "name": "tester", "color": "#fff" }
    ],
    "groupId": ["developerId", "testerId"]
  }
];

const groups = employees.reduce((acc, { id: employeeId, groups = [] }) => {
  groups.forEach(({ id, name, color }) => {
    acc[name] = {
      id, color, employee: [...(acc[name]?.employee ?? []), employeeId]
    };
  });
  return acc;
}, {});

console.log(groups);

A: If you like to add some speed, you could use the old fashioned for statement for iterating, especially of having only a single result object.
This approach does not create an object again and again and uses the already existing objects.

const
    employees = [{ name: "John Doe", id: "1", groups: [{ id: "developerId", name: "developer", color: "#fff" }, { id: "engineerId", name: "engineer", color: "#fff" }], groupId: ["developerId", "engineerId"] }, { name: "Jane Doe", id: "2", groups: [{ id: "developerId", name: "developer", color: "#fff" }, { id: "testerId", name: "tester", color: "#fff" }], groupId: ["developerId", "testerId"] }],
    result = {};

for (const { id: employeeId, groups } of employees) {
    for (const { id, name, color } of groups) {
        result[name] ??= { id, color, employee: [] };
        result[name].employee.push(employeeId);
    }
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: SPA React(18.2) App: React-Leaflet map component renders with no errors but off the side of the screen ENTIRELY. How to move it? I'm using react18 to create an app. Goal is to add a component 'page' that includes a map that takes up about 50 to 70% of the screen and includes markers for current user's location first (and add more markers once that is accomplished and styled.
I've created child nested components to be used by parent components and routes for pages:
components/CurrentLocation/index.js:

import { useEffect, useState } from 'react';
import { MapContainer, TileLayer, useMap, Marker, Popup, Circle } from 'react-leaflet';
import tileLayer from '../TileLayer/index';

const center = [52.22977, 21.01178];

const Location = () => {
  const map = useMap();
  const [position, setPosition] = useState(null)

  useEffect(() => {
    map.locate({
      setView: true
    })
    map.on('locationfound', (event) => {
      setPosition(event.latlng)
    })
  }, [map])

  return position
    ? (
      <>
        <Circle center={center} weight={2} color={'red'} fillColor={'red'} fillOpacity={0.1} radius={500}></Circle>
        <Marker position={position}>
          <Popup>You are here</Popup>
        </Marker>
      </>
    )
    : null
}

const MapWrapper = () => {
  return (
    <MapContainer
      center={center}
      zoom={18}
      scrollWheelZoom={false}
    >
      <TileLayer {...tileLayer} />
      <Location />
    </MapContainer>
  )
}

export default MapWrapper;

MapWrapper is imported to Locator/index.js
import React, { Component } from 'react';
import { Text, Box, ChakraProvider } from '@chakra-ui/react'
import Partners from '../Partners';
import MapWrapper from '../CurrentLocation';
import './style.css';

class Locator extends Component {

  render() {
    return (
      <div>

        <ChakraProvider>
          <Box display="flex" justifyContent="center">
            <Text>Select your store</Text>
          </Box>

          <Box bgColor='#628E90' border="3px solid white" minH='3500px' mt={3}>
            <Text>Test 2</Text>
            <Box className='map-box' border="3px solid white" display='inline-flex' ml={5}>
              <Text>Map SHOULD display here</Text>
              <MapWrapper />
            </Box>
            <Box display='flex' justifyContent='right'>
              // dynamically rendered list of stores with inventory
              <Partners />
            </Box>
          </Box>
        </ChakraProvider>

      </div>
    )
  }
}

export default Locator;

Locator gets imported to /src/App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link, } from 'react-router-dom';
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  createHttpLink,
} from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import './App.css';
import { ChakraProvider } from '@chakra-ui/react';
import { Box } from '@chakra-ui/react';
import NavMenu from './components/NavMenu/NavMenu';
import Home from './pages/Home';
import Login from './pages/Login';
import Signup from './pages/Signup';
import PartnerLogin from './pages/PartnerLogin';
import Education from './pages/Education/Education';
import PartnerInventory from './pages/PartnerInventory';
import Cart from './components/Cart/Cart.js';
import CustomerPage from './pages/CustomerPage';
import { StoreProvider } from './utils/GlobalState.js';
import Locator from './components/Locator/index'
import NoMatch from './components/NoMatch'

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem('id_token');
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

function App() {
  document.title = 'Too Good To Waste';

  return (
    <ApolloProvider client={client}>
      <Router>
        <StoreProvider>
          <ChakraProvider>
            <Box minH='1500px' bgColor='#F5EFE6'>
              <header>
                <NavMenu />

                <Box display="flex" justifyContent="center">
                  <Link id="home" to="/" className="blk-let">TOO</Link>
                  <Link id="home" to="/" className="csv-let">Good</Link>
                  <Link id="home" to="/" className="blk-let">TO</Link>
                  <Link id="home" to="/" className="csv-let">Waste</Link>
                </Box>

                <Cart />
              </header>

              <main>
                <Routes>
                  <Route path="/" element={<Home />} />
                  <Route path="*" element={<NoMatch />} />
                  <Route path="/signup" element={<Signup />} />
                  <Route path="/login" element={<Login />} />
                  <Route path="/locator" element={<Locator />} />
                  <Route path="/partnerlogin" element={<PartnerLogin />} />
                  <Route path="/education" element={<Education />} />
                  <Route path="/customer" element={<CustomerPage />} />
                  <Route path="/partnerInventory" element={<PartnerInventory />} />
                </Routes>
              </main>
            </Box>
          </ChakraProvider>
        </StoreProvider>
      </Router>
    </ApolloProvider>
  );
}

export default App;

And finally App is imported to /src/index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Dependencies for reference:
"dependencies": {
    "@apollo/client": "^3.7.1",
    "@chakra-ui/icons": "^2.0.11",
    "@chakra-ui/react": "^2.3.6",
    "@emotion/react": "^11.10.4",
    "@emotion/styled": "^11.10.4",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "dayjs": "^1.11.6",
    "framer-motion": "^7.6.1",
    "graphql": "^16.6.0",
    "install": "^0.13.0",
    "jwt-decode": "^3.1.2",
    "leaflet": "^1.9.2",
    "react": "^18.2.0",
    "react-animations": "^1.0.0",
    "react-awesome-reveal": "^4.1.0",
    "react-burger-menu": "^3.0.8",
    "react-dom": "^18.2.0",
    "react-error-boundary": "^3.1.4",
    "react-icons": "^4.6.0",
    "react-leaflet": "^4.1.0",
    "react-responsive-carousel": "^3.2.21",
    "react-router-dom": "^6.4.2",
    "react-scripts": "5.0.1",
    "styled-components": "^5.3.6",
    "web-vitals": "^2.1.4"
  },

I thought it wasn't rendering but then realized there were no errors. Upon turning off every styling option in the dev tools console, FINALLY, a tiny map corner poked out from the top left. The pics show the element selected with leaflet css that is imported from the css link. The item value I was messing with was:
style="transform: translate3d( 0px, 0px, 0px) scale(0.5);"

Changing the first 0 to 60px moved the very small rendering of the world map to the right, followed by 100px in second spot moved the rendering of the map down.
It did not solve any issues however because the map element still identifies as being in the position it started: kicked up and left off of the screen. Not to mention its tools like "+/-" for zoom etc. I tried a plethora of css ways that would normally affect SOMETHING but so far none of ways I know are actually getting it to budge at all let alone render in the box it's supposed to populate to.
I am going to try playing with adding the translation styling (even though it doesn't solve the overall problem of "map's home and center exists off of the screen" but it seems like there should be at least one better way!

A: From my test you need to set a height of the MapContainer.
<MapContainer
    center={center}
    zoom={18}
    scrollWheelZoom={false}
    style={{ height: 400, width: "100%", zIndex: 94 }}
>
    <TileLayer {...tileLayer} />
    <Location />
</MapContainer>


text:
Q: Reusable react-hook-form useFieldArray component in TypeScript I am making a reusable, dynamic form component using react-hook-form's useFieldArray hook and I am having problems correctly adding the type for field.
To set-up the form I have added a type and some defaultValues:
export type NamesArray = { name: string; required: boolean }[];

export type FormValues = { randomFormValue: string; namesArray: NamesArray };

const defaultValues = {
  namesArray: [{ name: "Me", required: true }]
};

Now, when I use my reusable form component, <NamesForm /> it should always know to use the namesArray part of the form for that component such that I should be able to do:
type Props<T> = {
  control: Control<T>;
  register: UseFormRegister<T>;
};

export function NamesForm<T extends NamesArray>({
  control,
  register
}: Props<T>) {
  const { fields, append } = useFieldArray<T, "namesArray", "id">({
    control,
    name: "namesArray"
  });

  return (
    <>
      {fields.map((field, index) => {
        return field.required && <input {...register(`namesArray.${index}.name` as const)} />;
      })}

      <button type="button" onClick={() => append({})}>
        Append
      </button>
    </>
  );
}

Where, in order to make the component reusable, I have used generic props.
My problem is that even though I have explicitly said that my generic T should contain a namesArray, TS can't seem to pick that up and gives me the error:

Type 'string' does not satisfy the constraint 'ArrayPath'.

And it is not enough for me to not define the type of field because I would like to use field's properties such as required.
Code sandbox: https://codesandbox.io/s/controlled-field-array-forked-vooe9w?file=/src/NamesForm.tsx:139-214

A: Your generic field values T should extend an object containing namesArray, not an array.
type Name = {
  name: string;
  required: boolean;
};
type FormValuesWithNamesArray = {
  namesArray: Name[];
};
export function NamesForm<T extends FormValuesWithNamesArray>

But even with this change the error persist. What did work for me is to remove the generic:
export type = Name {
  name: string;
  required: boolean;
}
export type FormValuesWithNamesArray = {
  namesArray: Name[];
  [key: string]: any;
}
type Props = {
  control: Control<FormValuesWithNamesArray>;
  register: UseFormRegister<FormValuesWithNamesArray>;
};

export function NamesForm({ control, register }: Props) {
  const { fields, append } = useFieldArray({
    control,
    name: "namesArray",
  });

  return (
    <>
      {fields.map((field, index) => {
        return (
          field.required && (
            <input {...register(`namesArray.${index}.name` as const)} />
          )
        );
      })}

      <button
        type="button"
        onClick={() => append({ name: "", required: false })}
      >
        Append
      </button>
    </>
  );
}


text:
Q: Variance convergence in Kalman Filtering when applying motion and measurements updates? I'm developing a visualization interface for Kalman Filters in 1D. I have an initial variance $variance\_init$ and constant motion and measurement variances. When I apply consecutive motion-measurement updates I notice that the variance converges to some value that is a function of the ratio $\frac{motion\_variance}{measurement\_variance}$.
The motion update is:
$new\_variance = previous\_variance + motion\_variance$
The measurement update is:
$new\_variance = ({\frac{1}{previous\_variance}+\frac{1}{measurement\_variance}})^{-1}$
I wanted to analytically calculate this variance that the system converges to but I don't know how to approach the problem. It is basically a function composition that looks something like this:  $measure(motion(...measure(motion(var\_init))$


text:
Q: How to add space to a  tag I have many
 tag within a main
 tag.
I would like increase the visual space created by the
 (example margin top and bottom).

Some text here

Some other text

Some other text

I could use different
 but I have to do it in this way in my website.
Any idea how increase the space created by
? Many thanks.

A: Take a look at the line-height property of CSS.
Example:
p { line-height: 90%; }

A: If you no want to use css, try of this code. when you use style with  of Html file the javascript programming will be prefer your order in Html file instead of same class inside the file of css.

Some text here

Some other text

Some other text

Some text here

Some other text

Some other text

Some text here

Some other text

Some other text

I hope my answer helped for your question.
best regards,
Wahab

A: You need to use the line-height property.
p {line-height:70px}

A: I think br tags are for line breaks nothing more nothing less. Why try to write a work-around-ish kinda code. If you can't go with any suggested answers i would say just use multiple br tags.


text:
Q: Console application for developer interviews I have been tasked with helping our HR department create some new interview questions for candidates applying for development positions. As part of the process, I would like to assess their ability to both understand code without the help of a compiler and spot potential future problems.
As such, I have devised a basic console application. The source code I will provide to the candidates and ask them the following questions:

*

*Would this code compile without any errors? If not, why not?

*Can you spot any potential issues in the code which might cause bugs in future?

*What improvements would you make to the code?

I've got my own answers to the questions, but I would love to get some feedback to see if there's anything that I may have missed.
using System;
using System.Collections.Generic;

namespace DeveloperTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var users = new List<User>();

            users.Add(new User("John Smith", "42", DateTime.Today));

            string name = "Jane Smith";
            int age = 37;
            int yearJoined = 17;
            int monthJoined = 01;
            int dayJoined = 15;
            users.Add(new User()
            {
                Name = name,
                Age = age,
                DateJoined = new DateTime(day: dayJoined, month: monthJoined, year: yearJoined)
            });

            users[0].PrintUserInfo();

            RemoveUsersUnderAge(users, 40);

            Console.ReadKey();
        }

        private void RemoveUsersUnderAge(List<User> users, int age)
        {
            foreach (var user in users)
            {
                if (user.Age < age)
                {
                    users.Remove(user);
                }
            }
        }
    }

    class User
    {
        private string _name;
        private int _age;
        private DateTime _dateJoined;

        public User()
        {

        }

        public User(string name, string age, DateTime dateJoined)
        {
            if (name == null) Name = "Unknown";
            if (age == null) Age = 0;
            if (dateJoined == null) DateJoined = DateTime.Today;

            Name = name;
            Age = Convert.ToInt32(age);
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        public DateTime DateJoined
        {
            get { return _dateJoined; }
            set { _dateJoined = value; }
        }

        private void PrintUserInfo()
        {
            Console.WriteLine($"Name: {this.Name}.");
            Console.WriteLine($"Age: {this.Age} years old.");
            Console.WriteLine($"Joined: {this.DateJoined}.");
        }
    }
}

A: You're on the right track, but your test could use some improvement. Don't test people to understand code, test them to understand algorithms. The majority of the analysis you're asking for can be performed by tools, instead have candidates do analysis that still today require humans to perform.
The majority of the issues with your code sample will be revealed in a quarter second after hitting build and fixed nearly as quickly. Protection modifiers, static/non-static members, and typos, and similar issues are not worth spending the time going through, because it won't reveal much about the candidates overall skill, because it is mostly a typo hunt.
What you want, and your code sample lacks, is a difficult algorithm to analyze and debug. Stuff like hairy date/time handling, C string splitting algorithms, small parsing algorithms, stuff like that. Key elements are looping, branching, and data manipulation. Those are where more insidious bugs can hide, stuff like off-by-one errors, lack of bounds checking, etc. Code samples that are especially good are where only edge or corner cases are a problem.
The code sample you've provided barely does anything, the majority of it is just getters and setters, minimal decision making and nearly inconsequential looping. Additionally, since your code sample doesn't really do any particular task, suggestions for how to improve it will be contrived and meaningless. Studying your sample can demonstrate to some extent someones ability to analyze code, but not to synthesize new code. That can be demonstrated by mentally walking through complicated algorithms, where a clear model of assignment and operations can be demonstrated.
Another good way to demonstrate synthesis ability is to have part of the algorithm under analysis missing. Leave out a nested function or some such, but leave enough of the main body for it to be clear what the algorithm is supposed to be doing. Then, have the candidate write the missing piece to make the overall algorithm work again, and verify it's correctness.
The types of tasks I've outlined will do a much better job of separating the major league players from the bush leagues, and doesn't instead evaluate them on the basis of their ability to do something computers already do a million times better.


text:
Q: iptables "recent" module - setting module parameters The manpage for iptables 'recent' module explains that the module itself accepts parameters. How does one go about setting these parameters? I would imagine they would be set somewhere where the module is loaded. I do not know where that is.
Does anyone have any ideas?

A: If you load the module by hand, you just add it to the modprobe command line:
modprobe ipt_recent param1=val1 param2=val2

Otherwise, if it's being loaded automatically, you can create a file in /etc/modprobe.d, say /etc/modprobe.d/ipt_recent, with contents of:
options ipt_recent param1=val1 param2=val2

Which will do the same thing as the modprobe line above.

A: Warning: Understand that changing this has an impact on the memory usage of the machine as these details are stored in memory and iptables require greater resources to deal with storing larger amounts of data.
Setup the xt_recent configuration file
Create the file /etc/modprobe.d/xt_recent.conf and include a line like this:
options xt_recent ip_list_tot=50 ip_pkt_list_tot=150
Don't forget to add some comments about what you're doing. Future you will thank you.
Prepare to reinitialize xt_recent
Before we remove any rules in your firewall currently using the recent module or simply disable the firewall. You may want to save your rules before you do this with sudo iptables-save > somefile.txt or maybe sudo service iptables save if you distro supports that.
Choose one of these two depending on your situation to clean up. You could also simply restart your computer at this point and skip to adding rules.
To shutdown iptables
sudo service iptables stop
To Remove specific Rules:

*

*Use iptables -L --line-numbers to list the rules and look for "recent:" in the rules.

*Use iptables -D INPUT # where # is the line number to delete rules.

Reinitialize xt_recent
Remove the module with sudo modprobe -r xt_recent.
Add it back with sudo modprobe xt_recent.
Check to make sure your parameters were applied with sudo cat /sys/module/xt_recent/parameters/ip_pkt_list_tot.
Add the rules that you couldn't
If you stopped iptables sudo service iptables start to bring it back.
Add your rules back in with the higher values you wanted.
Bonus:
sudo watch 'iptables -nvL' will allow you to watch stuff hit the xt_recent rules.

A: I don't have the reputation to reply to TopQ's answer, but I signed up for an account just to tell people not to do what he suggests. The source code of the module (http://lxr.linux.no/linux+v3.9/net/netfilter/xt_recent.c) has no provision to detect changes to that parameter and no provision to reallocate the kernel buffer responsible for keeping track of recent hits.
Therefore, if you chmod that parameter writable and subsequently change it, subsequent entries to existing recent hit logs will overrun the previously allocated kernel buffers and cause a kernel panic.

A: If the module is already loaded, you can still change the parameter by manipulating the value in /sys/module/ipt_recent/parameters/.
For example, to change the value of ip_pkt_list_tot you can do:
echo 200 > /sys/module/ipt_recent/parameters/ip_pkt_list_tot
Of course, you got to have the permission.


text:
Q: Perl Regex vs Parsing So I'm writing a static validator for a particular kind of file. These files are expected to have a certain JSON-like object in it. Sample below
theObject = {
key1 = value1,
key2 = value2,
key3 = {
    key4 = value4,
    key5 = value5
}
}

There are a lot of other things in this file but this is required and I need to validate its presence and form. My current solution to this has been to find the 2nd } after theObject's name and extract out the guts of the object so I can stick it in a JSON parser. Obviously this fails if the creator fails to include key3 entirely.
I've been trying to tweak a regex to fit the form
m/theObject = (\{.*\})/

Obviously this doesn't work. Any ideas on how to match the corresponding closing bracket to the expected opening bracket?

A: Use a recursive regular expression to match balanced braces.
use strict;
use warnings;

use JSON;

my $data = do { local $/; <DATA> };

# Find theObject within your data:
if ( $data =~ m/^theObject\s*=\s*(\{ (?: (?> [^{}]+ ) | (?1) )* \})/msx ) {
    my $hashref = from_json($1);

    print "Perl Data Structure:\n";
    use Data::Dump;
    dd $hashref;

} else {
    warn "Unable to find theObject";
}

__DATA__
theObject = {
   "key2" : "value2",
   "key1" : "value1",
   "key3" : {
      "key5" : "value5",
      "key4" : "value4"
   }
}

Outputs:
Perl Data Structure:
{
  key1 => "value1",
  key2 => "value2",
  key3 => { key4 => "value4", key5 => "value5" },
}

A: Looks like a simple case of nested braces matching... which in Perl is done with recursive regexes. But in this case you have to handle JSON strings too, as they may contain the } character:
(?(DEFINE)
    (?<json>
        \{ (?:
            [^{}"']+
            |(?<quote>["'])(?:[^\\"']+|\\.)*\k<quote>
            |(?&json)
        )* \}
    )
)

theObject\s*=\s*(?&json)

Use the x modifier to allow whitespace in the pattern.
Demo: http://regex101.com/r/jX2rS6/1

A: Using a proper parser is always an option too. So far what I can glean from your example is something like
Top       ::= KeyValue
KeyValue  ::= Key '=' Value
Key       ::= Name
Value     ::= Name
            | Object
Object    ::= '{' KeyValues '}'
KeyValues ::= KeyValue+

Name ~ [\w]+

(this is valid input for Marpa::R2 if I haven't made any mistakes). But there's a lot  I don't know, like whether you support other kinds of values, quoted strings maybe, what the whitespace rules are, exactly how "JSON-like" things are, and whether there is actually already a parser on CPAN good enough :)


text:
Q: Having trouble displaying the contents of my array stack So I am learning how stack works in C, and I wrote out a little menu that allows the user to push and pop integers to and from the stack. I used the global array implementation of stack.
#include <stdio.h>

#define MAX 5

int top = -1;
int myStack[MAX];

int push(int item){

    if(top >= MAX - 1){
        printf("stack overflow");
        return -999;
    }

    else{
        top++;
        myStack[top] = item;
    }
    return 1;
}

int pop(){

    if(top == -1){
        printf("no integer to pop from stack.");
        return -999;
    }

    int popped = myStack[top];
    top--;

    return popped;
}

void displayStack(int myStack[], int top){
    for(int i = 0; i < top; i ++){
        printf("%d ", myStack[i]);
    }
}

int main(){

    printf("Menu Options:\n");
    printf("1 - Push\n");
    printf("2 - Pop\n\n");

    int data, choice;

    while(1){
        printf("Enter choice: ");
        scanf("%d", &choice);

        if(choice == 1){
            printf("Enter data to push: ");
            scanf("%d", &data);
            push(data);
            displayStack(myStack, top);
            printf("\n\n");
        }

        if(choice == 2){
            pop();
            displayStack(myStack, top);
            printf("\n\n");
        }

        if(choice == 3){
            break;
        }
    }

    return 0;
}

My problem is, when I run the code for the first time and insert 1 to push an integer to the stack, everytime, the first call to push, my display doesn't return anything. Only the second time will it display an item from the stack on the screen.
I think this has something to do with the indexes in my display function, but I'm pretty sure I have them correct? After I call push, the top of the stack for the first time goes from -1 to 0, and my displayStack function is starting at index 0.
Any help would be appreciated, thank you!


text:
Q: Как передать именованный аргумент sqlite? Не могу разобраться, как мне передать именованный аргумент (переменную) в базу данных.
Создал базу данных следующим образом:
import sqlite3

conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()

cursor.execute("CREATE TABLE users (id numeric)") #пробовал и текстовое значение

Пытался вставить переменную так:
ids = [] #заполненный список с значениями, которые мне нужно вставить
for i in ids:
   cursor.execute("INSERT INTO users VALUES (?,)", i) #пробовал через форматирование строки, тоже не вышло

Что я делаю не так?

A: cursor.execute(sql, parameters) в качестве параметров ожидает итерируемый объект (обычно список или кортеж):
ids = [1,2,3]

for i in ids:
    cursor.execute("INSERT INTO users VALUES (?)", (i,))   # qmark style
#  NOTE: ---------------------------->       ^^^   ^^^^

используем именованные параметры:
for i in ids:
    cursor.execute("INSERT INTO users VALUES (:id)", {"id": i})  # (named style)

ВНИМАНИЕ: (<скаляр>) - не является кортежем!
In [55]: i = 1

In [56]: type( i )
Out[56]: int

In [57]: type( (i) )   #  /  NOTE!
Out[57]: int           #  \  (i) - это просто скаляр, а не кортеж

In [58]: type( (i,) )
Out[58]: tuple


text:
Q: Azure Function Context Log Location How do you view the context.log messages for an Azure Node.js Function?
If I have the following:
exports.handler = async (context) => {
    context.log.info('Hello Bob');
};

Where would I go to see Hello Bob?
I know exactly how to view such a phrase in AWS Cloudwatch but I cannot find the same in Azure.  I have looked at: https://learn.microsoft.com/en-us/azure/azure-functions/functions-monitoring but it points to Application Insights which when I go there and look at say, Activity Logs, there is no information.  I have also looked at Logs on that screen but it wants to run queries. So, how do you look at context.log.info data within Azure?

A: You can access that in the Azure Portal
It does not appear immediately. may take a couple of minutes after you run your function. also make sure the function has started

*

*Locate your Function app and click "Functions" > "your function name" > "Monitor" and any of the log records:

Or you can use the insights for that:

and


text:
Q: can many Postgres processes run with the same data directory?
I have an application running in multiple pods. You can imagine the app as a web application which connects to Postgres (so each container has both app and Postgres processes). I would like to mount the volume into each pod at /var/lib/postgresql/data so that every app can have the same state of the database. They can read/write at the same time.
This is just an idea of how I will go.
My question is: is there any concern I need to be aware of? Or is this the totally wrong way to go?
Or will it be better to separate Postgres from the app container into a single pod and let the app containers connect to that one pod?
If my questions show knowledge I lack, please provide links I should read, thank you!

A: This will absolutely fail to work, and PostgreSQL will try to prevent you from starting several postmasters against the same data directory as good as it can. If you still manage to do it, instant data corruption will ensue.
The correct way to do this is to have a single database server and have all your "pods" connect to that one. If you have many of these "pods", you should probably use a connection pooler like pgbouncer to fight the problems caused by too many database connections.


text:
Q: Sqoop Import from MySQL Server to Hadoop I am trying for importing data from MySQL Server to HDFS via Sqoop. But I am getting certain errors as:
Error: java.io.IOException: SQLException in nextKeyValue
at org.apache.sqoop.mapreduce.db.DBRecordReader.nextKeyValue(DBRecordReader.java:277)
at org.apache.hadoop.mapred.MapTask$NewTrackingRecordReader.nextKeyValue(MapTask.java:556)
at org.apache.hadoop.mapreduce.task.MapContextImpl.nextKeyValue(MapContextImpl.java:80)
at org.apache.hadoop.mapreduce.lib.map.WrappedMapper$Context.nextKeyValue(WrappedMapper.java:91)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
at org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1698)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
Caused by: java.sql.SQLException: The statement (1) has no open cursor.
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2901)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:773)
    at com.mysql.jdbc.MysqlIO.nextRow(MysqlIO.java:1304)
    at com.mysql.jdbc.MysqlIO.fetchRowsViaCursor(MysqlIO.java:933)
    at com.mysql.jdbc.CursorRowProvider.fetchMoreRows(CursorRowProvider.java:357)
    at com.mysql.jdbc.CursorRowProvider.hasNext(CursorRowProvider.java:291)
    at com.mysql.jdbc.ResultSet.next(ResultSet.java:2834)
    at org.apache.sqoop.mapreduce.db.DBRecordReader.nextKeyValue(DBRecordReader.java:237)
    ... 12 more

16/09/11 17:31:06 INFO mapreduce.Job:  map 100% reduce 0%
16/09/11 17:31:07 INFO mapreduce.Job: Job job_1473606531803_0004 failed with state FAILED due to: Task failed task_1473606531803_0004_m_000000
Job failed as tasks failed. failedMaps:1 failedReduces:0

16/09/11 17:31:07 INFO mapreduce.Job: Counters: 12
    Job Counters
        Failed map tasks=13
        Killed map tasks=3
        Launched map tasks=16
        Other local map tasks=16
        Total time spent by all maps in occupied slots (ms)=112163
        Total time spent by all reduces in occupied slots (ms)=0
        Total time spent by all map tasks (ms)=112163
        Total vcore-milliseconds taken by all map tasks=112163
        Total megabyte-milliseconds taken by all map tasks=114854912
    Map-Reduce Framework
        CPU time spent (ms)=0
        Physical memory (bytes) snapshot=0
        Virtual memory (bytes) snapshot=0
16/09/11 17:31:07 WARN mapreduce.Counters: Group FileSystemCounters is deprecated. Use org.apache.hadoop.mapreduce.FileSystemCounter instead
16/09/11 17:31:07 INFO mapreduce.ImportJobBase: Transferred 0 bytes in 53,373 seconds (0 bytes/sec)
16/09/11 17:31:07 INFO mapreduce.ImportJobBase: Retrieved 0 records.
16/09/11 17:31:07 ERROR tool.ImportTool: Error during import: Import job failed!

Has any one seen this behavior before? What am I doing wrong here? Pls suggest me solution.
Thanks.


text:
Q: Setting time limit php I am trying to set time limit in reservation system. Such that Users must
have the ability to remove their bookings, but not before the lapse of 1 minute away from the time when the booking has been entered
 <?php
 require_once 'connection.php';

if(isset($_SESSION['book'])){

if (isset($_SESSION['book_time'])){
    if (time()-$_SESSION['book_time']>= 60){

        if (isset($_POST['delete'])){

$machineID = $_POST['machine_id'];
$starttime = $_POST['start_time'];

$qry = "DELETE FROM bookings where machine_id = '$machineID' AND start_time = '$starttime'";

$result =  mysql_query($qry,$conn);
if ($result){

    if(mysql_affected_rows()>0){
        $message[] = 'Booking Deleted form DB';
    }
  }

    }
}
 }
  }
?>

but it couldn't remove even after 1 min with this script....what could be possible problem

A: Possible problems:

*

*$_SESSION['book'] or $_SESSION['book_time'] or $_POST['delete'] is NULL

*$machineID contains not exists ID

*$starttime contains wrong time or time in wrong format

Try to dump this variables. If they are ok try to run query manualy.


text:
Q: How to make a dynamic dropdown on hover in my sidebar? When I click the button sidebar will come with the dynamic categories in it. while I hover on a category,  I am trying to show the sub categories in the side bar.
But it's very hard for me to find this because am a newcomer.
My code is

                ×

                        <?php $sql=mysqli_query($con,"select id,categoryName  from category");
                        while($row=mysqli_fetch_array($sql))
                        {
                        ?>
                        <a href="category.php?cid=<?php echo $row['id'];?>" >|
                        <?php echo $row['categoryName'];?>
                        <?php }
                        ?>

        ☰

when i hover on the category , the corresponding sub categories should come .
My database is like , having two tables one category table and another one subcategory table.
category table

id  categoryName

1   aaa

2   bbb

3   ccc

subcategory table

id categoryid subcategory_name

1      1           zzz

2      2           yyy

3      2           xxx

4      3           www

A: You need to create a multi-dimensional array to achieve what you want. Since you are a beginner it would be better for you to walk on a simpler path (though it's not the optimal way, but you will understand why I'm saying this).
$sql=mysqli_query($con,"select id,categoryName  from category");
$catSubCatArr = array();
while($row=mysqli_fetch_array($sql)){
    $catSubCatArr[$row['id']] = $row['categoryName'];
    $innerSql=mysqli_query($con,"select id, categoryid, subcategory_name from subcategory where categoryid = ".$row['id']]);
    while($innerRow=mysqli_fetch_array($innerSql)){
        $catSubCatArr[$row['id']]['subcategory'][$innerRow['id']] = $innerRow['subcategory_name'];
    }
}

now create your desired dropdown which will be nested with this $catSubCatArr with the help of foreach(). Again I want to inform you that it's never a good idea to call SQL queries inside a loop, it will slowdown the process. But I think it will be helpful and you can change when you understand the flow completely.
you can add the HTML like this
<?php foreach($catSubCatArr as $key=>$val){ ?>
<a href="category.php?cid=<?php echo $key;?>" >|
<?php echo $val['categoryName'];?>
<?php /* Here start your sub category html?>
<?php foreach($val['subcategory'] as $innerkey=>$innerval){?>
<a href="category.php?cid=<?php echo $innerkey;?>" >|
<?php echo $innerval['subcategory_name'];?>
<?php }
}?>


text:
Q: How to go back multiple pages in ionic 3 I have the page flow like below:
A->B->C->D

Somehow I will do a function in page"D", after it need to go back page"B".
How can I achieve that?
Using .pop() just can go back one page.
Using .push(B) is also not the solution, because the flow will become:
A->B->C->D->B

The solution I want is:
A->B

Anyone know how to achieve it? Thanks a lot.

A: this.navCtrl.popTo(this.navCtrl.getByIndex(this.navCtrl.length()-(N+1)));

Where N is the number of pages that you want to go back.
So if you want to go back 2 pages N=2

A: Try Using the popTo() method by giving the index of page in a parameter like below:
nav.popTo( this.navCtrl.getByIndex(1))


text:
Q: How can I find element on mongo using $all operator with Yesod? Problem:
I have a Person model to retrieve from mongodb:
Person
    name Text
    favoriteFoods [Text]

This is my function:
getPersonsByFoods :: [Text] -> DB [Entity Person]
getPersonsByFoods foods = selectList [PersonFavoriteFoods ??? foods] []

I took a look at Query filter combinators but I didn't find any function that can help me to deal with a list. I need I kind of containsAll function.
This is should be the final mongo query:
PersonModel.find({ favouriteFoods: { "$all" : ["sushi", "burger"]} });

Meta:
- yesod >=1.6 && <1.7
- yesod-core >=1.6 && <1.7
- yesod-static >=1.6 && <1.7
- persistent >=2.9 && <2.10
- persistent-mongoDB >=2.8 && <2.9
- mongoDB
- persistent-template >=2.5 && <2.9

Question:
How can I achieve this result using Yesod?

A: I think you could use <-.
getPersonsByFoods :: [Text] -> DB [Entity Person]
getPersonsByFoods foods = selectList [PersonFavoriteFoods <-. foods] []

Alternatively if you are also using esqueleto you can:
getPersonsByFoods :: [Text] -> DB [Entity Person]
getPersonsByFoods foods = selectList [PersonFavoriteFoods `in_` valList foods] []


text:
Q: Backing up Excel Files to a different Directory In Excel 2007 in the Save As box there is an option to 'Create a Backup' which simply backs up the file whenever it is saved. Unfortunately it backs up the file to the same directory as the original.
Is there a simple way to change this directory to another drive / folder?
I have messed about with macros to do this, coming up with:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    'Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    'Saves the current file to a backup folder and the default folder
    'Note that any backup is overwritten
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveCopyAs Filename:="T:\TEC_SERV\Backup file folder - DO NOT DELETE\" & _
    ActiveWorkbook.Name
    ActiveWorkbook.Save
    Application.DisplayAlerts = True
    End Sub
This creates a backup of the file ok the first time, however if this is tried again I get:
Run-Time Error '1004';
Microsoft Office Excel cannot access the file 'T:\TEC_SERV\Backup file folder - DO NOT DELETE\Test Macro Sheet.xlsm. There are several possible reasons:
The file name or path does not exist
The file is being used by another program
The workbook you are trying to save has the same name as a...
I know the path is correct, I also know that the file is not open anywhere else. The workbook has the same name as the one I'm trying to save over but it should just overwrite.
I have posted the question about the coding on Stack Overflow but wondered if there is an easier way to do this.
Any help would be much appreciated.
Joe

A:
The workbook you are trying to save has the same name as a...

I am assuming this ends in "as a workbook that is already open". I don't know why this is a requirement, but Excel won't touch two spreadsheets with the same filename. You might want to try & Workbook.Name & ".bak" in your code.
Although you should note that you are probably going about this the wrong way. What you are trying to do is called "version control", and you should look into Shadow Copies and a source code repository (even though this Excel spreadsheet is not source code, you can still version the file). This is most likely "The Right Thing To Do (TM)"

A: Ok so the long and the short of it seems that there is no easy way to do this. There isn't the function present in Excel to allow the backups to be saved to a different folder.
What is required is a fairly simple Visual Basic Macro - similar to the one outlined above. I have Taken Taspeotis's ideas into account and so have upvoted his answer. I have not given the answer as correct as it does not answer the question. I do appreciate the time given though.


text:
Q: Error 3021 when I run VBA request to a linked table in Access I want to send a request (query) from Excel to an Access database. But when my request targets a linked table it triggers the 3021 error. However when I run the same resquest in Access, itself, the request editor (dynaset) shows 1300 rows.
I have tested various solutions:

*

*I tried executing the resquest with
conObj.execute(SQLString)

*Then with the following, with the same error
RecordSet.Open SQL, "DsnODBC"

*Finally with
RecSet.Open SQL, conn, adOpenForwardOnly, adLockReadOnly, adCmdText
But nothing works; every time I get an error at this line
LesResult = RecSet.GetRows()

'=========Instansiation des objets=========' 'init object
Set RecSet = New ADODB.recordset
Set conn = New ADODB.Connection
'=========================================='

'===========Connection à la base===========' 'DB connect
conn.ConnectionString = ThisWorkbook.leControler.strConnectString
conn.Open ThisWorkbook.leControler.strConnectString
'=========================================='

Select Case HerbierAdmin.ActiveAction

    Case "PM":
        [Somme code]

        SQL = "SELECT SAP_ClassItems.[Plan de montage] "
        SQL = SQL & "FROM SAP_ClassItems "
        SQL = SQL & "WHERE ((SAP_ClassItems.[Plan de montage] Like 'PM 21S *'));"
        Debug.Print SQL
        Set RecSet = conn.Execute("SELECT SAP_ClassItems.[Plan de montage] FROM SAP_ClassItems WHERE ((SAP_ClassItems.[Plan de montage] Like 'PM 21S *'));")

        LesResult = RecSet.GetRows() 'error here
        RecSet.Close

        For i = 0 To UBound(LesResult, 2)
           Me.ListeBox.AddItem (LesResult(0, i)) 'add result to drop down box
        Next

Expected result: The query result can be added to a drop-down list.

A: skip the variable:
Set RecSet = conn.Execute("SELECT SAP_ClassItems.[Plan de montage] FROM SAP_ClassItems WHERE ((SAP_ClassItems.[Plan de montage] Like 'PM 21S *'));")

    Do until recsec.eof
       Me.ListeBox.AddItem recsec(0) 'add result to drop down box
       recsec.movenext
    loop
    recsec.close

A: Ok, so thanks to Harassed Dad. The solution is place '%' instead of '*' on the like instruction.


text:
Q: Generate image data from three numpy arrays I have three numpy arrays, X, Y, and Z.
X and Y are coordinates of a spatial grid and each grid point (X, Y) has an intensity Z. I would like to save a PNG image using this data. Interpolation is not needed, as X and Y are guaranteed to cover each grid point between min(X) and max(Y).
I'm guessing the solution lies within numpy's meshgrid() function, but I can't figure out how to reshape the Z array to NxM intensity data.
How can I do that?

To clarify the input data structure, this is what it looks like:
   X   |    Y    |    Z
-----------------------------
0.1    | 0.1     | something..
0.1    | 0.2     | something..
0.1    | 0.3     | something..
...
0.2    | 0.1     | something..
0.2    | 0.2     | something..
0.2    | 0.3     | something..
...

0.2    | 0.1     | something..
0.1    | 0.2     | something..
0.3    | 0.3     | something..
...

A: To begin with, you should run this piece of code:
import numpy as np

X = np.asarray(<X data>)
Y = np.asarray(<Y data>)
Z = np.asarray(<Z data>)

Xu = np.unique(X)
Yu = np.unique(Y)

Then you could apply any of the following approaches. It is worth noting that all of them would work fine even if the data are NOT sorted (in contrast to the currently accepted answer):
1) A for loop and numpy.where() function
This is perhaps the simplest and most readable solution:
Zimg = np.zeros((Xu.size, Yu.size), np.uint8)
for i in range(X.size):
    Zimg[np.where(Xu==X[i]), np.where(Yu==Y[i])] = Z[i]

2) A list comprehension and numpy.sort() funtion
This solution - which is a bit more involved than the previous one - relies on Numpy's structured arrays:
data_type = [('x', np.float), ('y', np.float), ('z', np.uint8)]
XYZ = [(X[i], Y[i], Z[i]) for i in range(len(X))]
table = np.array(XYZ, dtype=data_type)
Zimg = np.sort(table, order=['y', 'x'])['z'].reshape(Xu.size, Yu.size)

3) Vectorization
Using lexsort is an elegant and efficient way of performing the required task:
Zimg = Z[np.lexsort((Y, X))].reshape(Xu.size, Yu.size)

4) Pure Python, not using NumPy
You may want to check out this link for a pure Python solution without any third party dependencies.

To end up, you have different options to save Zimg as an image:
from PIL import Image
Image.fromarray(Zimg).save('z-pil.png')

import matplotlib.pyplot as plt
plt.imsave('z-matplotlib.png', Zimg)

import cv2
cv2.imwrite('z-cv2.png', Zimg)

import scipy.misc
scipy.misc.imsave('z-scipy.png', Zimg)

A: You said you needed no interpolation is needed since every grid point is covered. So I assume the points are equally spaced.
If your table is already sorted primary by increasing x and secondary by y you can simply take the Z array directly and save it using PIL:
import numpy as np
# Find out what shape your final array has (if you already know just hardcode these)
x_values = np.unique(X).size
y_values = np.unique(Y).size
img = np.reshape(Z, (x_values, y_values))

# Maybe you need to cast the dtype to fulfill png restrictions
#img = img.astype(np.uint) # alter it if needed

# Print image
from PIL import Image
Image.fromarray(img).save('filename.png')

If your input isn't sorted (it looks like it is but who knows) you have to sort it before you start. Depending on your input this can be easy or really hard.

A: np.ufunc.at  is a good tool to manage duplicates in vectorized way.
Suppose these data :
In [3]: X,Y,Z=rand(3,10).round(1)

(array([ 0.4,  0.2,  0.1,  0.8,  0.4,  0.1,  0.5,  0.2,  0.6,  0.2]),
 array([ 0.5,  0.3,  0.5,  0.9,  0.9,  0.5,  0.3,  0.6,  0.4,  0.4]),
 array([ 0.4,  0.6,  0.6,  0.4,  0.1,  0.1,  0.2,  0.6,  0.9,  0.8]))

First scale the image (scale=3 here) :
In [4]: indices=[ (3*c).astype(int) for c in (X,Y)]

[array([1, 0, 0, 2, 1, 0, 1, 0, 1, 0]), array([1, 0, 1, 2, 2, 1, 0, 1, 1, 1])]

Make a empty image  : image=zeros((3,3)), according to indices bounds.
Then build. Here we keep the maximum.
In [5]: np.maximum.at(image,indices,Z)  # in place

array([[ 0.6,  0.8,  0. ],
       [ 0.2,  0.9,  0.1],
       [ 0. ,  0. ,  0.4]])

Finally save in PNG : matplotlib.pyplot.imsave('img.png',image)


text:
Q: MySQL IF/WHEN/ELSE/OR In MySQL, I'm trying to retrieve a single row from a database, unless it doesn't exist, in which case I want it to retrieve the second row. I've got the code written out, but for some reason it's retrieving both rows. If the first row is not found, it retrieves the second row. So regardless it always retrieves the second row.
SELECT *
FROM `members`
WHERE
`id` = 49
or `id` = 0

I've tried many variations (when/then/else, etc) on different databases with different columns, and it always retrieves both rows.
How can I retrieve just the one row that I need? And also, can anyone explain to me why it does this?

A: Which is the row that you want first?  id = 49?
You could try using mysql's ORDER BY combined with a LIMIT to get your desired results. For example if you wanted to get id 49 first you could do:
SELECT * FROM members WHERE id = 49 OR id = 0 ORDER BY FIELD(id, 49, 0) LIMIT 1
This will order the results by the field id but limit the results to only a single row.  So if there exists no row with id = 49 it'll still get the first row in your list which would be id = 0

A: An alternative approach is to use union all with some logic for verification:
SELECT m.*
FROM members m
WHERE id = 49
UNION ALL
SELECT m.*
FORM members m
WHERE id = 0 AND NOT EXISTS (SELECT 1 FROM member m2 WHERE m2.id = 49);

Under some circumstances, this could be marginally faster.

A: You can order by statements:
ORDER BY (id = 49) DESC

The DESC because (id = 49) is 1 for the row you want first.
If you only want 1, LIMIT 1. If you want more, you can chain these into custom sorting:
ORDER BY (id = 14) DESC, (id = 43) DESC, (id = 49) DESC LIMIT 3

etc.
Very easy to remember.


text:
Q: Delay when using AudioQueueStart() I am using the Audio Queue services to record audio on the iPhone. I am having a latency issue though when starting recording. Here is the code (approx):
OSStatus status = AudioQueueNewInput(
     &recordState.dataFormat, // 1
     AudioInputCallback, // 2
     &recordState,  // 3
     CFRunLoopGetCurrent(),  // 4
     kCFRunLoopCommonModes, // 5
     0,  // 6
     &recordState.queue);  // 7

// create buffers
for(int i = 0; i < NUM_BUFFERS; i++)
{
    if (status == 0)
        status = AudioQueueAllocateBuffer(recordState.queue, BUFFER_SIZE, &recordState.buffers[i]);
}

DebugLog(@"Starting recording\n");
OSStatus status = 0;
for(int i = 0; i < NUM_BUFFERS; i++)
{
    if (status == 0)
        status = AudioQueueEnqueueBuffer(recordState.queue, recordState.buffers[i], 0, NULL);
}
DebugLog(@"Queued buffers\n");
if (status == 0)
{
    // start audio queue
    status = AudioQueueStart(recordState.queue, NULL);
}
DebugLog(@"Started recording, status = %d\n", status);

The log output looks like this:
2009-06-30 19:18:59.631 app[24887:20b] Starting recording
2009-06-30 19:18:59.828 app[24887:20b] Queued buffers
2009-06-30 19:19:00.849 app[24887:20b] Started recording, status = 0

Note the 1-second delay between the "Queued Buffers" message and 2nd "Starting recording" message. Any ideas how I can get rid of it, apart from starting recording as soon as I start my app?
BTW, the 1-second is pretty consistent in the Simulator and Device, and doesn't seem to be affected by number or size of buffers. Using good old mono 16-bit PCM.

A: Mike Tyson covers this in his blog.
However, if you're looking to quickly start recording you would do better to use a remote audio unit, or AVAudioEngine.


text:
Q: Where am I wrong in determining Parallel vs Perpendicular? I am quoting Mathematics for Economists by Simon and Blume (page 347, Theorem 15.5) here.

The vector $\mathbf{v}=(v_1,v_2)$ points in the direction parallel to the tangent line to the level set of $G$ at $(x_0,y_0)$ if and only if $$DG(x_0,y_0)\cdot\mathbf{v}=\frac{\partial G}{\partial x}(x_0,y_0)v_1+\frac{\partial G}{\partial y}(x_0,y_0)v_2=0,$$ where $DG(x_0,y_0)=(\frac{\partial G}{\partial x}(x_0,y_0),\frac{\partial G}{\partial y}(x_0,y_0))$.

But, if we take $$\mathbf{v}=\left(1,-\frac{\frac{\partial G}{\partial x}(x_0,y_0)}{\frac{\partial G}{\partial y}(x_0,y_0)}\right),$$ $DG(x_0,y_0)\cdot\mathbf{v}=0$, but $DG(x_0,y_0)$ and $\mathbf{v}$ are perpendicular!
Where am I wrong?

A: The gradient $DG$ is perpendicular to the tangent line $T$. Since you are working in the plane statement from the book is perfectly correct:
$$ v \perp DG \iff v \parallel T. $$
PS: Recall that $v\cdot w = 0 \iff v\perp w$.


text:
Q: Assembly 8086 about dw instruction I'm working with 8086 proccessor, Is it possible to change the value of a word I first declared on the top?
Like this
;_____Variables_____;
X dw 0
;_____code_____;
(...)
mov ax, 65535
mov X, ax

Thanks in advance.


text:
Q: ZF2 form file upload. best practice: don't reupload file on item edition I had this problem many times before and I want like to have advices about what will be the best to deal with that:
I have a form to create a new item with label, description, etc ... and with an input file in order to upload a document; this last field is mandatory.
When I want to edit this item (so after saving it first into a db or whatever) I want the file field to not be mandatory anymore and if the user doesn't select a new file, I will keep the previous filename here.
So what's the best way to do that with Zend Framework 2 ? I already have my model, form and input filters set and everything is working well.
I was thinking about:
- having a different inputFilter configuration in edition mode,
- or having a validator for the input field checking that a filename was not already set for the entity attached to the form,
- or storing the current filename in a input hidden field (not really secure like that)
- or ???
Thank you in advance and have a nice day

A: You can simply change input filter in controller
$form = new \Zend\Form\Form();
$filters = $form->getInputFilter();
$filters->remove('file');
$filters->add(array(
    'name' => 'file',
    'required' => true,
    //...
));

or you can make function with this logic in input filter class


text:
Q: How to scale image in high quality and draw it to canvas I have a PNG image in app's resources, that has 950*291 pixels, placed in drawable-mdpi directory. I want to create an in-memory Bitmap, where I want to draw it scaled down (actually 100 pixels high). I tried many ways, but it looks pixelated.
I tried the following:

*

*Load it as BitmapDrawable, enabled AntiAlias and FilterBitmap and called it's draw method.

*Load it using BitmapFactory.decodeResource with opts.inScaled set to fales and drawn to canvas using Matrix.

*Same as previous, but first scaled it down using Bitmap.createScaledBitmap and then drawing to canvas without a matrix.

Neither worked. This is the image I get, it is not smooth, is pixelated:

It seems that Paint.setFilterBitmap does have some effect, because without it it's even a bit worse:

This is the scaled down version using just any image editor using the same original image, which is a lot smoother.

Am I not able to scale images in higher quality with Android? The image clearly stands out to other antialiased text in the image.
This is my current code:
// create in-memory bitmap
Bitmap bitmap = Bitmap.createBitmap(1000, 1100, Bitmap.Config.RGB_565);
bitmap.setDensity(Bitmap.DENSITY_NONE);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setFilterBitmap(true);
paint.setAntiAlias(true);

// load the original image
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScaled = false;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap logoBitmap = BitmapFactory.decodeResource(resources, R.drawable.main_logo, opts);
logoBitmap.setDensity(Bitmap.DENSITY_NONE);

// scale it down and draw it
Bitmap scaledLogo = Bitmap.createScaledBitmap(logoBitmap, logoWidth, logoHeight, false);
canvas.drawBitmap(scaledLogo, x, y, paint);

Tested on Android 5.0. I worked it around by adding scaled version to resources, but want to know what was wrong.


text:
Q: How to determine the type without instantiating the object? in java
public class GenericUtil<T> {

    public boolean judge(){
        return T instanceof Application;
    }
}

in kotlin
class GenericUtil<T> {
    fun judge(): Boolean {
        return T is Application
    }
}

I just want to determine if the generic T is an object type...

A: Its not possible, however, you can use reflection:
public class GenericUtil<T> {
    private final Class<T> clazz;

    public GenericUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    public boolean judge(){
        return Application.classisAssignableFrom(clazz);
    }
}


text:
Q: how to insert data in my sql using else if in jsp Hi  I'm trying to insert data in mysql but my page throw no response!
pease can anyone help me about it?
Code runs but println() is not displaying
  //<%@page import= "java.sql.*"%>

   // <%@ page import="java.util.Random"%>

    <%

        String dt = request.getParameter("dt");

        String particular = request.getParameter("vas");

        String emp = request.getParameter("emp");

        String amt = request.getParameter("amt");

        int amnt = Integer.parseInt(amt);

        //Class.forName("com.mysql.jdbc.Driver");

        //Connection con = //DriverManager.getConnection("jdbc:mysql://localhost:3306/furqania", "root", "khan");

        Statement st = con.createStatement();

        if (particular == "amanatraseedi")
     {
            Random rnd = new Random();

            int rn = rnd.nextInt(9000) + 10000;

            String sr = "AMT" + rn;

           // int i = st.executeUpdate("insert into      amanatraseedi='"+particular+"'(transactionid,dt,amount,empid) values('" + sr + "','" + dt + "','" + amnt + "','" + emp + "')");

            if (i > 0) {
                out.println("Amanat raseedi successful!");

            } else {

                out.println("something went wrong!");

            }
        }
        else if (particular == "amadhisab")
     {
            Random rnd = new Random();

           int rn = rnd.nextInt(9000) + 10000;
                    String sr = "AMD" + rn;
            int i = st.executeUpdate("insert into amadhisab='"+particular+"' (transactionid,dt,amount,empid) values('" + sr + "','" + dt + "','" + amnt + "','" + emp + "')");

            if (i > 0) {

               out.println("Amad hisab successful!");

       }
         else {

               out.println("something went wrong!");
                }
        }
        st.close();
        con.close();
    %>


text:
Q: MUITableHead color overriden by palette.text.color I want to use a different color for TableHead cells and TableBody cells. I have added the custom theme for both but the TableHead colors are being overridden by the palette.text.color.
How can I fix this?
const theme = createTheme({
  palette: {
    text: {
      primary: "green"
    }
  },
  components: {
    MuiTableHead: {
      styleOverrides: {
        root: {
          color: "red"
        }
      }
    }
  }
});

Working Example: https://codesandbox.io/s/focused-northcutt-nbstkr
Thanks

A: If the goal is to override color of the table header cells from the theme, try override styles on MuiTableCell instead of on MuiTableHead.
There is a head property under MuiTableCell for attaching any styles to the cells on header.
Tested on forked demo here: codesandbox
Example:
const theme = createTheme({
  palette: {
    text: {
      primary: "green"
    }
  },
  components: {
    MuiTableCell: {
      styleOverrides: {
        head: {
          color: "red"
        }
      }
    }
  }
});


text:
Q: In tig, is there a way to view diff for all files like Github pull request In tig, when showing diff view, we can only view diff per commits. What I want to achieve is a way to view diff for all files (just like git diff or Github Pull Request diff view). Is there a way or a mode to do that?
 Example image: https://i.imgur.com/evIe71O.png

A: Don't know what you mean all files. diff view is already a pager for git diff.
If you want to increase chunk context, just press ] or set it in .tigrc like
set diff-context = 300 # Number of lines to show around diff changes (diff)


text:
Q: Is vps server or dedicated server possible as fax server? I want the mail to fax .
I am currently using the alltofax.de to send fax from a mail.
I want to know if I can build a fax server on my dedicated server.
I studied about Hylafax, but said that modem should be connected.
Does this mean a physical modem?
I can't install modem equipment because I use cloud hosting server.
Can I build a fax (mail to fax) server on a cloud hosting server (dedicated server)?

A: Normally, when people talk about fax, they mean Group 3 Fax as standardized by ITU-T.
Other fax standards, like Group 4 Fax over ISDN, never gained any significance.
Group 3 Fax is a protocol to send images over the telephone network using audible frequencies (tones).
This implies that a fax server needs a connection to the telephone network, and a way to convert the image data to audible frequencies and back. The latter is called a modem.
Both of these requirements can be fulfilled in several ways, separately or together.
The classic telephone network (POTS) uses analog transmission over copper wire pairs. To connect such a line to a computer you need a physical modem, which will also take care of the conversion between data and tones. Physical modems exist in many forms, from classic standalone devices connecting to the computer via RS232 serial interfaces to plugin cards installed in an expansion slot of the computer itself or of a different device such as a router. It is theoretically feasible to have a modem in a router forward fax data over an IP network to a cloud server, though I have never heard of such a solution in actual use. So in practice, for a POTS fax server you cannot bypass the requirement of installing a physical modem next to or inside it, and running a phone line to it.
The newer digital telephone network (ISDN) uses digital transmission, still over copper wire pairs. To connect such a line to a computer you need a physical device called a terminal adapter (TA). Such a TA may or may not include a modem. If it doesn't, the computer can implement the modem function in software, computing the waveform of the tones to send and analyzing the waveform of the tones received. TAs come in basically the same forms as modems. There are devices comprising a TA and a router which forward the raw digital phone signal over an IP network, so you could theoretically build an ISDN fax server out of such an ISDN to IP gateway and a cloud server running a software modem. You'd still need a location with an Internet connection for that gateway, and an ISDN line running to it.
The most modern telephone network is Voice over IP (VoIP). With VoIP, the tones are transmitted over IP networks anyway, so there is no need for physical adapters apart from a regular network interface. Therefore it is possible to build a VoIP fax server on a cloud server. You'd need a contract with a VoIP provider to route the fax calls between the phone network and your server via SIP, software to implement the modem functionality as well as the fax protocol, and sufficient computing power to run it. Whether such a solution makes any sense economically compared to a professional fax service provider such as alltofax.de is an entirely different question.


text:
Q: Trump's use of "our" when "the" would do Mr. Trump and his spokesperson seem to favor the word OUR, as in our great military or our nation when THE nation might do. Is there a signal or purpose for this usage?

A: With regard to inclusiveness, Winston Churchill did much the same seventeen days after taking over as Prime Minister on the 10th of May, 1940 (eight months after the beginning of the Second World War) when he made a brief statement to the Commons on 28 May reporting the Belgian capitulation, and concluding:

Meanwhile, the House should prepare itself for hard and heavy tidings. I have only to add that nothing which may happen in this battle can in any way relieve us of our duty to defend the world cause to which we have vowed ourselves; nor should it destroy our confidence in our power to make our way, as on former occasions in our history, through disaster and through grief to the ultimate defeat of our enemies.

Having spoken to the House of Commons, thus, and having assumed their unity of purpose he then included not only the people of Great Britain but the nations which (at that time) encircled the globe in Commonwealth:

We shall go on to the end. We shall fight in France, we shall fight on the seas and oceans, we shall fight with growing confidence and growing strength in the air, we shall defend our island, whatever the cost may be. We shall fight on the beaches, we shall fight on the landing grounds, we shall fight in the fields and in the streets, we shall fight in the hills; we shall never surrender [...].

Then, including the 'Empire' and also the 'New World' - meaning the USA in particular - he continued:

and if, which I do not for a moment believe, this island or a large part of it were subjugated and starving, then our Empire beyond the seas, armed and guarded by the British Fleet, would carry on the struggle, until, in God's good time, the New World, with all its power and might, steps forth to the rescue and the liberation of the old.

Wikipedia

You ask 'is there a signal or purpose' to the present inclusiveness expressed by POTUS ? And that is why I have quoted Winston Churchill at length for the world faces a far more destructive force now than it did in 1939-45.
Now, by using technology that has become all too accessible, a rogue state  threatens the entire globe and attempts to push the whole of humanity towards an unthinkable precipice, while those closest to it seem reluctant to repress such ambitions.
And its solicitations regarding Olympic Games could as well be an attempt to drive a wedge between the whole peninsula and the rest of the world, or as well be a mere truculent response to sanctions, than they might be a genuine step towards a better peace.
I think that the President of the United States (whoever that happens to be at the present time) is quite right to attempt to gather the USA into one and is quite right to seek international allies in order to maintain the balance of power in this most dangerous world in which we live.

A: He is being precise.
There are in fact many great militaries, and many nations in the world, and while from context it is unlikely that Trump is referring to any other than the US, he is more technically clear in saying "our" rather than "the". Especially if you realize that some of Trump's listeners are international. Reminding people that they are part of the nation never hurt a politician either.


text:
Q: Can't get weather data from API using angular components I want to create a simple weather app using angular 2, just to learn this framework.
I've got GraphsComponent, where I'm going to draw temperature chart.
import { Component, OnInit } from '@angular/core';

import { WeatherAPIService } from './weatherAPI.service';

@Component({

  selector: 'my-graphs',

  template: '
Charts for {{this.weatherAPIService.cityName}}
',

  providers: [WeatherAPIService]
})

export class GraphsComponent implements OnInit {

    weatherData = {};
    cityName: string = "";

    constructor(
                    private weatherAPIService: WeatherAPIService,
              ) { }

    ngOnInit(): void {
        this.weatherAPIService.getWeather("London").then(data => this.weatherData = data);
        console.log(this.weatherData);  //wrong data
      }

}

I also have a WeatherAPIService, which provides weather data:
import { Injectable } from '@angular/core';

@Injectable()
export class WeatherAPIService {

    weatherData = {};
    cityName: string = "";

    getWeatherHelper (city: string) {
      var locationData = new Object();
        $.get("https://maps.googleapis.com/maps/api/geocode/json?address=" + city, function (data) {

           locationData['latitude'] = data.results[0].geometry.location.lat;  //latitude
           locationData['longitude'] = data.results[0].geometry.location.lng;  //longitude

            $.ajax({
                url: "https://api.darksky.net/forecast/[MyAPIKey]/" + locationData['latitude'] + ',' + locationData['longitude'],
                dataType: "jsonp",
                success: function (data) {
                    //alert("The temperatute in " + city + " is " + data.currently.temperature);
                    this.weatherData = data;
                    this.cityName = city;
                    console.log(data);  //good data
                    return data;
                }

            });

        }
    }

    getWeather(city: string): Promise<string[]> {
        return Promise.resolve(this.getWeatherHelper(city));
    }

  }

I want to get weather data to display it.
In getWeatherFunction, I use 2 APIs:
- Google geocoding to get latitude and longitude of the city i want weather for
- DarkSky to get the weather (it requires latitude and longitude)
The problem is the fact, that getting location and weather from APIs is asynchronous, so getWeatherHelper() finishes before the data is returned.
That's why I added weatherData and cityName in WeatherAPIService, but even though these variables have proper data after data from APIs is returned, cityName is not displayed in the template of GraphsComponent. Why is that? How should situations like this be handled? Where should I actually store the information from weather API? In the component or in the service?
As you can see, I used promise, because I thought it would get me the data after it is collected form API, but it doesn't.
As you probably noticed, I'm really new to angular, so please try to answer in the way, that I could understand it.
I know as much as I learned from official angular 2 tutorial ("Tour of heroes").

A: Apart from you mixing in jQuery, you're losing the this context, when using function. I'd suggest using a lambda expression, which preserves said context, so you can actually save the data.
So instead of using
function (data) {

start using a lambda, wherever you need an inline function:
(data) => {

Applied to your code:
getWeatherHelper (city: string) {
  var locationData = new Object();
    $.get("https://maps.googleapis.com/maps/api/geocode/json?address=" + city, (data) => {

       locationData['latitude'] = data.results[0].geometry.location.lat;  //latitude
       locationData['longitude'] = data.results[0].geometry.location.lng;  //longitude

        $.ajax({
            url: "https://api.darksky.net/forecast/[MyAPIKey]/" + locationData['latitude'] + ',' + locationData['longitude'],
            dataType: "jsonp",
            success: (data) => {
                //alert("The temperatute in " + city + " is " + data.currently.temperature);
                this.weatherData = data;
                this.cityName = city;
                console.log(data);  //good data
                return data;
            }

        });

    });
}


text:
Q: Include Next.js app bundles in main html files I am converting React client-side rendering to SSR using Next.js but unable to load bundled files in my main view file.
These are not working on my end.
<link rel="stylesheet" href="/js/bundles/server-side-components/out/_next/static/css/*.css" />
<link rel="preload" href="/js/bundles/server-side-components/out/_next/static/chunks/*.js" as="script" />
<link rel="preload" href="/js/bundles/server-side-components/out/_next/static/chunks/pages/*.js" as="script" />

Background:

*

*I am using laravel and frontend React.js.

*In laravel view (blade file). I have included react bundle file like this.

*<script type="text/javascript" src="/js/bundles/SocialApp/dist/main.bundle.js?v=xxxx.xxx" async></script>

*Everything is working fine.

*For performance, I wanted to move some components to Server-Side Rendering with Next.js.

*I have removed the specific routes from react and moved these components to Next.js directory Pages folder. For Exmaple, If I wanted to move /example route to SSR then, I have created a file with the same name (example.js) into pages directory of next.js and compiled the code.

*If I start next.js server separately, like http://localhost:3000/example. Server-Side rendering working perfectly fine. but I don't want to start next.js server separately and wanted to include build files into my main directory like I am doing with react bundles.

*How can I achieve my goal?


text:
Q: Expressing a $2\times 2$ matrix as a single equation. From another question (Verifying a Linear transformation from M 2,2 -> R) I saw the following proof which shows that
$$T(kv)=kT(v)$$
$$T(kv)=T\left(\begin{bmatrix}k\cdot a&k\cdot b\\k\cdot c&k\cdot d\end{bmatrix} \right)=ka+kb-kc+kd=k(a+b-c+d)=kT(v)$$
But I am wondering exacly what property of matrices gives this equality? $$T\left(\begin{bmatrix}k\cdot a&k\cdot b\\k\cdot c&k\cdot d\end{bmatrix} \right)=ka+kb-kc+kd$$
Would the example below also be true?
$$\begin{bmatrix}1&3\\5&7\\\end{bmatrix} = 1+3-5+7 = 6$$

A: I think you've slightly misunderstood the other question.
$T:M_{2\times 2}(\mathbb{R}) \to \mathbb{R}$ is a map from the vector space $(M_{2\times 2}(\mathbb{R}), +, \cdot, \boldsymbol{0}, \mathbf{I}, \mathbb{R})$ to its scalar field $\mathbb{R}$, defined by
$$T : \begin{bmatrix} a &b \\c &d\end{bmatrix} \mapsto a+b-c+d$$
The previous question asks whether this map is a linear form (a.k.a. a covector). A linear form must satisfy linearity, i.e. for all $\mathbf{A}, \mathbf{B} \in M_{2\times 2}(\mathbb{R})$, and for all $k \in \mathbb{R}$,

*

*$T(\mathbf{A}) + T(\mathbf{B}) = T(\mathbf{A} + \mathbf{B})$

*$kT(\mathbf{A}) = T(k\mathbf{A})$
This transformation does satisfy the above criteria, and so is a linear form.
This, however, is not due to any property of matrices (indeed, $M_{2\times 2}(\mathbb{R})$ is isomorphic to $\mathbb{R}^4$, and so each of these matrices can be replaced with a Cartesian vector) but instead the definition of $T$.
In your example, it is true that
$$T\left(\begin{bmatrix}1&3\\5&7\\\end{bmatrix}\right) = 1+3-5+7 = 6$$