text:
Q: how to add text on each rectangle in collection using matplotlib? I am using matplotlib for plotting and convenient visualization of some graphs in xy coordinates.
I need to highlight some regions - and I use rectangles for this.
But I am interested to add some text upon each rectangle - to be able to distinguish those regions. How to do it using patches because I have a lot of objects in a plot?
Here is the code I use to plot rectangles:
# sample data for rectangles visualization
windows_df = pd.DataFrame( {'window_index_num': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}, 'left_pulse_num': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}, 'right_pulse_num': {0: 2, 1: 3, 2: 4, 3: 5, 4: 6, 5: 7, 6: 8, 7: 9, 8: 10, 9: 11}, 'idx_of_left_pulse': {0: 0, 1: 4036, 2: 4080, 3: 4107, 4: 4368, 5: 4491, 6: 4529, 7: 4624, 8: 4626, 9: 4639}, 'idx_of_right_pulse': {0: 4080, 1: 4107, 2: 4368, 3: 4491, 4: 4529, 5: 4624, 6: 4626, 7: 4639, 8: 4679, 9: 4781}, 'left_pulse_pos_in_E': {0: 10.002042118364418, 1: 40.29395464818188, 2: 41.19356816747343, 3: 41.76060061888303, 4: 47.90221207147802, 5: 51.27679395217831, 6: 52.39165780468267, 7: 55.37561818764979, 8: 55.47294132608167, 9: 55.99635666692289}, 'right_pulse_pos_in_E': {0: 41.19356816747343, 1: 41.76060061888303, 2: 47.90221207147802, 3: 51.27679395217831, 4: 52.39165780468267, 5: 55.37561818764979, 6: 55.47294132608167, 7: 55.99635666692289, 8: 57.33777021469516, 9: 60.984834434908144}, 'idx_window_left_border': {0: 0, 1: 3990, 2: 4058, 3: 4093, 4: 4237, 5: 4429, 6: 4510, 7: 4576, 8: 4625, 9: 4632}, 'idx_window_right_border': {0: 4094, 1: 4238, 2: 4430, 3: 4510, 4: 4577, 5: 4625, 6: 4633, 7: 4659, 8: 4730, 9: 4792}, 'left_win_pos_in_E': {0: 10.002042118364418, 1: 39.38459790393702, 2: 40.74003692229216, 3: 41.46513255508269, 4: 44.66179219947279, 5: 49.53272998148, 6: 51.82972979173252, 7: 53.82159300113625, 8: 55.40803086073492, 9: 55.76645477820397}, 'right_win_pos_in_E': {0: 41.48613320837913, 1: 44.6852679849016, 2: 49.56014983071213, 3: 51.82972979173252, 4: 53.85265044341121, 5: 55.40803086073492, 6: 55.79921126600202, 7: 56.66110947958804, 8: 59.119140585251095, 9: 61.39880967219205}, 'window_width': {0: 4095, 1: 249, 2: 373, 3: 418, 4: 341, 5: 197, 6: 124, 7: 84, 8: 106, 9: 161}, 'window_width_in_E': {0: 31.48409109001471, 1: 5.300670080964579, 2: 8.820112908419965, 3: 10.364597236649828, 4: 9.190858243938415, 5: 5.875300879254915, 6: 3.9694814742695, 7: 2.8395164784517917, 8: 3.7111097245161773, 9: 5.632354893988079}, 'sum_pulses_duration_in_E': {0: 0.5157099691135514, 1: 0.5408987779694527, 2: 0.6869248977656355, 3: 0.7304908951030242, 4: 0.7269657511683718, 5: 0.537271616198268, 6: 0.7609034761658222, 7: 0.6178183490930067, 8: 0.8269277926972265, 9: 0.5591109437337494}, 'sum_pulse_sq': {0: 3.7944375922206044, 1: 3.8756992116858715, 2: 2.9661915477796663, 3: 3.070559830941317, 4: 3.0597037730539385, 5: 10.2020204659669, 6: 45.77535573608872, 7: 45.87630607524008, 8: 39.10335270063814, 9: 3.437205923490125}, 'pulse_to_window_rate': {0: 0.01638001769335214, 1: 0.10204347180781788, 2: 0.07788164447530765, 3: 0.0704794290047244, 4: 0.0790966122938326, 5: 0.09144580460471718, 6: 0.1916883807363909, 7: 0.2175787158769594, 8: 0.22282493757444324, 9: 0.09926770493999569}, 'max_height_in_window': {0: 20.815950580921104, 1: 20.815950580921104, 2: 5.324888970962656, 3: 5.324888970962656, 4: 5.14075603114903, 5: 86.81228155905252, 6: 110.06755904473022, 7: 110.06755904473022, 8: 110.06755904473022, 9: 14.735092268739246}, 'min_height_in_window': {0: -0.011928180619527797, 1: 1.6172637244080776, 2: 1.6172637244080776, 3: 0.8658702248969847, 4: 0.8658702248969847, 5: 0.8658702248969847, 6: 1.8476229914953515, 7: 2.918666252051556, 8: 3.2397786967451707, 9: 2.4893555139463266}, 'windows_sq': {0: 655.3712842149647, 1: 110.33848645112575, 2: 46.96612194869083, 3: 55.19032951390669, 4: 47.24795994896218, 5: 510.0482741740266, 6: 436.911136546121, 7: 312.538647650477, 8: 408.4727887246568, 9: 82.9932690531994}} )

fig_w, axs_w = plt.subplots()

#theoretical cross-section
#axs_w.plot(df_wo_NANS['E'], df_wo_NANS['theo_cs'], marker = "o", markersize = 1, linewidth = 1.0, alpha=0.6, color = 'green', label = 'Theo Cross Section')
axs_w.grid(color = 'grey', linestyle = '--', linewidth = 0.2)

#windows rectangular
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
boxes = []

for index,row in windows_df.iterrows():
    current_rect_left_corner = (row['left_win_pos_in_E'], row['min_height_in_window'])
    current_w = row['window_width_in_E']
    current_h = row['max_height_in_window']-row['min_height_in_window']

    boxes.append(Rectangle(current_rect_left_corner, current_w, current_h))

    left = row['left_win_pos_in_E']
    right = row['right_win_pos_in_E']
    bottom = row['min_height_in_window']
    top = row['max_height_in_window']

    #mark of the start of the current window
    axs_w.text(
        left, #left corner,  #0.5*(left+right), #middle of the rectangle
        top, #top
        str(index),
        horizontalalignment='center',
        verticalalignment='center',
        fontsize=5
        )

    #mark of the end of the current window
    axs_w.text(
        right, #right corner,  #0.5*(left+right), #middle of the rectangle
        top+0.5*bottom, #top
        str(index)+'e',
        horizontalalignment='center',
        verticalalignment='center',
        fontsize=5
        )

pc = PatchCollection(boxes, facecolor='y', alpha=0.2, edgecolor='black')
axs_w.add_collection(pc)

Added text marks using cycle but is it possible to do it using patch and collections to make more efficient code?


text:
Q: React Component Array not updating when value is changed I have an array of react hook instances. In this, I'm passing along a state value. When this state value is updated though, it does not reflect in those instances, it just keeps whatever the state was on creation.
        let newCircle = (
            <Annotation
                key={selected_image.annotations.length + 1}
                originX={x}
                originY={y}
                label={selected_label}
                image={selected_image}
                getMoveBtn={getMoveBtn}
                moveBtn={moveBtn}
            />
        )

^ This is the object creation.
The value I'm trying to access inside the object is "moveBtn". I've tried passing in a function that gets the value as well, however that does the same, just gets the value it had at creation.
import React, {useState} from "react";

const Annotation = (props) => {

    const {
        label,
        image,
        originX,
        originY,
        getMoveBtn,
        moveBtn
    } = props;

  const [position, setPosition] = useState({
    x: originX,
    y: originY,
    active: false,
    offset: { }
  });

  const handlePointerDown = (e) => {

    const element = e.target;
    const boundingbox = e.target.getBoundingClientRect();
    const x = e.clientX - boundingbox.left;
    const y = e.clientY - boundingbox.top;
    element.setPointerCapture(e.pointerId);
    var movable = getMoveBtn();
    console.log("move = ",movable)
    setPosition({
      ...position,
      active: true,
      offset: {
        x,
        y
      }
    });
  };
  const handlePointerMove = e => {
    const boundingbox = e.target.getBoundingClientRect();
    const x = e.clientX - boundingbox.left;
    const y = e.clientY - boundingbox.top;
    if (position.active) {
      setPosition({
        ...position,
        x: position.x - (position.offset.x - x),
        y: position.y - (position.offset.y - y)
      });
    }
  };
  const handlePointerUp = e => {
    setPosition({
      ...position,
      active: false
    });
  };

  return (
    <g id={label.title + "-g-" + (image.annotations.length + 1)}>

        <circle
            id={label.title + "-circle-" + (image.annotations.length + 1)}
            parent={label.id}
            type="circle"

            cx={position.x}
            cy={position.y}
            r={5}
            onPointerDown={(e) => handlePointerDown(e)}
            onPointerUp={handlePointerUp}
            onPointerMove={handlePointerMove}

            onClick={function() { console.log(moveBtn)}}
            stroke='black'
            strokeWidth={1}
            fill={label.color}
        />
        <text
            x={position.x+5}
            y={position.y-5}
            className='annotation-text'
        >
            {label.title}
        </text>
    </g>

  );
};

export default Annotation;

This is the component's code. You can see I'm trying to get it on line 28/29.
How do I allow it to use the current value?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configure private network with static IP for Snappy on Vagrant I am trying to run Vagrant box ubuntu/ubuntu-15.04-snappy-core-stable with two adapters NAT and Host-Only but that does not work with this config:
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/ubuntu-15.04-snappy-core-stable"
  config.vm.box_check_update = false
  config.ssh.forward_agent = true

  config.vm.network "forwarded_port", guest: 22, host: 2222, id: 'ssh', auto_correct: true
  config.vm.network "private_network", ip: "192.168.33.10", auto_correct: false
  config.ssh.username = "ubuntu"
  config.ssh.host = "192.168.33.10"
end

Result:
> vagrant destroy --force; vagrant up
==> default: Forcing shutdown of VM...
==> default: Destroying VM and associated drives...
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu/ubuntu-15.04-snappy-core-stable'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: test_default_8376498
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 192.168.33.10:2222
    default: SSH username: ubuntu
    default: SSH auth method: password
    default: Warning: Connection timeout. Retrying...
    default: Warning: Host appears down. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Host appears down. Retrying...
    default: Warning: Connection timeout. Retrying...
    default: Warning: Host appears down. Retrying...
    default: Warning: Connection timeout. Retrying...

A: We have a vagrant image directly available so that you don't have to jump into those hurdles!
If you download and install the image we present you in https://developer.ubuntu.com/en/snappy/start/#vagrant, you can simply connect to your vagrant image through vagrant ssh once the image is started.


text:
Q: Writing git branches in a file I am looking for a Bash script to write 'all' my git repository branches in a file as follow :
branches=origin/master,origin/master/feature/f1,origin/develop/feature/f2
something like following bash :
#!/bin/bash
cd /home/jenkins/mfnp
git fetch --all
git pull
git branch -r | awk '/origin\/MFNP/{printf "%s,", $1 }' | head -c -1 >>/home/jenkins/branches.properties
echo "" >> /home/jenkins/branches.properties

But this one doesn't work. anybody can fix it for me ?  or give me solution like this .

A: This worked for me:
git branch -r | sed 's/^/branches=/' | sed '/->/d' | tr '\n' ',' | tr -d ' ' >> /home/jenkins/branches.properties
May well be a more elegant solution but that does remove line breaks and excess spaces from the output of the git branch -r command. Hope it helps.
EDIT: the sed addition removes any line containing '->' so it should work no matter which branch you're working on when you run the command. Hope that sorts it for you.
EDIT 2: done :)


text:
Q: Import from Another Directory is Failing in Python I read that to use a python file as a module for import, I need to put __init__.py in the directory.
I have the following directory structure:
data_load
    -- __init__.py
    -- rand_data.py

etc
    -- __init__.py
    -- test.py

In test.py I import a class defined in rand_data and I get the error:
python test.py
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    from data_load.rand_data import RandData
ModuleNotFoundError: No module named 'data_load'

A: change to the parent directory of etc and data_load and type
python -m etc.test

This should do the job.
Here a small test case (Assuming you're on a linux machine)
## create the test case
mkdir -p import_issue/data_load import_issue/etc
touch import_issue/data_load/__init__.py import_issue/etc/__init__.py
echo 'print("I am", __name__)' > import_issue/etc/test.py
echo 'from data_load.rand_data import RandData' >> import_issue/etc/test.py
echo 'print("Randdata = ", RandData)' >> import_issue/etc/test.py
echo "class RandData:" > import_issue/data_load/rand_data.py
echo '    pass' >> import_issue/data_load/rand_data.py
#
# now perform the test
cd import_issue
python -m etc.test

The reason why things in your initial example didn't work out as expected is, that you present working directory was probably etc
and if you load a python script in etc, then it tries to import load_data relative to the present working directory (etc) and below etc there is no directory named rand_data, that has a file __init__.py in it.
My suggestion to fix is to go up to the common parent directory (This will now be your present working directory) and import etc/test as a module.
The reason is, that  test.py is in a directory etc with an init.py so you should import it as etc.test and not call it directly.
Calling a file, that is a module directly with etc/test.py is not really recommended and can provoke some rare confusing situations.

A: instead of running command in etc directory  python test.py run the python script in parent directory of etc and data_load.
ie what you need to do in terminal is (considering you are still in etc directory in terminal)
1.    `cd ..`
2.    `python etc/test.py`

this will work.
why are you facing error is because in test.py python is looking in the current directory for data_load module, and since there is no data_load module in etc directory it is giving this error.
how to solve above problem

*

*append the sys.path in code

*run the script from project main folder which contains all the package and python module and scripts.


text:
Q: SIMD integer store I am writing a program using SSE instructions to multiply and add integer values. I did the same program with floats but I am missing an instruccion for my integer version.
With floats, after I have finished all my operations, I return de values back to a regular float array doing:
_mm_store_ps(temp4,temp3);

temp4 is a float *, and temp3 a __m128.
The problem is that I cannot find a similar intrinsic for intengers. How should I return the values back to a regular array?
Thanks a lot for your answers ;)

A: See _mm_load_si128, _mm_store_si128 (aligned) and _mm_loadu_si128 _mm_storeu_si128 (unaligned).
You might have overlooked these because for some reason the types are different compared to the float intrinsics. These are what lower to the movdqa/movdqu that you want.


text:
Q: Jquery Hide/show using dropdown options not working IE or CHROME I have a mutliple drop down menus that I am using to hide/show rows in my table.
Example:
 <select name="kp1_action" class="longboxsmall">
     <option class="hidenextrow" value="">Button Disabled</option>
    <option class="showtransferoptions" value="transfercall">Transfer Call + Log Keypress to Reports</option>
    <option  class="shownextrow" value="logkeypress">Log Keypress to Reports Only</option>
    <option  class="shownextrow" value="optout">Optout of Call List</option>
  </select>

I have assigned classes to each of the different options so I can trigger events when they are clicked this is my jQUERY.
        $(".shownextrow").click(function() {
  $(this).closest("tr").next().show().find('.longboxsmall').hide();
});

                        $(".showtransferoptions").click(function() {
  $(this).closest("tr").next().show().find('.longboxsmall').show();
});

                $(".hidenextrow").click(function() {
  $(this).closest("tr").next().hide().find('.longboxsmall').hide();
});

Everything works perfectly in Firefox but not in IE or CHROME why is this? Is there a better way of doing the above?

A: I would bind the "change" event to the SELECT instead, and then in the event handler, evaluate the value of the SELECT.
$("SELECT[name=kp1_action]").change(function()
{
    if(this.value == "transfercall") {
        ...
    }
    // OR
    if($(this).hasClass("shownextrow")) {
        ...
    }
});


text:
Q: How to give a unique name to elements of foreach outside of the loop? What I am trying to do is explode some strings from MySQL by /,/, and then somehow be able to refer to these arrays outside of the loop.
This is because, each region, country and province are listed in the $data array in the appropriate order, and I need to glue them together somehow.
For example, inside MySQL there is a string stored as:
Regions: Africa, Balkans, South America
Countries: Uganda, Greece, Brazil
Provinces: Ubuge, Athenos, Santa Catarina

But I am having a really hard time trying to imagine how to tie these together, remember that sometimes there is only one member in each array, or there can be up to a hundred. But each array always contains the same number.
My attempt is something like this... I can get them to print like this, but I can't save them to use outside of the loop.
  for ($i = 0; $i < $numrows; $i++){

            $provinces = explode(',', $data[$i]['provinces']) ;
            $countries = explode(',', $data[$i]['countries']) ;
            $regions = explode(',', $data[$i]['regions']) ;

            foreach($countries as &$country){

            echo $country;

                }
}

Any ideas or help would be appreciated.
What I would like to have the final product look like would be
Place:
Africa --- Uganda --- Ubuge
Balkans --- Greece --- Athenos
South America --- Brazil --- Santa Catarina

A: Hmm, an associative array might be a good solution for this, if I understand your issue:
$region_list = array();

for ($i = 0; $i < $numrows; $i++){
     $provinces = explode(',', $data[$i]['provinces']) ;
     $countries = explode(',', $data[$i]['countries']) ;
     $regions = explode(',', $data[$i]['regions']) ;

     // So we don't have to run count every time in the loop
     $length = count($countries);

     // Since it's based of the same numeric index
     for($j = 0; $j < $length; $j++)
        $region_list[$regions[$j]] = array(
          'province' => $provinces[$j],
          'country' => $countries[$j]);
     }
}

// Now to loop through all our data
// For an associative array, we can loop over key => value so $region
// becomes the region name
foreach($region_list as $region => $data) {
   echo "$region --- {$data['country']} --- {$data['province']}";
}

A: db redesign that would work:
regions
id | region
countries
id | country | region_id
Provinces
id | province | country_id


text:
Q: Proper way to remove Page from website I have a product page in my website which I have added 3 years before.
Now the product production was stopped and the product page was removed from website.
What I did is I started displaying message in the product page telling that the production of the product got stopped.
when some one searches in google for that products the product page which was removed from site shows up first in google search.
The page rank for the product page is also high.
I don't want the removed product page to be shown at the top of search result.
What is the proper method to remove a page from website so that it gets depicted by what ever google have indexed in its table.
Thanks for the reply

A: Delete It
The proper way to remove a page from a site is to delete the actual file that is been returned to the user/bot when the page is requested. If the file is not on the webserver, any well configured webserver will return a 404 and the bot/spider will choose to remove that from the index in the next refresh.
Redirect It
If you want to keep the good "google juice" or SERP ranking the page has, probably due to any inbound links from external sites, you'd be best to set your websever to do a 302 redirect to a similar (updated product).
Keep and convert
However, if the page is doing so well that it ranks #1 for searches to the entire site, you need to use this to your advantage. Leave the bulk of the copy on the page the same, but highlight to the viewer that the product no longer exists and provide some helpful options to the user instead: tell them about a newer, better product, tell them why it's no longer available, tell them where they can go to get support if they already have the discontinued product.

A: I am completely agree with above suggestion and want to add just one point.
If you want to remove that page from Google Search Result; just login to Google webmaster tool (you must have verified that website in Google webmaster tool) and add that particular page for index removal request.
Google will de-index that page and it will be removed from Google search rankings.


text:
Q: Gorm BeforeCreate hook is not working to generate a UUID I am trying to generate a UUID every time I create a company. I thought about doing it in the hook function, but it is not working. I tried to panic the program if it is executed, but the hook is not responding.
I followed the documentation on how I can implement the hook, but it does not work for me.
Hooks documentation: https://gorm.io/docs/hooks.html
import (
    "time"

    "github.com/jinzhu/gorm"
    uuid "github.com/satori/go.uuid"
)

type Base struct {
    ID        uuid.UUID  `gorm:"type:UUID;" json:"_id"`
    CreatedAt time.Time  `gorm:"type:Date;" json:"created_at"`
    UpdatedAt time.Time  `gorm:"type:Date;" json:"updated_at"`
    DeletedAt *time.Time `gorm:"type:Date;" json:"deleted_at"`
}

type CompanyModel struct {
    Base
    // Departments []DepartmentModel `gorm:"foreignKey:id" json:"departments"`
    Cvr         int               `gorm:"not null" json:"cvr"`
    Name        string            `gorm:"not null" json:"name"`
}

// BeforeCreate creates
func (u *Base) BeforeCreate(tx *gorm.DB) (err error) {
    u.ID = uuid.NewV4()
    panic(u.ID)
    return
}

// BeforeSave creates
func (u *Base) BeforeSave(tx *gorm.DB) (err error) {
    u.ID = uuid.NewV4()
    panic(u.ID)
    return
}

I am creating a company by the following
    tx := db.Session(&gorm.Session{SkipHooks: false}).Create(&models.CompanyModel{
        Cvr:  12333,
        Name: "test,
        // Departments: company.Departments,
    },
    )

The saved value when I execute is always:
[1.479ms] [rows:0] INSERT INTO "company_models" ("id","created_at","updated_at","deleted_at","cvr","name") VALUES ('00000000-0000-0000-0000-000000000000','2021-04-21 18:00:51.879','2021-04-21 18:00:51.879',NULL,12333,'test')

A: It looks like you are using gorm v1, and I think you need gorm v2. The import is "gorm.io/gorm".
Minimum working example:
package main

import (
    "fmt"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type User struct {
    Id int
    Name string
}

func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
    u.Name = "Steve"
    return
}

func (u *User) BeforeSave(tx *gorm.DB) (err error) {
    u.Name = "Sally"
    return
}

func main() {
    db, err := gorm.Open(sqlite.Open("hooks.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }
    db.AutoMigrate(&User{})
    user := User{
        Name: "Blake",
    }
    db.Create(&user)
    fmt.Println(user.Name)
    user.Name = "Tyler"
    db.Save(&user)
    fmt.Println(user.Name)
}

Prints:
Steve
Sally


text:
Q: I need some help in a query in SQL Server I need a query that filters from the first day of the previous month and the current day at 0 hours.
Can anyone help me?

A: Use date arithmetics:
where mydate >= dateadd(month, -1, datefromparts(year(getdate()),month(getdate()), 1))

Expression datefromparts(year(getdate()),month(getdate()), 1) gives you the first day of the current month; you can then substract 1 month to get the result that you want.
If you want to filter out today's data (and beyond), then:
where
    mydate >= dateadd(month, -1, datefromparts(year(getdate()),month(getdate()), 1))
    and mydate < cast(getdate() as date)


text:
Q: Bash command substitution with a variable I'm new to bash scripting and I've been learning as I go with a small project I'm taking on. However, I've run into a problem that I cannot seem to get past.
I have a variable that I need to include in a command. When ran directly in the shell (with the variable manually typed), the command returns the expected result. However, I can't get it to work when using a variable.
So, if I manually run this, it correctly returns 0 or 1, depending if it is running or not.
ps -ef | grep -v grep | grep -c ProcessName

However, when I try to embed that into this while clause, it always evaluates to 0 because it's not searching for the correct text.
while [ `ps -ef | grep -v grep | grep -c {$1}` -ne 0 ]
do
  sleep 5
done

Is there a way I can accomplish this? I've tried a myriad of different things to no avail. I also tried using the $() syntax for command substitution, but I had no luck with that either.
Thanks!

A: I think that instead of {$1} you mean "$1".  Also, you can just do pgrep -c "$1" instead of the two pipes.
In addition, there's also no need to compare the output of grep -c with 0, since you can just see if the command failed or not.  So, a much simplified version might be:
while pgrep "$1" > /dev/null
do
    sleep 4
done

A: You should really use -C with ps rather than the messy pipes if you're using the full process name. If you're interested in substring matching, then your way is the only thing I can think of.


text:
Q: Unable to connect to server on local network via new openvpn I created an openvpn server on AWS using the marketplace AMI, I changed the 'vpn settings' for the network address ad the group default IP both to be 10.0.0.0/20
I then downloaded the client file and added that into my Ubuntu 18.04 vpn settings via the import option.
After that I tried to ssh into another server found at 10.0.10.220 That failed even though port 22 is wide open (0.0.0.0/0)
When checking ifconfig for details about the connection I see the below which is related to the VPN.
tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1500
        inet 10.0.8.2  netmask 255.255.252.0  destination 10.0.8.2
        inet6 fe80::eac9:76b7:5e88:68e4  prefixlen 64  scopeid 0x20<link>
        unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 100  (UNSPEC)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 141  bytes 7544 (7.5 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

A note, my local home network is 192.168.X.X so should be no conflicts
EDIT**
ip route
default via 10.0.8.1 dev tun0 proto static metric 50
default via 192.168.0.1 dev wlp2s0 proto static metric 600
10.0.0.0/16 via 10.0.8.1 dev tun0 proto static metric 50
10.0.8.0/22 dev tun0 proto kernel scope link src 10.0.8.2 metric 50
18.204.38.141 via 192.168.0.1 dev wlp2s0 proto static metric 600
169.254.0.0/16 dev wlp2s0 scope link metric 1000
172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1 linkdown
192.168.0.0/24 dev wlp2s0 proto kernel scope link src 192.168.0.200 metric 600
192.168.0.1 dev wlp2s0 proto static scope link metric 600

EDIT 2**
My terraform code
resource "aws_instance" "vpn" {
  ami           = "ami-0ca1c6f31c3fb1708"
  instance_type = "t3.micro"
  availability_zone = "us-east-1a"
  key_name = "josh"
  monitoring = true
  vpc_security_group_ids = [aws_security_group.vpn.id]
  disable_api_termination = true
  associate_public_ip_address = true
  subnet_id = aws_subnet.public["us-east-1a"].id
  source_dest_check = false

  tags = {
    Name = "VPN"
  }
}

resource "aws_eip" "vpn_eip" {
    instance = "${aws_instance.vpn.id}"
    vpc = true
}

resource "aws_security_group" "vpn" {
  name        = "vpn"
  description = "Allow vpn traffic"
  vpc_id      = aws_vpc.Main_VPC.id

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  ingress {
    from_port   = 943
    to_port     = 943
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  ingress {
    from_port   = 1194
    to_port     = 1194
    protocol    = "udp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port       = 0
    to_port         = 0
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
  }
}

EDIT 3**
Add Jenkins server TF
resource "aws_instance" "jenkins" {
  ami           = var.ubuntuAMI
  instance_type = "t3.small"
  availability_zone = "us-east-1a"
  key_name = "josh"
  monitoring = true
  vpc_security_group_ids = [aws_security_group.ssh_access.id, aws_security_group.jenkins.id]
  disable_api_termination = true
  associate_public_ip_address = true
  subnet_id = aws_subnet.public["us-east-1a"].id

  tags = {
    Name = "Jenkins"
  }
}

resource "aws_eip" "jenkins_eip" {
    instance = aws_instance.jenkins.id
    vpc = true
}

resource "aws_eip_association" "jenkins_eip_assoc" {
  instance_id   = "${aws_instance.jenkins.id}"
  allocation_id = "${aws_eip.jenkins_eip.id}"
}

resource "aws_security_group" "jenkins" {
  name        = "jenkns"
  description = "Allow jenkins traffic"
  vpc_id      = aws_vpc.Main_VPC.id

  ingress {
    from_port   = 80
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

A: Two issues
1) You haven't NAT'd the traffic on your vpn server, so other systems need a return route, add this in AWS or make all traffic look like it's coming from the VPN Server
2) You can't Access the Internet as your source IP range (vpn subnet) isn't getting NAT'd on the vpn router
Both cases can be solved by adding this policy to the server running openvpn
iptables -t nat -A POSTROUTING -s 10.0.8.0/22 -o eth0 -j MASQUERADE
iptables save

or
firewall-cmd --zone=external --add-masquerade --permanent
firewall-cmd --reload


text:
Q: WebApi Telerik Kendo UI Grid with angularjs I've an html page where i've inserted a kendo-grid
<kendo-grid options="GridOptions">
</kendo-grid>

GridOptions are configured in my angularjs controller (as Telerik suggested)
$scope.GridOptions = {
    dataSource: {
        type: "odata",
        transport: {
            read: {
                url: "http://localhost/mywebsitename/odata/DentalicaProducts"
            }
        },
        serverPaging: true,
        serverSorting: true,
        serverFiltering: true,
        pageSize: 5
    },
    scrollable: false,
    sortable: true,
    pageable: true
};

When i try to load this page kendo automatically compose the URL for loading grid content:
> http://localhost/mywebsitename/odata/DentalicaProducts?$callback=jQuery2…337801940739_1418890531179&%24inlinecount=allpages&%24format=json&%24top=5

But I received this Response:
 - Status Code: 400 Bad Request
and the following Response:

{
    "error":{
      "code":"","message":"The query parameter '$callback' is not supported."
    }
  }

My backend service is a webAPI v2.2 service which implements ODataController (v4.0).
If I invoke it directly it works nice and i get my product list.
Can anyone help me?


text:
Q: solution of an infinite horizon optimization problem Give the following formulation:
$\min_{\{x_s(t):\forall s,t\}} \sum_{s \in \mathcal{S}} \mathbf{1}\left(\lim_{T\rightarrow \infty} \frac{1}{T}  \sum_{t=1}^T \frac{y_s(t)}{x_s(t)}\leq 1\right)$
$s.t. \qquad \quad y_s(t+1)=f(y_s(t),x_s(t))$
what math tool can give the optimal solution to this problem?


text:
Q: PowerApps Customer Support Portal will not show field I'm trying to do something very simple in displaying on a customer support portal the 'owner' of the support case.  However, no matter what I do I can't get this field to show on the particular 'Edit Case' web page.
I have added the field 'Owner' to the form (changed label to 'Assigned To').
Form Creation
I have then published this and synced it with the web page, but as you can see the field does not appear in the web page:
web
I have tried everything I can think of but this field will not appear on the form, on either the actual portal or the web form creation page. I have tried:

*

*Hiding/showing the field.

*Creating a new form based on the current
one

*Creating a brand new form with the owner field on.

*Clearing the portal cache

The strange thing is I have a list page showing all the cases and the owner displays perfectly here.
list
I'm really stuck to why this field will not display at all on this form.
Pete
EDIT:
As I move the field up and down the form I can see a blank row moving up and down the form field, it's like it can't display the field at all.
blank area

A: First thing First, Is your Form "case" (Entity Case-->incident) the correct form on PowerPortals?
In most cases (out of the box) it is Case Portals Forms. Please check this.
Second thing, clear your portals cache.
Login in to Portals as Admin and then use below url, clear cache, It shall help.
https://[yourURL].powerappsportals.com/_services/about
let me know if it helps.


text:
Q: Are the following definitions of a local property equivalent? I have seen two different definitions of a local property of rings.

*

*$P$ is a local property of rings if $P(A)$ is equivalent to $P(A_{\mathfrak p})$ for all prime ideals $\mathfrak p$.

*$P$ is a local property if $P(A)$ implies $P(A_f)$ for all $f\in A$, and $P(f_i)$ for $f_i$ such that $A=(f_1,f_2,...f_n)$ implies $P(A)$.
Here $P(A)$ denotes '$P$ holds for $A$'.
Are these two definitions equivalent?


text:
Q: Change Element Style On Page Scroll I want to change the visibility of an element after the user scrolls down 100px.
I have some code already,
var fixed = false;
$(document).scroll(function() {
    if( $(this).scrollTop() >= 100 ) {
        if( !fixed ) {
            fixed = true;
            $('#logo-scroll').css({position:'fixed', display:'visible !important'});
        }
    } else {
        if( fixed ) {
            fixed = false;
            $('#logo-scroll').css({display:'none'});
        }
    }
});

JSFiddle.
The code has two problems.

*

*It doesn't default to be invisible, I want it so it starts invisible.

*It doesn't repeat, when the user scrolls back up, it doesn't go back being invisible.
More details,
I want to make something like this header, but, as you can see, there's a certain point where you see half of the small logo, and a PART of the bigger one. It doesn't affect techcrunch much as the header is small, but on my site, it does. I have made everything, I just need to start it in display:none, and become visible after 100px.

A: Well the question has already been answered. just adding a better example which might be useful for others and it's exactly what op wants.
code and demo
Edited: Added actual code from original source.
jQuery:
// This function will be executed when the user scrolls the page.
$(window).scroll(function(e) {
    // Get the position of the location where the scroller starts.
    var scroller_anchor = $(".scroller_anchor").offset().top;

    // Check if the user has scrolled and the current position is after the scroller start location and if its not already fixed at the top
    if ($(this).scrollTop() >= scroller_anchor && $('.scroller').css('position') != 'fixed')
    {    // Change the CSS of the scroller to hilight it and fix it at the top of the screen.
        $('.scroller').css({
            'background': '#CCC',
            'border': '1px solid #000',
            'position': 'fixed',
            'top': '0px'
        });
        // Changing the height of the scroller anchor to that of scroller so that there is no change in the overall height of the page.
        $('.scroller_anchor').css('height', '50px');
    }
    else if ($(this).scrollTop() < scroller_anchor && $('.scroller').css('position') != 'relative')
    {    // If the user has scrolled back to the location above the scroller anchor place it back into the content.

        // Change the height of the scroller anchor to 0 and now we will be adding the scroller back to the content.
        $('.scroller_anchor').css('height', '0px');

        // Change the CSS and put it back to its original position.
        $('.scroller').css({
            'background': '#FFF',
            'border': '1px solid #CCC',
            'position': 'relative'
        });
    }
});

HTML

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum metus nec neque convallis id interdum nibh aliquet. Nulla eget varius diam. Ut ut dolor dolor. Mauris vehicula sodales mi quis euismod. In sem metus, volutpat nec fringilla sed, fermentum ac turpis. Cras aliquam venenatis rutrum. Donec pharetra ante sit amet justo pellentesque nec consequat ante elementum. Ut imperdiet iaculis tortor, id pretium urna pharetra sit amet. Aenean pharetra nunc risus, ac scelerisque urna. Morbi dictum egestas augue, in euismod metus commodo ac. Duis nisl ante, consequat et tincidunt id, eleifend eu ante. Integer lectus velit, tempus eu feugiat et, adipiscing ut mauris.

This is the scrollable bar

        Quisque sollicitudin elit vitae diam consequat accumsan. Suspendisse potenti. Donec dapibus tortor at justo eleifend at pellentesque leo lobortis. Etiam ultrices leo et nulla iaculis eu facilisis augue fermentum. Pellentesque eu leo purus. Vestibulum bibendum, metus at bibendum blandit, lacus neque porttitor diam, id facilisis lectus mauris et leo. Donec adipiscing interdum lacus sed condimentum. In auctor sollicitudin orci, ac interdum risus aliquet ullamcorper. Curabitur mollis accumsan vulputate. Etiam adipiscing diam nec dui posuere ut tincidunt felis tristique. Vestibulum neque enim, placerat sed placerat commodo, consectetur ac mauris. Sed ultrices pretium nibh, a blandit libero imperdiet pulvinar. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

    ...

CSS:
.container{font-size:14px; margin:0 auto; width:960px}
.test_content{margin:10px 0;}
.scroller_anchor{height:0px; margin:0; padding:0;}
.scroller{background:#FFF; border:1px solid #CCC; margin:0 0 10px; z-index:100; height:50px; font-size:18px; font-weight:bold; text-align:center; width:960px;}

A: Use: display:block; and display:none;
jsFiddle DEMO
Add this to your CSS:
#logo-scroll{ display:none; position:fixed; }

jQ:
var $logo = $('#logo-scroll');
$(document).scroll(function() {
    $logo.css({display: $(this).scrollTop()>100 ? "block":"none"});
});

BTW: on TC page it's just a CSS play with z-indexes. nothing more. all elements are visible at page load, it's just the scroll that makes appear a z-index lower element beneath the big logo.
In plain Javascript would be like this:
var win = window,
    docEl = document.documentElement,
    $logo = document.getElementById('logo-scroll');

win.onscroll = function(){
   var sTop = (this.pageYOffset || docEl.scrollTop)  - (docEl.clientTop || 0);
   $logo.style.display =  sTop > 100 ? "block":"none" ;
};


text:
Q: BeautifulSoup не находит тэг # imports
from tkinter import *
import requests
from bs4 import BeautifulSoup
# requests
r = requests.get("https://www.google.com/search?q=%D0%BA%D1%83%D1%80%D1%81+%D0%B4%D0%BE%D0%BB%D0%BB%D0%B0%D1%80%D0%B0+%D0%BA+%D0%B1%D0%B5%D0%BB.+%D1%80%D1%83%D0%B1%D0%BB%D1%8E&oq=%D0%9A%D1%83&aqs=chrome.1.69i59l2j69i57j69i59l2j69i61l3.2591j0j7&sourceid=chrome&ie=UTF-8")
soup = BeautifulSoup(r.text, "html.parser")
ds_course_tag =  soup.findAll("span", {"class": "DFlfde SwHCTb"})
# root
sd = Tk()

sd.geometry("300x500")
sd.title("Калькулятор валют")
sd.resizable(False, False)

def clear():
    rub_entry.delete(0, END)
    dollar_entry.delete(0, END)

def count():

    # dollar_course = float(dollar_course_entry.get())
    #logic
    if rub_entry.get() == "":
        rub = float(dollar_entry.get())*dollar_course
        rub = round(rub, 3)
        rub_entry.delete(0, END)
        rub_entry.insert(END, rub)

    elif dollar_entry.get() == "":
        dollar = float(rub_entry.get())//dollar_course
        dollar = round(dollar, 3)
        dollar_entry.delete(0, END)
        dollar_entry.insert(END, dollar)

# elements

# dollar_course_label = Label(text="Курс доллара")
# dollar_course_label.place(x=80, y=75)

# dollar_course_entry = Entry()
# dollar_course_entry.place(x=80, y=100)

dollar_label = Label(text="Доллары")
dollar_label.place(x=80, y=225)

dollar_entry = Entry()
dollar_entry.place(x=80, y=250)

rub_label = Label(text="Рубли")
rub_label.place(x=80, y=275)

rub_entry = Entry()
rub_entry.place(x=80, y=300)

counter = Button(text="Рассчитать", command=count)
counter.place(x=80, y=400)

clearer = Button(text="Очистить", command=clear)
clearer.place(x=80, y=450)

sd.bind("<Return>", lambda x: count())

sd.mainloop()

Я пробовал разные сайты, но не выходило.
Это конвертер валют, он должен брать курс доллара к бел. рублю из интернета, но не получилось.
Помогите пожалуйста


text:
Q: Installing TTF fonts in LaTeX One of the annoying aspects of LaTeX is the limited number of fonts that come by default, and the pain involved in making new fonts 'LaTeX' ready. I have a collection of truetype fonts that I'd like to prepare for use, and I definitely want to make sure I have vector versions of these fonts (i.e not type 3/bitmapped versions). Is there a relatively painless way to do this ?

A: The easiest way is with XeTeX or LuaTeX and the fontspec package. They can use any TTF font installed on the system. For Linux this means both the system wide fonts and any fonts you put into ~/.fonts/ (e.g. by installing them via Nautilus).
To use the fonts you simply have to load the fontspec package and set the font:
\documentclass{article}

\usepackage{fontspec}
\setmainfont{Arial}

\begin{document}
Lorem ipsum...
\end{document}

Then compile the the document with xelatex or lualatex. The fontspec documentation describes all the possibilities for changing fonts.
The only drawbacks (as far as I am aware) are that you can only generate .pdf files and that you need a sufficiently new TeX distribution (TeX Live 2009 should work for XeTeX and Tex Live 2010 for LuaTeX).

A: One solution is to use XeLaTeX, which lets you use system fonts (mostly) hassle-free.

A: The process for PdfTeX is something like this (depends a little bit on your distribution):

*

*Get autoinst.pl from Fontools from CPAN

*Get otf2tfm from lcdf-typetools

*Run autoinst.pl (using Perl) on all ttfs

*Add generated PdfTeX font mapping (in MikTeX for instance initexmf --edit-config-file updmap, add Map yourmap.map and run initexmf --mkmaps)

You can do the whole process manually as well (autoinst.pl is nothing but a smart wrapper):

*

*Create tfm metrics and a ttfonts.map using ttf2tfm

*Create virtual font tables using vptovf

*Create afm metrics using ttf2afm

*Create pdf font map using afm2tfm

*Put *.tfm, *.afm, *.ttf, *.vf into the fonts/tfm/ etc.

*Add the font maps

*Create a package/sty to pull the various fonts into a font family (this is where I am stuck)

My ruby script for running the commands looks like this:
require 'fileutils'

basename = "Nexus"

open("#{basename}.map", 'a') { |pdfFontMap|

    Dir["#{basename}*.ttf"].each{ |file|

        file.sub!(/\.ttf$/, "")

        ttf = "#{file}.ttf"

        file.gsub!(/_/,"") # Remove underscores

        puts `ttf2tfm #{ttf} -q -T T1-WGL4.enc -v ec#{file}.vpl rec#{file}.tfm >> ttfonts.map`

        puts `vptovf ec#{file}.vpl ec#{file}.vf rec#{file}.tfm`

        puts `ttf2afm -e T1-WGL4.enc -o rec#{file}.afm #{ttf}`

        pdfFontMap.puts `afm2tfm rec#{file}.afm -T T1-WGL4.enc rec#{file}.tfm`.gsub(/\r|\n/, "") + " <#{ttf}"
    }
}

You can find more details about the manual way in:
http://www.radamir.com/tex/ttf-tex.htm
P.S.:

*

*Run initexmf --update-fndb EVERY time new files are put somewhere

A: LuaTeX brings TTF-support, but I have no Idea how mature it is right now.


text:
Q: Reading defined Data from SQL I have a Problem with reading data with Pandas.read_sql (...):
My code Looks like this:
import psycopg2 as pg
import pandas as pd

con = pg.connect(host='db123', database='data', user='ortm', password='***')

db = pd.read_sql_query('select calculationtime, state from stateresult WHERE ID = A123', con)

I get the following Error Message:
Execution failed on sql 'select calculationtime, state from stateresult WHERE ID = A123': FEHLER:  Spalte "g351" existiert nicht
LINE 1: ...m stateresult WHERE ID = A123
I tried this with another column which is a boolean or integer. I think it has sth. to do with the column being defined as character varying(250).
I tried to get it to work with a CAST but that didnt work neither.
[I'm using Python 2.7]

A: Why don't you try this once and inform the response you got.
If your connection with database is correct.But I am not aware about python.Once check it and revert to me if it gives error message.
   db = pd.read_sql_query("select calculationtime, state from stateresult WHERE ID = 'A123'", con)


text:
Q: How to write concepts that make use of ADL I would like to write a concept that would allow me to verify if a given statement, using ADL, is valid and has a proper return type.
In my specific case, I want to write a String concept that should enforce the following requirements:

*

*The type has begin and end semantics for both its const and non-const flavors:
 // Akin to what this function does for `T` and `T const`
 template< typename T >
 auto test(T& t) {
     using std::begin;
     return begin(t);
 }

 // calling test with `T` and `T const` should be valid.

*The return types of begin and end are consistent for both const and non-const flavors and they satisfy the std::contiguous_iterator concept.
So far I went with a trait implementation like the following:
namespace Adl {

using std::begin;

template< typename T >
using HasBeginT = decltype(begin(std::declval< T >()));

}

template< typename T >
using HasBegin = std::experimental::is_detected< Adl::HasBeginT, T >;

But I would like to directly embed this ADL usage in the definition of my constraint instead.

A: The idiom using std::X; X(...); is considered a bad idea post-C++20. The standard idiom now is to create a customization point object for X. Or in your case, use the existing customization point object: std::ranges::begin.
The way you call such a customization point is by spelling it out in full; internally, it can make an ADL call (without using anything) if the type being provided has such a call.


text:
Q: Transposition in Javascript I have following as input
[
  {
    "level1": [
      { "subject": "English", "avgScore": 100% },
      { "subject": "Math", "avgScore": 80% }
    ]
  },
  {
    "level2": [
      { "subject": "English", "avgScore": 90% },
      { "subject": "Math", "avgScore": 75% }
    ]
  },
  {
    "level3": [
      { "subject": "English", "avgScore": 100% },
      { "subject": "Math", "avgScore": 80% },
      { "subject": "Science", "avgScore": 90% }
    ]
  },
  {
    "level4": [
      { "subject": "Math", "avgScore": 80% },
      { "subject": "Science", "avgScore": 90% }
    ]
  },
  {
    "level5": [
      { "subject": "Computer", "avgScore": 80% }
    ]
  }
]

and I am trying to convert into the following form
    [
      {
        label: "English",
        values:[
          { grade: "level1", avgScore: 100% },
          { grade: "level2", avgScore: 90% },
          { grade: "level3", avgScore: 100% }
        ]
      },
      {
        label: "Math",
        values:[
          { grade: "level1", avgScore: 80% },
          { grade: "level2", avgScore: 75% },
          { grade: "level3", avgScore: 80% },
          { grade: "level4", avgScore: 80% }
        ]
      },
      {
        label: "Science",
        values:[
          { grade: "level3", avgScore: 90% },
          { grade: "level4", avgScore: 90% }
        ]
      },
      {
        label: "Computer",
        values:[
          { grade: "level5", avgScore: 80% }
        ]
      }
    ]

So far I have following code which is not giving me the array values
convert( inputFormat) {
  const subjects = Array.from( inputFormat.reduce((acc, subject) => {
    const level = Object.keys(subject)[0];
    subject[level].forEach((levelZone) => {
      acc.add(levelZone.subject);
    });
    return acc;
  }, new Set()));

  return subjects.map((subject) => {
    return {
      label: subject,
      values:  inputFormat.map((subject) => {
        return Object.keys(subject)[0]
      }, []);
    }
  });
}

A: You can iterate input array within .map() to check if subject is equal to a property name of an object, if true .push() "avgScore" value and the property name set at "grade" to property name

const input = [{
    "level1": [{
        "subject": "English",
        "avgScore": "100%"
      },
      {
        "subject": "Math",
        "avgScore": "80%"
      }
    ]
  },
  {
    "level2": [{
        "subject": "English",
        "avgScore": "90%"
      },
      {
        "subject": "Math",
        "avgScore": "75%"
      }
    ]
  },
  {
    "level3": [{
        "subject": "English",
        "avgScore": "100%"
      },
      {
        "subject": "Math",
        "avgScore": "80%"
      },
      {
        "subject": "Science",
        "avgScore": "90%"
      }
    ]
  },
  {
    "level4": [{
        "subject": "Math",
        "avgScore": "80%"
      },
      {
        "subject": "Science",
        "avgScore": "90%"
      }
    ]
  },
  {
    "level5": [{
      "subject": "Computer",
      "avgScore": "80%"
    }]
  }
];

function convert(inputFormat) {
  return Array.from(
    [...new Set(
      inputFormat.map(prop => {
        const [{subject}] = prop[Object.keys(prop).pop()];
        return subject
      })
     )
    ]
    , label => {
      const values = [];
      for (const prop of inputFormat) {
        for (const [grade, props] of Object.entries(prop)) {
          for (const {subject, avgScore} of props) {
            label === subject && values.push({avgScore, grade})
          }
        }
      }
      return {label, values}
    })
}

console.log(convert(input));


text:
Q: Best way to achieve late-stage polymorphism I have several disparate templated pure abstract classes. I derive from these to get a bunch of classes, and from there, I can use those to make a bunch of objects. I would like to put all of these objects into a container. However, they are all of different types. I am wondering how to accomplish this late-stage polymorphism.
Say this is my pre-existing code that I have right now:
#include <iostream>

template<typename T>
class A{
public:
    A() : m_num(1.0) {};
    virtual ~A() {};
    virtual void printNum() const = 0;
protected:
    T m_num;
};

template<typename T>
class B{
public:
    B() : m_num(2.0) {};
    virtual ~B() {};
    virtual void printTwiceNum() const = 0;
protected:
    T m_num;
};

class A_example : public A<int>
{
public:
    A_example() : A<int>() {};
    void printNum() const { std::cout << m_num << "\n"; };
};

class B_example : public B<int>
{
public:
    B_example() : B<int>() {};
    void printTwiceNum() const { std::cout << 2*m_num << "\n"; };
};

int main(){
    A_example first;
    B_example second;
    first.printNum();
    second.printTwiceNum();

    return 0;
}

With more classes, it could get pretty messy inside of main(). Ideally I could jut iterate over the container and call print() on each element. My first thought is to use a std::vector<unique_ptr<Base>>. This seems to work:
#include <iostream>
#include <vector> // new include
#include <memory> // new include
#include <utility> // new include

// new Base class here
class Base{
public:
    virtual ~Base(){};
};

template<typename T>
class A : public Base{ // new inheritance here
public:
    A() : m_num(1.0) {};
    virtual ~A() {};
    virtual void printNum() const = 0;
protected:
    T m_num;
};

template<typename T>
class B : public Base{ // new inheritance here as well
public:
    B() : m_num(2.0) {};
    virtual ~B() {};
    virtual void printTwiceNum() const = 0;
protected:
    T m_num;
};

class A_example : public A<int>
{
public:
    A_example() : A<int>() {};
    void printNum() const { std::cout << m_num << "\n"; };
};

class B_example : public B<int>
{
public:
    B_example() : B<int>() {};
    void printTwiceNum() const { std::cout << 2*m_num << "\n"; };
};

int main(){

    std::vector<std::unique_ptr<Base>> v;
    v.emplace_back( new A_example() );
    v.emplace_back( new B_example() );
    //v[0]->printNum(); // nope
    //v[1]->printTwiceNum(); // nope

    return 0;
}

This is cool because I didn't have to change A_example or B_example, and all I changed in A and  B was that I added : public Base. However, I have no idea how to call each elements print*** function. Is there any way to call the printNum() and printTwiceNum() functions, and for them to be automatically recognized?

A: The simplest approach is to just make a virtual function Base::print and have your derived classes implement it.  But that's not always appropriate.
Another approach is to branch on dynamic_cast conversions.  The premise there is that some functions are only available on some classes.  But this can get hairy especially when using class templates, as you must handle all expected template parameters.
To generalize this, you can use interface classes.  Let's say you have lots of different classes but only a small number of print variations.  In that case, it may make sense to do this:
class PrintNumInterface {
public:
    virtual void printNum() const = 0;
};

class PrintTwiceNumInterface {
public:
    virtual void printTwiceNum() const = 0;
};

template<typename T> class A : public Base, public PrintNumInterface { ... };
template<typename T> class B : public Base, public PrintTwiceNumInterface { ... };

And now, no matter how many additional classes or template expansions you have to deal with, you only need to handle these interfaces:
for (auto& p : v)
{
    if (PrintNumInterface* iface = dynamic_cast<PrintNumInterface*>(p.get())
        iface->printNum();
    else if (PrintTwiceNumInterface* iface = dynamic_cast<PrintTwiceNumInterface*>(p.get())
        iface->printTwiceNum();
}


text:
Q: Замена реального переноса строки на последовательность символов "\n" в PHP Есть переменная $sms_text.
Вывод var_dump($sms_text);:
string(358) "Не работают:
№*****, ДО наименование – с 00.00.2016 г., (СОБ, ОСТиТ, Касса, Прочее);
№*****, ДО наименование – с 00.00.2016 г., (СОБ, ОСТиТ, Касса, Прочее);
№*****, ДО наименование – с 00.00.2016 г., (СОБ, ОСТиТ, Касса, Прочее);"

Подскажите, как заменить все переносы строки на символ \n, т.к. данный текст корректно не распознается парсером?
UPD:
Т.е. надо чтобы в данной переменной вместо переносов был именно символ \n, например:
"Не работают:\n№*****, ДО наименование – с 00.00.2016 г., (СОБ, ОСТиТ, Касса, Прочее);\n№*****, ДО наименование – с 00.00.2016 г., (СОБ, ОСТиТ, Касса, Прочее);\n№*****, ДО наименование – с 00.00.2016 г., (СОБ, ОСТиТ, Касса, Прочее);"

A: Просто замените перенос строки на нужные символы:
$sms_text = str_replace("\r", "", str_replace("\n", "\\n", $sms_text));


text:
Q: Cannot link library using CMake in Android Studio: Unable to load native library As soon as I want to add my own library via target_link_libraries(...) my application crashes with the following error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: my.process, PID: 3651
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.process/android.app.NativeActivity}: java.lang.IllegalArgumentException: Unable to load native library: /data/app/my.process/lib/x86/libnative-activity.so

My CMake file in src/cpp/main/CMakeLists.txt looks like this:
cmake_minimum_required(VERSION 3.4.1)

# build native_app_glue as a static lib
add_library(app-glue STATIC
            ${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c)

# now build app's shared lib
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")

# Native-Activity
add_library(native-activity SHARED "")

# Native-Library
add_library(native-lib SHARED "")

include("Native/CMakeLists.txt")

# Link the native-activity
target_sources(native-activity PRIVATE "${CMAKE_CURRENT_LIST_DIR}/main.cpp")

target_include_directories(native-activity PRIVATE
                           ${ANDROID_NDK}/sources/android/native_app_glue)

# add lib dependencies
target_link_libraries(native-activity
                      android
                      app-glue
                      log)

target_link_libraries(native-activity native-lib)

and the CMake file in src/cpp/main/Native/CMakeLists.txt looks like this:
set_target_properties(native-lib PROPERTIES LINKER_LANGUAGE CXX)

If I remove the following line from the first CMake file in src/cpp/main/CMakeLists.txt compilation works:
target_link_libraries(native-activity native-lib)

What do I do wrong?

A: What worked for me was using the find_library(...) CMake command and use the full path to link the library native-lib against native-activity.
The working CMake file is shown below:
cmake_minimum_required(VERSION 3.4.1)

# build native_app_glue as a static lib
add_library(app-glue STATIC
            ${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c)

# now build app's shared lib
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")

# Native-Activity
add_library(native-activity SHARED "")

# Native-Library
add_library(native-lib SHARED "")

include("Native/CMakeLists.txt")

# Link the native-activity
target_sources(native-activity PRIVATE "${CMAKE_CURRENT_LIST_DIR}/main.cpp")

target_include_directories(native-activity PRIVATE
                           ${ANDROID_NDK}/sources/android/native_app_glue)

# add lib dependencies
target_link_libraries(native-activity
                      android
                      app-glue
                      log)

find_library(native-lib my-native-lib)

target_link_libraries(native-activity ${my-native-lib})


text:
Q: media Query for macbook pro 15" I'm trying to apply media query for laptop 15" and smaller with no success.
Here is my media query:
@media screen and (min-device-width: 1200px) and (max-device-width: 1600px) and (-webkit-min-device-pixel-ratio: 1) { }

And:
@media screen and (min-device-width: 1200px) and (max-device-width: 1600px) and (-webkit-min-device-pixel-ratio: 2)  and (min-resolution: 192dpi) { }

I works for 13inch macbook pro but no for the 15".
Any help would be much appreciated.
Thanks

A: It might be a problem with min-device-width, as it should only work on mobile devices (tablet, smartphones):

min-device-width

Try using those (without -device-) so you can test it on your computer's browser.

min-width or max-width

Styles for Desktop
@media screen and (min-width: 1025px) and (max-width: 1280px) {

   /* Styles for Desktops */
 }

Also add inside  tag
<meta name="viewport" content="width=device-width, initial-scale=1">

A:  /*--cover up mac , mac-book---*/

@media only screen and (min-width: 1024px) and (max-width: 1920px) {}

/*--mac book pro , and mac-book retina display screen---*/

@media only screen and (min-width: 1920px) and (max-width: 2560px) {}

A: Retina Display media queries
@media only screen and (-webkit-min-device-pixel-ratio : 1.5), only
screen and (min-device-pixel-ratio : 1.5) { styles }


text:
Q: Create Camel endpoints in java to use in xml routes I've been trying to create endpoints in java and have those endpoints referenced in my xml routes but have been unsuccessful. I can do this in xml:
<endpoint id="kafkatopic" uri="kafka:..."/>

and have the endpoint referenced in the routes:
<route id="eventflow">
    <from ref="kafkatopic" ...>

What i want to do is replace the xml endpoint declaration using java. I've tried something like:
Endpoint kafkaep = camelCtx.getEndpoint(kafkaUri);

however i'm stumped on how i can create a key "kafkatopic" to refer to the endpoint such that the xml route is able to find it. I've checked the EndpointRegistry but doesn't allow me to provide a simple name for the endpoint.
Any help is appreciated. Thanks.
Here's my camelContext:
<camelContext xmlns="http://camel.apache.org/schema/blueprint"
    trace="true" id="context">

    <routeBuilder ref="myRouteBuilder" />
    <route id="eventflow">
        <from ref="kafkatopic" ...>

My simplified RouteBuilder.configure() has below. Here i was trying to put the endpoint in the endpointRegistry hoping that it will used by the xml route. There's not a lot of docs on EndpointRegistry so i was shooting in the dark with this.
    // endpoint i have formatted to be "someKey=uri"
    String endPoint = getConfigs("camel-endpoint");
    String [] eptoks = ep.split("=", 2);
    EndpointRegistry<String> endpointRegistry = camelContext.getEndpointRegistry();
    Endpoint endpoint = camelContext.getEndpoint(eptoks[1]);
    endpointRegistry.put(eptoks[0], endpoint);

A: You could try defining the endpoint in Spring, either explicitly:
<bean id="kafkaComponent" class="org.apache.camel.component.kafka.KafkaComponent"/>
  <bean id="kafkaEndpoint" class="org.apache.camel.component.kafka.KafkaEndpoint">
    <constructor-arg value="kafka:..."/>
    <constructor-arg ref="kafkaComponent"/>
</bean>

or using Spring factory bean and method:
http://www.javabeat.net/create-spring-beans-using-factory-methods/

A: The easiest way to achieve this would be to create a class which implements the
org.apache.camel.Processor

interface and configure this in the spring xml file, e.g.
<bean id="sp" class="com.mycompany.SimpleProcessor"/>

In your route you can then reference this simply using the id you gave in the bean, e.g.
<to uri="sp" />

A: I would say that makes it a bit confusing to read although perhaps you have a good reason but when I look at the route I want to clearly know the endpoint details unless they are referenced above somewhere. To have to look up the endpoint in a java class can be cumbersome later on.
I recently found out that you can write your entire RouteBuilder logic in java and simply let the blueprint xml call it just like any other bean? That why your routes are in java and the startup mechanism in xml.

A: I know it's late but here's what i did to make this work. Basically i programmatically created the endpoints simply as "direct" endpoints based on configuration and reference those direct endpoints in my camel routes xml file. That way i avoided having environment specific values like hostnames, port numbers, etc., in my xml routes file and just have one version for all environments.


text:
Q: Why can't I connect to my remote MySQL Server? I have a asterisk server that is set up in on a VPS provider.  I need one of my local applications to connect to the database to pull reports, but I am having dificulty getting a read only connection to work.
I can see that the server is listening on port 3306:
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN

I have created a firewall exception:
 Chain INPUT (policy ACCEPT 12 packets, 2400 bytes)
 num   pkts bytes target     prot opt in     out     source               destination
 1     7326 1439K ELASTIX_INPUT  all  --  *      *       0.0.0.0/0            0.0.0.0/0

 Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 num   pkts bytes target     prot opt in     out     source               destination
 1        0     0 ELASTIX_FORWARD  all  --  *      *       0.0.0.0/0            0.0.0.0/0

 Chain OUTPUT (policy ACCEPT 215M packets, 43G bytes)
 num   pkts bytes target     prot opt in     out     source               destination
 1     7280 1542K ELASTIX_OUTPUT  all  --  *      *       0.0.0.0/0            0.0.0.0/0

 Chain ELASTIX_FORWARD (1 references)
 num   pkts bytes target     prot opt in     out     source               destination
 1        0     0 REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0                reject-with icmp-port-unreachable

 Chain ELASTIX_INPUT (1 references)
 num   pkts bytes target     prot opt in     out     source               destination
 1        0     0 ACCEPT     tcp  --  *      *       173.###.##.0/24       0.0.0.0/0           tcp spt:3306 dpt:3306
 2        0     0 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
 3        0     0 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0
 4        0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp dpts:67:68
 5       22  9834 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp dpts:5004:5082
 6        0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp dpt:4569
 7        0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp dpt:5036
 8     7065 1411K ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp dpts:10000:20000
 9        0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp dpt:2727
 10       0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp spt:53
 11       0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp dpt:69
 12       0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:25
 13       0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:110
 14       0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:143
 15      22  1857 ACCEPT     tcp  --  *      *       173.##.##.0/24       0.0.0.0/0           tcp dpt:443
 16       0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:993
 17       0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:995
 18       0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:5222
 19       0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:9090
 20     206 14216 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
 21       3   152 REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           reject-with icmp-port-unreachable

I have a read only user created:
GRANT SELECT ON *.* TO 'read_only'@'%' IDENTIFIED BY PASSWORD '******************'

But I continue to get the error :
Error number: 2003
Can't connect to MySQL server on '209.###.##.##' (0)

What am I missing here?

A: Your problem is that the client connection won't come from port 3306, but instead from a randomly-assigned ephemeral source port.  Remove the --sport 3306 and your listed servers should be able to connect.


text:
Q: How to make a function inside render() wait for component did mount hello I want my function called Monday() to wait for ComponentDidMount() before being called inside my render()
my component takes the ID of my student from the path and then runs into another backend route which returns an array of courses the student has.
and then that array of arrays gets divided into smaller arrays where every array has a course name course day and course time.
I want Monday function to display the name but it returns undefined because it gets called before my ComponentDidmount().
This is my code`

  componentDidMount() {
        console.log(this.props.match.params.id)
        if(this.props.match.params.id==='100')
        window.location='/passerror'
         axios.get('http://localhost:5000/users/'+this.props.match.params.id)
          .then(async response => {
            console.log(response.data.sections)
              this.setState({
                listA:response.data.sections.map(sections => sections)
              })
              console.log(this.state.listA)

              this.sortLists()
          })
          .catch((error) => {
          })
   }
     sortLists(x){
        console.log(x[0])
        if(this.state.listA[0]){
               this.state.listB.push(this.state.listA[0].name,this.state.listA[0].day,this.state.listA[0].time)

         }
         if(this.state.listA[1]){
            this.state.listC.push(this.state.listA[1].name,this.state.listA[1].day,this.state.listA[1].time)

      }
      if(this.state.listA[2]){
        this.state.listD.push(this.state.listA[2].name,this.state.listA[2].day,this.state.listA[2].time)

    }
    if(this.state.listA[3]){
        this.state.listE.push(this.state.listA[3].name,this.state.listA[3].day,this.state.listA[3].time)

    }

    console.log(this.state.listB.length,this.state.listC[0],this.state.listD,this.state.listE)
    }
    monday(e){
      console.log(this.state.listB[0])
      let coursename=this.state.listB[0];

    console.log(coursename)
      return(coursename)
    }
    render() {
        return (

              Day
              Monday
              Tuesday
              Wednesday
              Thursday
              Friday

              8:00AM - 9:30AM
               {this.monday()}

        )
      }
    }

A: You should not manually change state like this.state.listA[0] = xyz, you need to use this.setState
You shouldn't manually make something wait for componentDidMount to complete.
When componentDidMount is called and the data fetching is complete, it will set the state and cause react to render again, during this render it should have picked up the new value. It works in this sandbox: https://codesandbox.io/s/boring-matsumoto-ti9ot?file=/src/App.js
However, during the initial render, there is no data, so at this point you will need to display either a fallback value, or let it be empty until the data fetching is complete.
The sequence of operation goes like this:

*

*React initial render with no data available

*componentDidMount called, data fetching happens

*data fetching async returns, setState with new data

*state change causes react to update, and re-render

*render with new state which has data.

Make sure you understand how react lifecycle works: https://reactjs.org/docs/react-component.html


text:
Q: How to catch files uploaded using ajax with PHP I've this JavaScript code to upload a file
// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();

xhr.open("post", "pro/upload.php", true);

// Set appropriate headers
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);

// Send the file (doh)
xhr.send(file);

Now how do I catch the file at upload.php?
I tried with global $_FILES["file"] variable but an error says "Undefined Index". Does that mean the global variable is not set?

A: You should pass in Content-Disposition as well in setRequestHeader
Ref Link: Content-Disposition Reference

A: I am using Ajax file upload which is working perfect for me and it is easy to implement, If you like to work with jQuery please prefer this link.
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/


text:
Q: I want to show some text when make mouse over I want to show some text when make mouse over. Can you help me please? how can I hide and show text on image?  below my code.

.foodMenu {
 text-align: center;
 background-image: url(../img/burger.jpg);
 background-image: url(../img/burger.jpg);
 background-image: url(../img/burger.jpg);
 background-size: cover;
 background-position: center;
 height: 210px;
 width: 280px;
 }

.foodMenu .menuTitle {
 font-size: 22px;
 text-transform: none;
 }

.foodMenu .menuTitle:hover {

 }

Burgers

iv>

A:

.foodMenu {
 text-align: center;
 background-image: url(../img/burger.jpg);

    /****  Do not repeat your Commands
 background-image: url(../img/burger.jpg);
 background-image: url(../img/burger.jpg);
    ****/

 background-size: cover;
 background-position: center;
 height: 210px;
 width: 280px;

    /* positioning to make the text element inside the div */
    position:relative;
 }

.foodMenu .menuTitle {
 font-size: 22px;
 text-transform: none;

    /** position text element **/
    position:absolute;
    bottom:0;
    left:0;
    right:0;

    opacity:0; /* opacity to hide the element */
    background:rgba(0,0,0,.75); /* background for good looking */
    transition:all 0.3s; /* animation effect */
    -webkit-transition:all 0.3s; /* animation effect */
 }

.foodMenu:hover .menuTitle {
 opacity:1; /* opacity to show the element on mouse over */
 }

Burgers


text:
Q: How to escape quotes in solr nested query syntax? I.e. I want to search for phrase with nested queries syntax
so
_query_:"{!dismax qf=myfield}"how now""

How to solve this for first level?
How to solve this for any level? _query_:"_query_:"{!dismax qf=myfield}"how now"""

A: One option would be to dereference the parameter in the local params:
_query_:"{!dismax qf=myfield v=$query1}" then at the end of the url add query1="how how" and do that foreach query but change to query2 query3 etc.
see bottom of this page
http://wiki.apache.org/solr/LocalParams


text:
Q: React Native open link in browser with request body Currently I'm using Linking.openUrl(yourUrl?params) to open links into a browser, but it is very limited if you need to send parameters with that URL. Right now, the only way to do it is add them as params in the URL. The issue I'm running into is I'm trying to link from an app into a website and I want to auto login the user when landing on the site. The way to do this is to send session tokens that are way too long for the URL as parameters so that the website can use those tokens to determine who is landing on the page and auto log them in.
Is there a way to link from an app to the browser and send parameters in the body or a POST or something?


text:
Q: Requests to server how to scale for larger traffic demand I'm no expert on servers so i wanted to ask which is my best option for handling larger traffic in the long term..
I have two main options here with the use of javascript:
1) Place all HTML into one file, request once with Javascript, then use div id's to separate each page to their own JS variable to use when user visits a given link. This means 1 request for all HTML pages (not including CSS file and images), down side being the data being sent is alot larger, and it loads HTML pages the user may not even visit.
2) Keep the HTML to their own HTML pages and request the given HTML page when the user visits the page. This will result in more requests, but less data sent "per request" as well as only requesting content the user actually visits.
Which of the is generally going to be the best option long term ?

A: I would say 2 is the better option, for both development and performance.
Putting all your HTML in one file probably won't be scalable long-term. As your site gets more complex the file will just get larger and larger. This makes it harder to work on because you will have to scroll through the file too much to find what you need. Also, if you're working on this with other people merge conflicts will become more of a problem.
More requests isn't really a bad thing; single-page apps for example make LOTS of small requests, but often your static content will be cached and your dynamic content is small JSON over the wire.


text:
Q: Reflexivity axiom for inferring functional dependencies As you know, there are three Armstrong's Axioms for inferring all the functional dependencies on a relational database. (X, Y and Z are set of attributes)

*

*Reflexivity: If X ⊆ Y, then Y → X

*Augmentation: If X → Y, then XZ → YZ for any Z

*Transitivity: if X → Y and Y → Z, then X → Z
I understand the augmentation and transitivity for example if we had such schema:

SOME_SCHEMA(a, b, c, d)

with such functional dependencies:

*

*a → b

*b → c

By using augmentation we could get ac → bc or by using transitivity we could get a → c and much more, however I am not sure how to infer more functional dependencies using reflexivity axiom? What does it really mean that some attribute is a subset of some other attribute?
Could you show me an example using my schema or creating your own, please?

A: The transitivty rule can be also stated like this:
A1, A2, …, An → Ai

Where i is any number between 1 and n.  I think this definition of the rule is a bit clearer. A1 is a subset of A1 through An, and thus you can infer the above dependency.
These type of dependencies are called trivial dependencies.  The simplest form of this is:
A → A

As you can see, A is a subset of A, therefore by the definition of reflexivity, we can infer the above dependency.
This really isn't a very useful axiom, both of the first two axioms are not very useful on their own, but are there for formality sake, so we can get to the last axiom, which is very useful.
To use your example, we could say the following.  Given that we have the table:
SOME_SCHEMA(a, b, c, d)

We can infer such dependencies as:
a, b, c, d → a
a, b, c, d → a, c

And many more dependencies of the same nature.
By the way, here are some good slides that explain functional dependencies in general really well.  There a few slides on Armstrong's rules as well.  I found these helpful when learning this stuff: Functional Dependency Slides


text:
Q: Bill alone cannot solve this problem a. Bill alone cannot solve this problem. He needs help.
b. Bill alone cannot solve this problem. Everyone else in the class can.
Are both of the above grammatically correct?
Are they correctly punctuated?
In which case does one have to set off 'alone' with commas?
c. Bill, alone, cannot solve this problem.

A: They are both grammatically correct; they're using two different definitions of the adverb form.  See https://en.wiktionary.org/wiki/alone#Adverb
Example "a" appears to be usage 2.  Example "b" looks like usage 3.3.
Whether they're correctly punctuated is a matter of opinion, I think, as it's your second sentence in each example that provides the context to resolve the ambiguity.  You might opt to replace the usage in example "b" with something like "Only Bill is unable to solve this problem".


text:
Q: How to Pop a Codenameone Form to show previous Form So I was trying to build a custom UI among which there was back arrow (not the one that can be used from Form's toolbar in Codenameone) like this:
Now the issue is when I want to implement the actionListener of the back button, I don't seem to find the method to pop itself.
Yeah there is native support for back button with toolbar something similar to this :
    form.getToolbar().setBackCommand(title, evt -> menuCard.getComponentForm().showBack());

But i want to do something like this :

backButton.addActionListener {
        form.dispose()
        print("the form should dispose")
    }

where I want to hook the logic to dispose / dismiss the form to an actionListener of a Button  I can't do that as dispose() on Formis package private .
Then I did a hack
package com.codename1.ui;

import com.codename1.ui.layouts.Layout

class CustomForm constructor(contentPaneLayout: Layout) : Form(contentPaneLayout) {

    public override fun dispose() {
        super.dispose()
    }
}

But calling dispose() on this new Form does not dismiss the form either.
What is the right way to dismiss/dispose/pop a form from its's screen to show the previous form?


text:
Q: How to maintain the same ASP session during a redirect to SSL? I have a shopping cart website running classic ASP that needs help during the checkout process.  When a user is ready to checkout, they are redirected to an SSL version of the site.
Response.Redirect "https://example.com/beginCheckoutProcess.asp"

When the jump occurs, the customer starts a new session when they arrive at the SSL version of the site.  This means that the contents of their cart are lost, leaving them with a terrible experience on the site.
Is there a way to maintain the same ASP session across the jump to SSL?

A: If you keep the subdomain same it'll just work.

A: Have you tried setting a cookie and storing it on both ends? Then you can recreate the session on the other end.


text:
Q: Run ldd for a binary with parameter I know ldd can only take a binary as its parameter what I am asking here is how to run ldd with a binary, say, mybin, with parameter of the binary. For instance, mybin --myparam ./configfile.conf.
The linker will differ if I add the conf file for my binary because it loads some plugins in runtime with the plugins' shared object files, plugin1.so something like this. I have some undefined reference issue but I still got no idea which .so file I was missing.
If I run ldd ./mybin, everything is linked and running the plain binary is fine. Once I add the conf file for my binary, to let it loads some plugins shared library, then my binary will report errors when loading those library(coded exception throw, with some undefined reference error messages).
So if there is way to run ldd with mybin --myparam ./a.file something like this would help a lot.

A: Use the LD_DEBUG environment variable for this. To see the relevant options, run any command with LD_DEBUG=help. For example, running LD_DEBUG=help ls on my machine gives this output:
LD_DEBUG=help ls
Valid options for the LD_DEBUG environment variable are:

  libs        display library search paths
  reloc       display relocation processing
  files       display progress for input file
  symbols     display symbol table processing
  bindings    display information about symbol binding
  versions    display version dependencies
  scopes      display scope information
  all         all previous options combined
  statistics  display relocation statistics
  unused      determined unused DSOs
  help        display this help message and exit

To direct the debugging output into a file instead of standard output
a filename can be specified using the LD_DEBUG_OUTPUT environment variable.

One way of debugging your dlopens, or whatever late loading mechanism you are using, would be to run your executables with the relevant args with LD_DEBUG=all. This would give you a lengthy output detailing symbol lookups and search paths. This output would also tell you about resolution failures.


text:
Q: Match Symbol specific number of times When defining a syntax, it is possible to match 1 or more times (+) or 0 or more times (*) similarly to how it is done in regex. However, I have not found in the rascal documentation if it is possible to also match a Symbol a specific amount of times. In regex (and Rascal patterns) this is done with an integer between two curly brackets but this doesn't seem to work for syntax definition. Ideally, I'd want something like:
lexical Line = [0-9.]+;
syntax Sym = sym: {Line Newline}{5};

Which would only try to match the first 5 lines of the text below:
..0..
11.11
44.44
1.11.1
33333
55555

A: No this meta syntax does not exist in Rascal. We did not add it.
You could write an over-estimation like this and have a post-parse filter reject more than 5 items:
syntax Sym = fiveLines: (Line NewLine)+ lines

visit (myParseTree) {
   case (Sym) `<(Line NewLine)+ lines>` :
      throw ParseError(x.src) when length(lines) != 5;
}

Or unfold the loop like so:
syntax Sym
    =  Line NewLine
       Line NewLine
       Line NewLine
       Line NewLine
       Line NewLine
    ;

Repetition with an integer parameter sounds like a good feature request for us the consider, if you need it badly. We only have to consider what it means for Rascal's type-system; for the parser generator its a simple rule to add.


text:
Q: Redirect to action pass complex model I want to pass to RedirectToAction model with List type property
For example, I have this simple model:
public class OrgToChooseFrom
    {
        public string OrgId { get; set; }
        public string FullName { get; set; }
    }

And complex model as this:
public class SelectCounteragentViewModel
    {
        public List<OrgToChooseFrom> Counteragents { get; set; }
        public OrgToChooseFrom SelectedOrg { get; set; }
    }

When I pass simple model with RedirectToAction every value is in place
        [HttpGet]
        public IActionResult ConfirmChoice(OrgToChooseFrom vm)
        {
            return View(vm);
        }

But when I try to pass complex model SelectCounteragentViewModel, there are empty list and null for the "SelectedOrg" field
        [HttpGet]
        public IActionResult SelectFromCAOrganizations(SelectCounteragentViewModel vm)
        {
            return View(vm);
        }

How can I do it?

A: RedirectToAction cannot pass complex model.You can try to use TempData as
Kiran Joshi said.Here is a demo:
public IActionResult Test()
        {

            SelectCounteragentViewModel vm = new SelectCounteragentViewModel { Counteragents = new List<OrgToChooseFrom> { new OrgToChooseFrom { OrgId ="1", FullName = "d" } }, SelectedOrg = new OrgToChooseFrom { OrgId = "1", FullName = "d" } };
            TempData["vm"] = JsonConvert.SerializeObject(vm);
            return RedirectToAction("SelectFromCAOrganizations", "ControllerName");
        }
[HttpGet]
        public IActionResult SelectFromCAOrganizations()
        {
            SelectCounteragentViewModel vm = JsonConvert.DeserializeObject<SelectCounteragentViewModel>(TempData["vm"].ToString());
            return View(vm);
        }


text:
Q: How to redirect the output of time command to a log file? I have a few servers which are acting strangely, so in order to find the problem, I wrote some bash script which is supposed to run some basic tests and output them to a log file.
The script looks like that:
#!/bin/bash
PENDERLIST="/root/pender.list"
PING="/bin/ping"
ETHTOOL="/sbin/ethtool"
FILE="/root/14mfile"
function writelog
{
        echo "$(/bin/date +%F) $(/bin/date +%R): $*"
}
for SRV in $(cat $PENDERLIST); do
writelog "################### Begin $SRV ########################"
echo "### PING ###"
$PING $SRV -c 2
ssh root@$SRV "yum install lshw -y"
echo "### Uname -a ###"
ssh root@$SRV "uname -a"
echo "### Release ###"
ssh root@$SRV "/bin/cat /etc/*release*"
LSHW=$(ssh root@$SRV "lshw -C network |grep eth | awk 'NR==1' ")
NIC=$(echo $LSHW |  awk -F: '{print $2}')
echo "### IFCONFIG ###"
ssh root@$SRV "ifconfig"
echo "### ETHTOOL ###"
ssh root@$SRV "ethtool $NIC"
echo "### FILE TRANSFER ###"
time scp $FILE root@$SRV
writelog "############## End of report for $SRV #################"
done

I'm running it like so:
./check_server.sh > log.txt

All the output is written to the log successfully apart from the time command there.
I've tried changing the command to:
(time scp $FILE root@$SRV) 2> log.txt
{ time ls; } 2> out.txt

But both print the output of time to the screen rather than to the log.txt file.
How can I redirect time's output to the log?
Edit #1:
While checking the log, at the line where the output of time should be, I see this:
### FILE TRANSFER ###
2014-11-23 02:31: ############## End of report for pender4.company.com #################
2014-11-23 02:31: ################### Begin pender5.company.com ########################

A: time command is shell keyword... when your run time command in terminal it's not /usr/bin/time so the options like -a and  -o will not work with time command. However man time will still display man page of /usr/bin/time .You have to use /usr/bin/time -o logfile command  to redirect the time's output to file logfile or you can use the following command which is similar to shell's keyword time:
/usr/bin/time -o time_log -f "%E real,%U user,%S sys" [command] [args] to redirect the time's output to file time_log


text:
Q: how to hide menu options in jsp/html pages according to user logged in I menu option according to the user logged in.
I have created a simple login page with header.jsp, footer.jsp, user bean, servlet and dao. In header.jsp I have created menu options  that contains AddDayWork, WeekTimeSheet, AddNewEmployee, RetrieveTimeSheet buttons for admin & manager. And for employees only AddDayWork, WeekTimeSheet buttons must be shown.  If the login user is not admin or manager I don't want them to have access for AddNewEmployee, RetrieveTimeSheet buttons. please help
header.jsp

DayWise TimeSheet

Weekly TimeSheet

Add New Employeer

Retrieve TimeSheet

Index.jsp

                User ID
                <input type="text" name="Emp_id" required="required" />

                Password
                <input type="password" name="Pwd" required="required" />

                <input type="submit" value="Login" />

LoginServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String n=request.getParameter("Emp_id");
    String p=request.getParameter("Pwd");

    HttpSession session = request.getSession(false);
    if(session!=null)
    session.setAttribute("name", n);

    if(LoginDao.validate(n,p)){
        RequestDispatcher rd=request.getRequestDispatcher("timesheet.jsp");
        rd.forward(request,response);
    }
    else{
        out.print("
Sorry Employee ID or password error
");
        RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
        rd.include(request,response);

    }

    out.close();
}
 protected void doPost(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
    doGet(request, response);
}

LoginDao.java
public class LoginDao {

public static boolean validate(String name, String pass) {

    boolean status = false;
    PreparedStatement pst = null;
    ResultSet rs = null;
    try{
            Connection conn=ConnectionProvider.getConn();

        pst = conn.prepareStatement("select * from employee where Emp_id=? and Pwd=?");
        pst.setString(1, name);
        pst.setString(2, pass);

        rs = pst.executeQuery();
        status = rs.next();

    } catch (Exception e) {
        System.out.println(e);
    }
 return status;
}
}

A: You have to create RBS (ROll Based System)
1. create a table to store the rolls of user
2. match with roll and write the code in if else statement ex:-
//For admin
if(rollId == 1){
//  write code for other admin
}else{
   // write code for other user
 }


text:
Q: Disticnt id when i'm using join I need to eliminate duplicate ids.I have already tried the code below, but when i'm using it it doesnt appears me anything.
Select disticnt i.id,b.barcode,i.code,i.name,i.price
from inventory i
join barcodes b on i.id=b.id

The problem is that i get same ids cause i have much different barcodes which fixs in one id. How can i eliminate duplicate ids

A: The problem is that the barcodes table might have multiple rows for each id in the inventory table. In order to get only one record from the inventory table you must first need to figure out what barcode would you like to get back for each id that have multiple barcodes. One way is to use group by with max or min:
SELECT i.id,
       MAX(b.barcode) as barcode,
       i.code,
       i.name,
       i.price
FROM inventory i
JOIN barcodes b on i.id=b.id
GROUP BY i.id, i.code, i.name, i.price


text:
Q: Unrecognized Selector - [NSView borderRect] I'm having trouble getting the NSRect of a view's border.  I keep getting an unrecognized selector error.
Here is the code:
NSGradient *BorderGradient = [[NSGradient alloc] initWithStartingColor:[NSColor blackColor] endingColor:[NSColor whiteColor]];
[BorderGradient drawInRect:[self.window.contentView borderRect] angle:-90];
// Unrecognized Selector error here

I'm trying to access the border rect to add a color gradient to the border.  The code also crashes when I try to access the borderRect by itself, like this:
NSRect rect = [self.window.contentView borderRect];
NSLog(@"origin.x = %f", rect.origin.x);

And if trying to convert the drawInRect: to CGRect.  Like so:
NSGradient *BorderGradient = [[NSGradient alloc] initWithStartingColor:[NSColor blackColor] endingColor:[NSColor whiteColor]];
[BorderGradient drawInRect:NSRectToCGRect([self.window.contentView borderRect]) angle:-90];
// Unrecognized Selector error here

Any help would be greatly appreciated.
Thanks!

A: NSView (what is returned from self.window.contentView) does not have a borderRect method, which is causing the Unrecognized Selector error.
You probably want frame or bounds instead.

A: NSView doesn't have a method named -borderRect. Is it a custom method you've implemented? NSBox does have a -borderRect method. Are you expecting your window's content view to be an instance of NSBox? Have you checked to see that that's actually true.
Perhaps you really want -frame or -bounds?


text:
Q: How can I convert this data set into an object I would like to convert this data set into an object.

Intended outcome
let data = [
  {
    "Year Group": "Year Six",
    "Sunday": [Girl's football],
    "Monday": [No clubs on this day],
    "Tuesday": [Girls Netball]
  },
  {
    "Year Group": "Year Five",
    "Sunday": [Boys football],
    "Monday": [No clubs on this day],
    "Tuesday": [Girls Netball]
}
]

This data will then be used to create a branching Google form. If there is a better object structure in order to achieve this, please do let me know.
Thank you,
For those that may need it. Following one of the answers, I realised it would be better if I had a situation where only the days unique to the year group were stored in the year group object.
Below is the adapted code based on one of the answers by 'TheWizEd'.
let values = ws.getDataRange().getValues();
    let data = [];
    values.shift();  // remove headers
    // create year groups
    let yearGroups = [...new Set(values.map( row => row[1] ))];

    yearGroups.forEach((group) => {
      let sorted = values.filter( row => row[1] ===  group )
      let days = [...new Set(sorted.map((row)=> row[4] ))]
      let dayBlankArray = days.map( day => [] )
      sorted.forEach((e)=>{
        let index = days.indexOf(e[4]);
        if( index >= 0 ) dayBlankArray[index].push(e[0]);
      })
      let object = { "Year Group": group };
      days.forEach((day,index)=> {
        object[day] = dayBlankArray[index]

      })
      data.push(object);
    })
    return data
}

A: Here is an example of how to sort and create groups by year.
Code.gs
function createGroups() {
  try {
    let days = ["Sunday","Monday","Tuesday","Wednesday"];
    let spread = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = spread.getSheetByName("Sheet1");
    let values = sheet.getDataRange().getValues();
    let data = [];
    values.shift();  // remove headers
    // create year groups
    let groups = [...new Set(values.map( row => row[1] ))];
    console.log("groups = "+groups)
    groups.forEach( group => {
        let activities = days.map( day => [] );
        // sort by group
        let sorted = values.filter( row => row[1] ===  group );
        // nest sort by day
        sorted.forEach( activity => {
            let index = days.indexOf(activity[4]);
            if( index >= 0 ) activities[index].push(activity[0]);
          }
        );
        // now construct the object
        let object = { "Year Group": group };
        let numDays = days.length;
        days.forEach( (day,index) => {
            if( activities[index].length === 0 ) {
              activities[index].push("No clubs on this day");
              numDays--;
            }
            object[day] = activities[index];
          }
        );
        object["Num Days"] = numDays;
        data.push(object);
      }
    );
    console.log(data);
  }
  catch(err) {
    console.log(err)
  }
}

Execution log
9:34:27 AM  Notice  Execution started
9:34:28 AM  Info    groups = Year Five,Year Six,Year Seven,Year One,Year Two
9:34:28 AM  Info    [ { 'Year Group': 'Year Five',
    Sunday: [ 'Girls Football', 'Boys Football' ],
    Monday: [ 'No clubs on this day' ],
    Tuesday: [ 'Girls Netball' ],
    Wednesday: [ 'No clubs on this day' ] },
  { 'Year Group': 'Year Six',
    Sunday: [ 'Girls Football' ],
    Monday: [ 'No clubs on this day' ],
    Tuesday: [ 'Girls Netball' ],
    Wednesday: [ 'No clubs on this day' ] },
  { 'Year Group': 'Year Seven',
    Sunday: [ 'Girls Football', 'Boys Football' ],
    Monday: [ 'No clubs on this day' ],
    Tuesday: [ 'Girls Netball' ],
    Wednesday: [ 'No clubs on this day' ] },
  { 'Year Group': 'Year One',
    Sunday: [ 'No clubs on this day' ],
    Monday: [ 'No clubs on this day' ],
    Tuesday: [ 'Multi Sports' ],
    Wednesday: [ 'Gymnastics' ] },
  { 'Year Group': 'Year Two',
    Sunday: [ 'No clubs on this day' ],
    Monday: [ 'No clubs on this day' ],
    Tuesday: [ 'Multi Sports' ],
    Wednesday: [ 'Gymnastics' ] } ]
9:34:28 AM  Notice  Execution completed

Reference

*

*Array.map()

*[...new Set()]

*Array.forEach()

*Array.filter()

*Array.indexOf()