text:
Q: Logback - How to get ListAppender instance I'm using a logging client/server architecture with SocketAppender in the client, and SimpleSocketServer in the server.
I want to store all the logs in a Java List for later processing. I think I can use the ListAppender, which has a backing List collection.
I got the Console and Rolling appenders working, but I have no idea how to get the ListAppender instance so I can access the logs.
Client config file
<?xml version="1.0" encoding="UTF-8" ?>

<!-- ==================================================================== -->
<!-- SocketAppender configuration file.                                   -->
<!-- ==================================================================== -->

<configuration>

  <appender name="SOCKET" class="ch.qos.logback.classic.net.SocketAppender">
    <RemoteHost>127.0.0.1</RemoteHost>
    <Port>6000</Port>
    <ReconnectionDelay>5000</ReconnectionDelay>
    <IncludeCallerData>true</IncludeCallerData>
  </appender>

  <root level="debug">
    <appender-ref ref="SOCKET" />
  </root>

</configuration>

Server config file
<?xml version="1.0" encoding="UTF-8" ?>

<!-- ==================================================================== -->
<!-- This config file is intended to be used by a SocketServer that logs  -->
<!-- events received from various clients on the console and to a file    -->
<!-- that is rolled over when appropriate. The interesting point to note  -->
<!-- is that it is a configuration file like any other.                   -->
<!-- ==================================================================== -->

<configuration>

  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">

    <layout class="ch.qos.logback.classic.PatternLayout">
      <Pattern>%date %-5level [%thread] %logger - %message%n</Pattern>
    </layout>

  </appender>

  <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>rolling.log</File>

        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <FileNamePattern>rolling.%i.log</FileNamePattern>
            <MinIndex>1</MinIndex>
            <MaxIndex>3</MaxIndex>
        </rollingPolicy>

        <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>8KB</MaxFileSize>
        </triggeringPolicy>

    <layout class="ch.qos.logback.classic.PatternLayout">
      <Pattern>%relative %-5level %logger - %message%n</Pattern>
    </layout>
  </appender>

  <appender name="LIST"  class="ch.qos.logback.core.read.ListAppender"/>

  <root>
    <level value ="debug"/>
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="ROLLING" />
  </root>
</configuration>

A: In order to use ListAppender, I was missing to attach it to the root logger in the server xml file. Check the root tag in the server config file below.
<?xml version="1.0" encoding="UTF-8" ?>

<!-- ==================================================================== -->
<!-- This config file is intended to be used by a SocketServer that logs  -->
<!-- events received from various clients on the console and to a file    -->
<!-- that is rolled over when appropriate. The interesting point to note  -->
<!-- is that it is a configuration file like any other.                   -->
<!-- ==================================================================== -->

<configuration>

  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">

    <layout class="ch.qos.logback.classic.PatternLayout">
      <Pattern>%date %-5level [%thread] %logger - %message%n</Pattern>
    </layout>

  </appender>

  <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>rolling.log</File>

        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <FileNamePattern>rolling.%i.log</FileNamePattern>
            <MinIndex>1</MinIndex>
            <MaxIndex>3</MaxIndex>
        </rollingPolicy>

        <triggeringPolicy
            class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>8KB</MaxFileSize>
        </triggeringPolicy>

    <layout class="ch.qos.logback.classic.PatternLayout">
      <Pattern>%relative %-5level %logger - %message%n</Pattern>
    </layout>
  </appender>

  <appender name="LIST"  class="ch.qos.logback.core.read.ListAppender"/>

  <root>
    <level value ="debug"/>
<!--    <appender-ref ref="CONSOLE" />-->
<!--    <appender-ref ref="ROLLING" />-->
    <appender-ref ref="LIST" />
  </root>
</configuration>

After that, it's trivial to get the list appender in Java:
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.slf4j.LoggerFactory;

Logger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
ListAppender<ILoggingEvent> listAppender = (ListAppender<ILoggingEvent>) rootLogger.getAppender("LIST");


text:
Q: How do I initialize a CompositionTarget to null using the Rust Crate for Windows? Specifically, what is the correct way to initialize the CompositionTarget member in the following Rust Crate for Windows CoreApp code excerpt?
#[implement(Windows::ApplicationModel::Core::IFrameworkView)]
struct AppView {
    target: CompositionTarget,
}

#[allow(non_snake_case)]
impl AppView {
    fn new() -> Self { //
        Self {
            //target: std::ptr::null_mut(),
            //target: CompositionTarget(0),
        }
    }

    fn Initialize(&self, _: &Option<CoreApplicationView>) -> Result<()> {
        Ok(())
    }

    fn Load(&self, _: &HSTRING) -> Result<()> {
        Ok(())
    }

    fn Uninitialize(&self) -> Result<()> {
        Ok(())
    }

    fn Run(&self) -> Result<()> {
        let window = CoreWindow::GetForCurrentThread()?;
        window.Activate()?;

        let dispatcher = window.Dispatcher()?;
        dispatcher.ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit)?;

        Ok(())
    }

    fn SetWindow(&self, _: &Option<CoreWindow>) -> Result<()> {
        let compositor = Compositor::new()?;
        let root = compositor.CreateContainerVisual()?;
        //...
        Ok(())
    }
}

fn main() -> Result<()> {
    unsafe {
        CoInitializeEx(std::ptr::null_mut(), COINIT_MULTITHREADED)?;
    }

    let app: IFrameworkViewSource = App().into();
    CoreApplication::Run(app)?;
    Ok(())
}

A: Rust does not have null. Instead, you should use Option:
struct AppView {
    target: Option<CompositionTarget>,
}

impl AppView {
    fn new() -> Self {
        Self {
            target: None,
        }
    }
    ...

This works well since in the windows crate a CompositionTarget cannot be null, any function that would return a null value will return an Option::None or Err(Error::Ok) instead. See this issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get the "name" of a key from QKeyEvent in Qt Is there an easy way of getting the name of a key (so something like "uparrow" from a key event instead of just getting the key code "16777235")? Do I have to make a list of key names myself?

A: Another approach leverages the Qt metaobject system and the introspection into most enumerations in the Qt namespace. This works in both Qt 4 and Qt 5.
// https://github.com/KubaO/stackoverflown/tree/master/questions/keyname-21764138
#include <QMetaEnum>

namespace SO {
enum KeyNameOption { KeyNameNone = 0, AppendArrow = 1 };
Q_DECLARE_FLAGS(KeyNameOptions, KeyNameOption)
}
QString keyName(int index, SO::KeyNameOptions opt = {}) {
   constexpr static auto const getEnum = [](const char *name) {
      int enumIndex = qt_getQtMetaObject()->indexOfEnumerator(name);
      return qt_getQtMetaObject()->enumerator(enumIndex);
   };
   static const auto keyEnum = getEnum("Key");
   static const auto modifierEnum = getEnum("KeyboardModifiers");

   auto name = modifierEnum.valueToKeys(index & Qt::KeyboardModifierMask);
   index &= ~Qt::KeyboardModifierMask;

   if (name == "NoModifier")
      name.clear();
   else {
      name.replace('|', '+');
      name.replace("Modifier", "");
      name.append('+');
   }

   auto keyName = keyEnum.valueToKey(index);
   if (keyName)
      name.append(keyName + 4);
   if ((opt & SO::AppendArrow) && index >= Qt::Key_Left && index <= Qt::Key_Down)
      name.append(" Arrow");
   return QLatin1String(name);
}

int main() {
   Q_ASSERT(keyName(Qt::Key_Tab) == "Tab");
   Q_ASSERT(keyName(Qt::ShiftModifier | Qt::Key_Up, SO::AppendArrow) == "Shift+Up Arrow");
   Q_ASSERT(keyName(Qt::AltModifier | Qt::Key_Down) == "Alt+Down");
}

You'd then use it in, say, keyPressEvent, as follows:
void MyWidget::keyPressEvent(QKeyEvent * ev) {
  qDebug() << keyName(ev->key());
}

A: Using human-readable names in your code
You can use the Qt::Key enum, or get the key as a string with QKeyEvent::text().
From QKeyEvent documentation:

int QKeyEvent::key () const
Returns the code of the key that was pressed or released.
See Qt::Key for the list of keyboard codes. These codes are independent of the underlying window system. Note that this function does not distinguish between capital and non-capital letters, use the text() function (returning the Unicode text the key generated) for this purpose.
...

Qt::Key is an enum that maps numeric key IDs (like the return value of QKeyEvent::key()) to programmer-readable names like Qt::Key_Up.
If you only care about alphanumeric keys, you can also use QKeyEvent::text() to get the value:

QString QKeyEvent::text () const
Returns the Unicode text that this key generated. The text returned can be an empty string in cases where modifier keys, such as Shift, Control, Alt, and Meta, are being pressed or released. In such cases key() will contain a valid value.
See also Qt::WA_KeyCompression.

Displaying human-readable names to the user
Use QKeySequence::toString() or build your own table of "nice" names.
The easiest way to get human-readable key names to show to the user is to use QKeySequence::toString().
Here's an example:
Qt::Key key = Qt::Key_Up;
qDebug() << QKeySequence(key).toString(); // prints "Up"

If you don't like the names that QKeySequence uses (e.g. you want to use "Up Arrow" instead of "Up"), you'll need to make your data table to remap the enum values to your preferred names.


text:
Q: How to create a slider in GMS3 I would like to create a slider dialog in dm-script, which enables users to change the number value in the text field.
Is there an appropriate way to create such a spin slider? It will be appreciated if you share some wisdom. Thank you very much in advance.

A: Scripted dialogs do currently not support sliders at all.
You could create "spin controls" by creating two arranged push-buttons and an edit field though.
You may also want to look at this answer here on spin controls


text:
Q: ¿Hay una forma de utilizar populate() dentro de la información que se ha traído con otro populate? Mi consulta originalmente trae esto:
{
    "payload": {
        "_id": "622a12390c6e374f5427754c",
        "idOffices": "621786b0582c3f4d68107d67",
    }
}

por medio de populate al campo idOffices obtengo esto:
"payload": {
        "_id": "622a12390c6e374f5427754c",
        "idOffices": {
            "_id": "621786b0582c3f4d68107d67",
            "idVenues": "621650a2bac1f704507c7474",
            "office": "Prueba",
            "floor": 10,
            "capacity": 154,
            "status": true,
            "createdAt": "2022-02-24T13:22:56.591Z",
            "updatedAt": "2022-02-24T13:22:56.591Z"
        },
    }

La pregunta es: ¿hay alguna forma de utilizar populate en el campo idVenues y que traiga la info de esa collección, aunque ese campo no esté en el schema?
Este es mi Schema
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, SchemaTypes, Types } from 'mongoose';

export type sitesDocument = SitesSchemas & Document;

@Schema({ versionKey: false, timestamps: true })
export class SitesSchemas {

  @Prop({type:SchemaTypes.ObjectId, required:true, ref:'Offices._id'})
  idOffices:Types.ObjectId;

  @Prop({ required: true })
  name: string;

  @Prop({ required: true })
  capacity: number;

  @Prop({ required: true })
  status: boolean;
}
export const sitesSchema = SchemaFactory.createForClass(SitesSchemas);
export const sitesCollection = {
  name: 'sites',
  collection: 'Sites',
  schema: sitesSchema,

};

Como el campo idVenues lo obtengo con populate() no lo incluí en el schema.

A: Para traer nested collections puedes checar la documentación de Mongoose en este apartado.
Pero básicamente tendrías que ejecutar el query de esta manera:
PayloadModel.findOne({id})
.populate({
    path: 'idOffices',
    populate: { path: 'idVenues' }
 });

Pregunta: La última parte de tu post dice que idVenues no está en el Schema de idOffices. Por qué idVenues no estaría en el Schema de idOffices? Incluye idVenues en el Schema de idOffices. Si algunas idOffices no necesitan ese campo, el campo simplemente no se rellenará.


text:
Q: Installing Ubuntu 16.04 in my laptop I have seen some posts related to installation of ubuntu 16.04 but couldn't figure out anything. Let me make few honest statements. In the first place I dont even know how to install an operating system. Secondly I see that to install ubuntu I have to first download it. I do not know which all files to download. It is my earnest request if someone can give step by step details right from downloading to installing in minutest details.
I have a Dell Inspiron system
Windows 10 installed
4 GB RAM
500 GB Hard Disk
Processor- Intel

A: For dual boot follow these steps to install Ubuntu alongside Windows 10
(taken from https://verdictforu.com/2016/09/06/how-to-dual-boot-ubuntu-16-04-and-windows-10/)

Step 1: Prepare Windows Machine for Dual-Boot

*

*The first thing you need to take care is to create a free space on the computer hard disk in case the system is installed on a single
partition.
Login to your Windows machine with an administrative account and
right click on the

Start Menu -> Command Prompt (Admin)

in order to enter Windows Command Line.

*Once in CLI, type diskmgmt.msc on prompt and the Disk Management utility should open. From here, right click on C:(or whichever
partition you want) partition and select Shrink Volume in order to
resize the partition.
C:\Windows\system32>diskmgmt.msc

*On Shrink C:(or your selected partition) enter a value on space to shrink in MB (use at least 20000 MB depending on the your partition
size) and hit Shrink to start partition resize as illustrated below
(the value of space shrink from below image is lower and only used for
demonstration purposes).
Once the space has been resized you will see a new unallocated
space on the hard drive. Leave it as default and reboot the computer
in order to proceed with Ubuntu 16.04 installation.

Step 2: Install Ubuntu 16.04 with Windows Dual-Boot

*

*Download Ubuntu 16.04 LTS ISO file.
Download ISO file of Ubuntu 16.04 LTS from their official
website
Once the ISO file is downloaded, burn it into a USB pendrive or DVD
and Boot your system with bootable USB Pen drive or DVD.

*Select 'Install Ubuntu' to start installation.

*Preparing to Install Ubuntu 16.06 LTS
In case your system is connected to the Internet and wants to
install third party tools during installation, you can select both the
options as shown in below snap otherwise leave the options uncheck.

*Now it's time to select an Installation Type. You can choose to Install Ubuntu alongside Windows Boot Manager, option that will
automatically take care of all the partition steps.
Use this option if you don't require personalized partition scheme.
In case you want a custom partition layout, check the Something else
option and hit on Continue button to proceed further.
The option Erase disk and install Ubuntu should be avoided on
dual-boot because is potentially dangerous and will wipe out your
disk.

*On this step we'll create our custom partition layout for Ubuntu 16.04. On this guide will recommend that you create two partitions, one for root and the other for home accounts data and no partition
for swap (use a swap partition only if you have limited RAM
resources or you use a fast SSD).
To create the first partition, the root partition, select the
free space (the shrink space from Windows created earlier) and hit on
the + icon below. On partition settings use the following
configurations and hit OK to apply changes:

*

*Size = at least 20000 MB

*Type for the new partition = Primary

*Location for the new partition = Beginning

*Use as = EXT4 journaling file system

*Mount point = /

Create the home partition using the same steps as above. Use all
the available free space left for home partition size. The partition
settings should look like this:

*

*Size = all remaining free space

*Type for the new partition = Primary

*Location for the new partition = Beginning

*Use as = EXT4 journaling file system

*Mount point = /home

Create a Swap partition and give a size to swap, mostly it is
double of your ram size. so if ram is 2 gb swap should be 4 gb.

*If you don't want to create a swap partition than hit the Install Now button in order to apply changes to disk and start the
installation process.
A pop-up window should appear to inform you about swap space.
Ignore the alert by pressing on Continue button.
Next a new pop-up window will ask you if you agree with committing
changes to disk. Hit Continue to write changes to disk and the
installation process will now start.

*On the next screen adjust your machine physical location by selecting a city nearby from the map. When done hit Continue to move
ahead.

*Next, select your keyboard layout and click on Continue button.

*Pick up a username and password for your administrative sudo account, enter a descriptive name for your computer and hit Continue
to finalize the installation.
This are all the settings required for customizing Ubuntu 16.04
installation. From here on the installation process will run
automatically until it reaches the end.

*After the installation process reaches its end hit on Restart Now button in order to complete the installation.
The machine will reboot into the Grub menu, where for ten seconds, you will be presented to choose what OS you wish to use further:
Ubuntu 16.04 or Microsoft Windows.
Ubuntu is designated as default OS to boot from. Thus, just press Enter key or wait for those 10 seconds timeout to drain.

*After Ubuntu finishes loading, login with the credentials created during the installation process and enjoy it. Ubuntu 16.04 provides
NTFS file system support automatically so you can access the files
from Windows partitions just by clicking on the Windows volume.

That's it! In case you need to switch back to Windows, just reboot the
computer and select Windows from the Grub menu.
Images are taken from - Tecmint and Linuxtechi
Hope it helps you to dual boot Ubuntu with Windows 10.

A: If your laptop has a dvd reader go to the Ubuntu website and download Ubuntu 16.04 desktop and burn the iso to a dvd.  If you use the subject laptop to download, Ubuntu will select the correct architecture (32 or 64 bit).  If you use another machine and you don't know the laptop architecture, select 32 bit.  Then boot your laptop from the dvd (enter the laptop BIOS and set the boot priority to CD/DVD reader if needed).  Explore the option to test Ubuntu without installing to check hardware compatibility.  If you like, then select the install option from the Ubuntu desktop.
how to install Ubuntu

A: It's not too difficult. First, you need to download Ubuntu. To do that, go to the download page on the website, click the "Download" button, and then click the "Take me to the the download" link at the bottom of the page (unless you want to donate..). The download will start automatically.
Once you've downloaded the ISO file, you need to decide weather to install from a DVD or from a USB stick. If you want to to use a DVD, you will need need a blank DVD. If you want to use a USB stck (flash drive), you'll need a flash drive (obviously..). If you're using a DVD, read the burning a DVD guide. If you're using a flash drive, read the Creating a bootable USB stick on windows, and follow the instructions there to put the ISO file on the USB stick or burn a DVD.
Then, restart your computer, with the USB stick connected, or the DVD in the drive, and follow the installation instructions (which are pretty simple). It will also give you options weather to install Ubuntu alongside windows, or to replace Windows entirely. See the installation guide for details.
Let me know if you get stuck somewhere, and I'll try to help.

A: You might want to also consider using VirtualBox to install it inside windows, Any errors you make learning Ubuntu will be MUCH less likely to hurt your windows install. When you have more confidence, you can go ahead with a dual boot install.


text:
Q: How to pass the number values from angular to webapi this is my code
model.ts
export class Customer {
    customer_id :number
    firstname : string
    lastname : string
    email : string
    telephone : number
    password : string
}

component.ts
resetForm(form? : NgForm)
  {
    if(form!=null)
          form.reset();
      this.customerService.selectedCustomer=
      {
        customer_id : null,
        firstname :'',
        lastname :'',
        email :'',

        password:'',
        telephone: //i want to pass 10 digit no here

      }

I want to pass telephone number to webapi form angular 5.how to achieve it

A: Change your model class to below
export class Customer {
customer_id :number
firstname : string
lastname : string
email : string
telephone : string
password : string }

You can pass it as string value to controller.
Then in future even if the format of number changes it would be easy to post.
resetForm(form? : NgForm)
{
  if(form!=null)
      form.reset();
  this.customerService.selectedCustomer=
   {
    customer_id : null,
    firstname :'',
    lastname :'',
    email :'',
    password:'',
    telephone: ''
  }


text:
Q: Import local packages as modules not in the React-Native project In a React-Native project, I found that if your local package has a valid package.json file, you can import that like a module in node_modules without a relative path .
For example,
app/                             # a React-Native project
  |- any_folder_for_packages/
  |   |- foo/
  |       |- package.json
  |       |- index.js
  |- src/
  |   |- bar/
  |       |- bar.js
  |- ...

In this case, you can import the package foo in the bar.js using either:
// with a relative path
import foo from '../../any_folder_for_packages/foo';

or
// like a module (without a relative path)
import foo from 'foo';

The packager will try to find and use any local module which contains a package.json matching the requirement.
The question
I have a local package which is not in the React-Native project, how can I import it
projects/
  |- app/                # a React-Native project
  |   |- src/
  |   |   |- bar/
  |   |       |- bar.js  # need to import the package foo as a module which is not in this project
  |   |- ...
  |- other_paths/
      |- foo/
          |- package.json
          |- index.js

I tried to use
// like a module (without a relative path)
import foo from 'foo';

but it failed to find the module.
How can I use react-native to find the package when packing for development or bundling for the production?

A: Answer given by @Plague doesn't work in react native. You have to configure your metro.config.js file to use a local package.
If Using Expo
In expo, metro.config.js file may not be visible, so in the root directory of your project, run this command;
npx expo customize metro.config.js

This will generate the file for you with some default configuration. Now to import any package, you have to modify two things here;
config.resolver.nodeModulesPaths, to include the package, and ;
config.watchFolders to keep a watch on the package.
In nutshell, metro.config.js file should be like this;
// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require("expo/metro-config");

const config = getDefaultConfig(__dirname);

const packagePath = "/full/path/to/package";

// here i added the packagePath to the list in the configuration to include it
config.resolver.nodeModulesPaths.push(packagePath);

// here i added the package again to another configuration key, to keep a watch on it if we make any changes.
config.watchFolders.push(packagePath);

module.exports = config;

That is it, but your code editor may report that module is not found, for that warning to remove, you can just run the command below;
npm install /path/to/package

BUT there is a problem with this
The dependencies in our package conflicts with that of main project.
So here is another way of installing a local package.
Using install-local
For this we don't need to make any changes to any file. We just need to install this package;
npm install install-local

And then install the local package using this;
npx install-local --save path/to/package

A: You will need to make your application aware of it through your root package.json files.
Confirm the new local module has a basic package.json configured.
For example:
{
  "name": "foo",
  "version": "0.0.1"
}

Ensure the package has an index.js and that it has something exported or export default.
For example, at the bottom of the index.js:
export default foo;
Then, simply save the package as a project dependency in your root module to via NPM.  To do this and install it automatically into your node_modules you can use this command.
npm install --save file:other_paths/foo

note make sure you have the correct relative path from your general project package.json to your new module package.json.
Example, in this case it would be:
app/                          # a React-Native project root
  |- other_paths/
  |   |- foo/
  |      |- package.json      # new module package json
  |      |- index.js
  |- src/
  |   |- bar/
  |       |- bar.js
  |- package.json             # project package json

If set up correctly you should then be able reference the module anywhere in your project without relative path.
import Foo from 'foo';


text:
Q: If timestamp falls between other 2 timestamp of same person for another booking I have a table below.
booking_person TABLE
What i am trying to check is if there is any overlap of time (not date) of person in any other booking. As person can not be at 2 places at same time. Its fine if booking start time is same as end time of another booking.
I am using query below but it returns me nothing but the screenshot i have attached there is overlap of time. Booking end time of booking_id 1 falls between start and end time of booking_id 2.
select * from booking_person y
where exists (
    select 1 from booking_person y2
    where y.booking_id <> y2.booking_id
    and y.person_id = y2.person_id
    and FROM_UNIXTIME(y.date_time) BETWEEN FROM_UNIXTIME(y2.date_time) and FROM_UNIXTIME(y2.date_time_end)
    and FROM_UNIXTIME(y.date_time_end) BETWEEN FROM_UNIXTIME(y2.date_time) and FROM_UNIXTIME(y2.date_time_end)
)
order by person_id

A: The logic for an overlap of two time periods is:

*

*the first starts before the second ends

*the first ends after the second starts

You can translate this into SQL as:
select bp.*
from booking_person bp
where exists (select 1
              from booking_person bp2
              where bp2.person_id = bp.person_id and
                    bp2.booking_id <> bp.booking_id and
                    bp2.date_time < bp.date_time_end and
                    bp2.date_time_end > bp.date_time
             )
order by bp.person_id;

Note that this uses strict inequalities.  I am not sure if the end points count for overlapping.  This version does not consider overlaps on end points to be overlaps.


text:
Q: Relation between conservative force and potential energy Couple of days before I came across a question something like this

A particle is moving in a conservative force field from point $A$ to point $B$. Let $U_A$ and $U_B$ be the potential energies of particle at points $A$ and $B$ respectively and $W_C$ is the work done in the process in moving the particle from $A$ to $B$. (Take work done to be positive)

And we needed to find the correct relations among some alternatives. What I figured out is as follows:

*

*Potential Energy of particle is equal to $negative$ of $work$ $done$ by $conservative$ force.

*And Work done is equal to Change in Potential energy of particle.
So I found the alternatives as $W_C$=$-(U_B-U_A)$ i.e $W_C$=$(U_A-U_B)$ as correct , but correct answer is $W_C$=$(U_B-U_A)$. I think there is some trick in the last statement of question that "(Take work done to be positive)
"
But if I take work done to be positive then $U_B$<$U_A$ but this also contradicts the answer as the answer is $U_B$>$U_A$
This made a huge confusion in my mind. Please tell me if I am missing some concept. And do tell me the  correct answers too.

A: The work done that we consider here is the work done by external force (or by us).
So if the potential energy at a point is high then it means that the work done by us against the conservative field (say, gravity) will be also be high.
For example, if we lift a body, it's potential energy increases with the height because we are doing work against the conservative force (i.e, gravitational force) and this work (+ve work) gets stored in the body as its potential energy.
In other words, higher we lift the body higher will be its potential energy.
Energy conservation plays a very important role here.
Now, if the body comes down the work done by gravity will be positive. The body's potential energy will be converted into kinetic energy. The body is coming from a point of high potential energy to a point of lower potential energy, so this loss will be the gain in the kinetic energy (or the work done by gravity).
Therefore, the work done by the conservative force (gravity) will be equal to the loss in potential energy.
Since the work done by gravity is $+ve$ and there is a loss in potential energy $(\Delta U=-ve)$,
$W_{conservative}=-\Delta U$

A: The problem is that it is not clear from the question which force is doing the work.
Is $F_{\rm C}$ the external force or the force due to the conservative field?
The change in potential energy of a particle in going from position $A,\, (U_{\rm A})$ to position $B,\, (U_{\rm B})$ is the work done by an external force in moving the particle from $A$ to $B,\,(W_{\rm external, AB})$
$$W_{\rm external, AB}= U_{\rm B} - U_{\rm A}$$
[Liftng a mass $m$ in a gravitaional field strength $g$ a height $h$ you (the provider of the external force) would have to exert an upward force $mg$ and move it through a distance $h$ doing and amount of work equal to $mgh$ which is the change in potential energy.]
The work done in moving the particle from $A$ to $B$ by the force due to the conservative field is
$$W_{\rm field, AB}= -(U_{\rm B} - U_{\rm A})= - W_{\rm external, AB}$$
[The force due to the conservative field $mg$ is downwards and in the opposite direction to the ditection in which the mass is move upward a distance $h$ , so the work done by the force due to the conservative field is $-mgh$ and that by definition is minus the change in potential energy.
So again the change in potential energy is $mgh$.]

A: Potential Energy of particle is equal to negative of work done by conservative force.
And Work done is equal to negative Change in Potential energy of particle. As it is loss of energy from system. So,
$$W=-(-(U_b-U_a))$$
$$W=U_b-U_a$$


text:
Q: How to initialize a Typescript Interface that has Arrays? Let's say I have the following interfaces:

export interface MyObject {
  id: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface MyFile extends MyObject {
  data: any;
  name: string;
}

export interface MyUser extends MyObject {
  name: string;
  photos: Array < MyFile > ;
}

How do I initialize a MyUser instance in an, say, Angular app? The issue I'm having is that my object is actually huge, and I thought there would be a way to not having to declare default value for every property, especially that I do have arrays of arrays within my model!

A: Anything that conforms to an interface implements it by definition. This is because TypeScript has a structural type system.
Here are a few examples of initializing an implementation of your interface.
const user = {
  id: "1",
  createdAt: new Date(),
  updatedAt: new Date(),
  name: "Kurt",
  photos: [{
    id: "1",
    name: "avatar.png",
    createdAt: new Date(),
    updatedAt: new Date(),
    data: "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="
  }]
};

The object literal above implements the MyUser interface.
You can also specify the interface type on your variable declaration which is helpful in this case since it provides intellisense for the interface members as we are writing the object literal.
const user: MyUser = {
  id: "1",
  createdAt: new Date(),
  updatedAt: new Date(),
  name: "Kurt",
  photos: [{
    id: "1",
    name: "avatar.png",
    createdAt: new Date(),
    updatedAt: new Date(),
    data: "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="
  }]
};


text:
Q: OpenGrok indexer fails to execute I fetched OpenGrok 1.3.4 from their download page[1] and followed the installation instructions [2] to setup the software on my system (FreeBSD 12.1-RELEASE).
I have tomcat8.5 installed and the default welcome page displays without any issues. I use Universal Ctags and I think other dependencies listed in OpenGrok web site have already been installed.
pkg install openjdk8 universal-ctags tomcat85 python36 py36-pip ctags

I can view http://localhost:8080/source, which displays error messages since the indexer was not run at this stage (this is expected as indicated in the installation instructions).
When I try to run the indexer, I am getting the error below and I think it is related to my Tomcat or OpenGrok settings rather than the system I am trying to install the software on. My experience with Java servlets or server pages is very limited hence I would appreciate any  guidance.
root@opengrok-manual:~ # java -Djava.util.logging.config.file=/opengrok/etc/logging.properties -jar /opengrok/dist/lib/opengrok.jar -c /usr/local/bin/uctags -s /opengrok/src -d /opengrok/data -H -P -S -G -W /opengrok/etc/configuration.xml -U http://localhost:8080/source
17:00:39 SEVERE: Couldn't notify the webapp on http://localhost:8080/source.
javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized
    at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1056)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:859)
    at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:743)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:205)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:390)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:741)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:404)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:300)
    at org.opengrok.indexer.index.IndexerUtil.enableProjects(IndexerUtil.java:60)
    at org.opengrok.indexer.index.Indexer.main(Indexer.java:316)

Couldn't notify the webapp on http://localhost:8080/source: HTTP 401 Unauthorized.
17:00:43 WARNING: Couldn't notify the webapp that project org.opengrok.indexer.configuration.Project@1becde2d was indexed: InboundJaxrsResponse{context=ClientResponse{method=PUT, uri=http://localhost:8080/source/api/v1/projects/hellogitworld/indexed, status=401, reason=Unauthorized}}
17:00:46 WARNING: Couldn't notify the webapp that project org.opengrok.indexer.configuration.Project@ab468482 was indexed: InboundJaxrsResponse{context=ClientResponse{method=PUT, uri=http://localhost:8080/source/api/v1/projects/WhileyCompiler/indexed, status=401, reason=Unauthorized}}
17:00:46 SEVERE: Failed to send configuration to http://localhost:8080/source (is web application server running with opengrok deployed?)
java.io.IOException: InboundJaxrsResponse{context=ClientResponse{method=PUT, uri=http://localhost:8080/source/api/v1/configuration?reindex=true, status=401, reason=Unauthorized}}
    at org.opengrok.indexer.configuration.RuntimeEnvironment.writeConfiguration(RuntimeEnvironment.java:1493)
    at org.opengrok.indexer.index.Indexer.sendToConfigHost(Indexer.java:1102)
    at org.opengrok.indexer.index.Indexer.main(Indexer.java:347)

root@opengrok-manual:~ #

[1] https://github.com/oracle/opengrok/releases
[2] https://github.com/oracle/opengrok/wiki/How-to-setup-OpenGrok


text:
Q: Set CssClass on a label inside a Repeater, in a Template Col in a GridView I have a Repeater inside a Grid View control (Telerik).
<telerik:GridTemplateColumn FilterControlAltText="Filter TemplateColumn column" HeaderText="<%$ resources: PARTNER_LIST_GRID_CATEGORY %>" UniqueName="TemplateColumn">
    <HeaderStyle CssClass="myGridHeader" />
    <ItemTemplate>
        <asp:Repeater runat="server" ID="dlPartnerCat" OnItemDataBound="dlPartnerCat_OnItemDataBound">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblPartCat" CssClass="k-margin-l-10-desktop" Text='<%#Eval("BusinessPartnerCategoryName")%>' />
            </ItemTemplate>
            <%--  <AlternatingItemTemplate>
                <asp:Label runat="server" ID="lblPartCat" CssClass="k-margin-l-10-desktop" Text='<%#Eval("BusinessPartnerCategoryName")%>' />
            </AlternatingItemTemplate>--%>
        </asp:Repeater>
    </ItemTemplate>
</telerik:GridTemplateColumn>

I bind the data to it in a following way:
void BindPartners()
{
    var _partners = new BusinessPartnerRepo().GetAll(CompanyHelper.GetCompId()).Where(i => i.IsActive == true);
    var _p = new TD.Data.Entity.BusinessPartner();

    gvPartnerList.DataSource = _partners;
    gvPartnerList.Rebind();

    foreach (GridDataItem _dataItem in gvPartnerList.Items)
    {
        var _selectedItem = _dataItem.ItemIndex;
        var _list = _dataItem.MuchBetterFindControl<Repeater>("dlPartnerCat");
        var _id = (int)_dataItem.OwnerTableView.DataKeyValues[_selectedItem]["BusinessPartnerId"];

        if (_id > 0)
        {
            _p = _partners.FirstOrDefault(i => i.BusinessPartnerId == _id);

            if (_list != null)
            {
                _list.DataSource = _p.BusinessPartnerCategories.OrderBy(n => n.BusinessPartnerCategoryName);
                _list.DataBind();
            }
        }
    }
}

all of this works great. But I want to apply Css class to the label inside the repeater. This worked great with a single value (like I do with Status) and it even forks for the first value in the repeater..
protected void dlPartnerCat_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
    foreach (GridDataItem _item in gvPartnerList.Items)
    {
        var _list = _item.MuchBetterFindControl<Repeater>("dlPartnerCat");

        foreach (RepeaterItem _ite in _list.Items)
        {
            var _partCatlbl = _ite.MuchBetterFindControl<Label>("lblPartCat");

            if (_partCatlbl != null)
            {
                switch (_partCatlbl.Text)
                {
                    case "Customer":
                        _partCatlbl.CssClass = ApplicationCssHelper.CustomerClass;
                        break;
                    case "Customer - Supplier":
                        _partCatlbl.CssClass = ApplicationCssHelper.Customer_SupplierClass;
                        break;
                    case "Supplier":
                        _partCatlbl.CssClass = ApplicationCssHelper.SupplierClass;
                        break;
                    case "Agent":
                        _partCatlbl.CssClass = ApplicationCssHelper.AgentClass;
                        break;
                    default:
                        _partCatlbl.CssClass = ApplicationCssHelper.WarningClass;
                        break;
                }
            }
        }

    }
}

the value in the repeater can be multiple and I want to set different class based on the value (text) for the label in the repeater

any ideas anybody??
Ok, I have resolved this ...at least partially
I altered the OnDataBound method for the repeater:
protected void dlPartnerCat_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        foreach (GridDataItem _item in gvPartnerList.Items)
        {
            var _list = _item.MuchBetterFindControl<Repeater>("dlPartnerCat");

            foreach (RepeaterItem _ite in _list.Items)
            {
                var _partCatlbl = _ite.MuchBetterFindControl<Label>("lblPartCat");

                if (_partCatlbl != null)
                {
                    switch (_partCatlbl.Text)
                    {
                        case "Customer":
                            _partCatlbl.CssClass = ApplicationCssHelper.CustomerClass;
                            break;
                        case "Customer - Supplier":
                            _partCatlbl.CssClass = ApplicationCssHelper.Customer_SupplierClass;
                            break;
                        case "Supplier":
                            _partCatlbl.CssClass = ApplicationCssHelper.SupplierClass;
                            break;
                        case "Agent":
                            _partCatlbl.CssClass = ApplicationCssHelper.AgentClass;
                            break;
                        default:
                            _partCatlbl.CssClass = ApplicationCssHelper.WarningClass;
                            break;
                    }
                }
            }

        }
    }

and the result are following:

as you can see all elements have css class applied exept the last one... anybody know why?

A: I think you need to remove both foreach loops. There is no need to and it only add extra overhead.
protected void dlPartnerCat_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
    var _partCatlbl = e.Item.FindControl("lblPartCat") as Label

    if (_partCatlbl != null)
    {
        switch (_partCatlbl.Text)
        {
            case "Customer":
                _partCatlbl.CssClass = ApplicationCssHelper.CustomerClass;
                break;
            case "Customer - Supplier":
                _partCatlbl.CssClass = ApplicationCssHelper.Customer_SupplierClass;
                break;
            case "Supplier":
                _partCatlbl.CssClass = ApplicationCssHelper.SupplierClass;
                break;
            case "Agent":
                _partCatlbl.CssClass = ApplicationCssHelper.AgentClass;
                break;
            default:
                _partCatlbl.CssClass = ApplicationCssHelper.WarningClass;
                break;
        }
    }
}


text:
Q: High performance comparison of signed int arrays (using Intel IPP library) We're trying to compare two equally sized native arrays of signed int values using inequality operations, <, <=, > and >=, in a high performance way. As many values are compared, the true/false results would be sotred in a char array of the same size of the input, where 0x00 means false and 0xff means true.
To accomplish this, we're using the Intel IPP library. The problem is that the function we found that does this operation, named ippiCompare_*, from the images and video processing lib, supports only the types unsigned char (Ipp8u), signed/unsigned short (Ipp16s/Ipp16u) and float (Ipp32f). It does not directly support signed int (Ipp32s)
I (only) envision two possible ways of solving this:

*

*Casting the array to one of the directly supported types and executing the comparison in more steps (it would became a short array of twice the size or a char array of four times the size) and merging intermediate results.

*Using another function directly supporting signed int arrays from IPP or from another library that could do something equivalent in terms of performance.
But there may be other creative ways... So I ask you're help with that! :)
PS: The advantage of using Intel IPP is the performance gain for large arrays: it uses multi-value processor functions and many cores simultaneously (and maybe more tricks). So simple looped solutions wouldn't do it as fast AFAIK.
PS2: link for the ippiCompare_* doc

A: I thought there is an SSE instruction that would compare integers. Have you look into the intrinsics that can do that?

A: You could do the comparison with PCMPEQD followed by a PACKUSDW and PACKUSWB. This would be something along
#include <emmintrin.h>

void cmp(__m128d* a, __m128d* b, v16qi* result, unsigned count) {
    for (unsigned i=0; i < count/16; ++i) {
        __m128d result0 = _mm_cmpeq_pd(a[0], b[0]);  // each line compares 4 integers
        __m128d result1 = _mm_cmpeq_pd(a[1], b[1]);
        __m128d result2 = _mm_cmpeq_pd(a[2], b[2]);
        __m128d result3 = _mm_cmpeq_pd(a[3], b[3]);
        a += 4; b+= 4;

        v8hi wresult0 = __builtin_ia32_packssdw(result0, result1);  //pack 2*4 integer results into 8 words
        v8hi wresult1 = __builtin_ia32_packssdw(result0, result1);

        *result = __builtin_ia32_packsswb(wresult0, wresult1);  //pack 2*8 word results into 16 bytes
        result++;
    }
}

Needs aligned pointers, a count divisible by 16, some typecasts I have omitted because of lazyness/stupidity and probably a lot of debugging, of course. And I didn't find the intrinsics for packssdw/wb, so I just used the builtins from my compiler.

A: Backing out of the box for a bit: are you sure this is a performance problem?  Unless your data set fits in L1 cache, you will be cache-fill limited and the actual cycles you're spending on your comparison operations (which are hardly slow even when done in the most naive way possible) can't possibly be limiting.


text:
Q: How to Create DDL in HIVE and save it as a file in your directory Currently, I use the following code to show the DDL of tables in HIVE:
Show create table cus_data

I'm trying to write the results of that statement to a file in a given location on my command line. I tried the following but to no avail:
hive>  show create table  -f  "home/e13/sample_file"

Any ideas/suggestions?

A: Try this
hive -e "show create table cus_data" > ~/output.txt


text:
Q: Pushing object into Array of Arrays retains pointer to original object I was wondering if anyone could help provide context on this one.
With the below example:
const finalArray: any[][] = []
const accumulatedArray: any[] = []

const ids = ['1','2']
for (const id of ids) {
    accumulatedArray.push({
        id: id,
    })
}

finalArray.push(accumulatedArray)

accumulatedArray.length = 0 // remove elements from array

console.log(finalArray)

The above code will output [ [] ], which took me by surprise, I was expecting to see [ [ { id: '1' }, { id: '2' } ] ] but I can achieve this by creating a new array using a spread operator:
finalArray.push([...accumulatedArray])

question is
Why does the element in the array of arrays (finalArray) point to the accumulatedArray ?


text:
Q: CTRL+D is not working in vs code copy similar code Previous in I have used ctr+d for duplicating the code many times, but when I switched to desktop and installed vs code and all the necessary extensions for my react project. And now this CTRL+D keyboard shortcut is not working. Can any help me to solve this issue

A: I recently met this issue too. I found a solution, see this: https://linuxpip.org/duplicate-lines-vscode/.
The main step are:

*

*File > Preferences > Keyboard Shortcuts.

*type "copy line",then you will see the related shortcuts.

*remember the new shortcut(e.g. Shift + Alt + Down) or modify the shortcut to ctrl + D.

A: shift + alt + arrow-down works for me.

A: For me it was a VS Code extension causing the ctrl + ... binds not to work. It was "Vim emulation". Try isolating the issue by uninstalling the extensions until you find which one.

A: Similar issue for Windows 10, resolved using CTRL + F2.


text:
Q: How to stop displaying the data values from different data objects on Chart JS 2.x? I am using Chart JS 2.5 to visualize 2 data object in a bar chart and I can visualize the data values from both objects, but when I want to see the data values of one data object I still see all the data values of the second data object.

Data object 2 is deselected but I can still see its values.

HTML
<canvas id="myChart" width="100" height="100"></canvas>

JS script
var ctx = document.getElementById("myChart");
debugger;
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["2 Jan", "9 Jan", "16 Jan", "23 Jan", "30 Jan", "6 Feb", "13 Feb"],
    datasets: [{
        label: 'Data object 1',
        data: [6, 87, 56, 15, 88, 60, 12],
        fill: false,
        backgroundColor: "#4082c4",
    },

    {
        label: 'Data object 2',
        data: [16, 57, 23, 60, 88, 40, 42],
        fill: false,
        backgroundColor: "#9082d4",
    }]
    },
     options: {
        "hover": {
        "animationDuration": 1
    },
    "animation": {
        "duration": 1,
                    "onComplete": function () {
                        var chartInstance = this.chart,
                            ctx = chartInstance.ctx;

                        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'bottom';

                        this.data.datasets.forEach(function (dataset, i) {
                        var meta = chartInstance.controller.getDatasetMeta(i);
                        meta.data.forEach(function (bar, index) {
                        var data = dataset.data[index];
                        ctx.fillText(data, bar._model.x, bar._model.y - 5);
                    });
                });
            }
        },

    legend:{
        "display": true
       },
    tooltips: {
        "enabled": true
     },
    scales: {
        yAxes: [{
                display: false,
                gridLines: {
                display : false
            },
            ticks: {
                    display: false,
                beginAtZero:true
                }
            }],
            xAxes: [{
                    gridLines: {
                    display : false
                },
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.js"</script>

JS Fiddle
Edit online
How can I see the data values for the selected data object instead of getting in display all the data values?
This behaviour is present for the bar, line, polarArea, and radar graphs.

A: Basically, you need to check whether a particular dataset is hidden or not, before drawing the text on animation complete.
To accomplish so, you can simply replace your onComplete function with the following ...
"onComplete": function() {
   var chartInstance = this.chart,
      ctx = chartInstance.ctx;

   ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
   ctx.textAlign = 'center';
   ctx.textBaseline = 'bottom';

   this.data.datasets.forEach(function(dataset, i) {
      var isHidden = dataset._meta[0].hidden; //'hidden' property of dataset
      if (!isHidden) { //if dataset is not hidden
         var meta = chartInstance.controller.getDatasetMeta(i);
         meta.data.forEach(function(bar, index) {
            var data = dataset.data[index];
            ctx.fillText(data, bar._model.x, bar._model.y - 5);
         });
      }
   });
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ["2 Jan", "9 Jan", "16 Jan", "23 Jan", "30 Jan", "6 Feb", "13 Feb"],
      datasets: [{
            label: 'Data object 1',
            data: [6, 87, 56, 15, 88, 60, 12],
            fill: false,
            backgroundColor: "#4082c4",
         },
         {
            label: 'Data object 2',
            data: [16, 57, 23, 60, 88, 40, 42],
            fill: false,
            backgroundColor: "#9082d4",
         }
      ]
   },
   options: {
      "hover": {
         "animationDuration": 1
      },
      "animation": {
         "duration": 1,
         "onComplete": function() {
            var chartInstance = this.chart,
               ctx = chartInstance.ctx;

            ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
            ctx.textAlign = 'center';
            ctx.textBaseline = 'bottom';

            this.data.datasets.forEach(function(dataset, i) {
               var isHidden = dataset._meta[0].hidden; //'hidden' property of dataset
               if (!isHidden) { //if dataset is not hidden
                  var meta = chartInstance.controller.getDatasetMeta(i);
                  meta.data.forEach(function(bar, index) {
                     var data = dataset.data[index];
                     ctx.fillText(data, bar._model.x, bar._model.y - 5);
                  });
               }
            });
         }
      },
      legend: {
         "display": true
      },
      tooltips: {
         "enabled": true
      },
      scales: {
         yAxes: [{
            display: false,
            gridLines: {
               display: false
            },
            ticks: {
               display: false,
               beginAtZero: true
            }
         }],
         xAxes: [{
            gridLines: {
               display: false
            },
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>


text:
Q: Gitlab CICD minutes insufficient? According to gitlab.com, free CICD limit is 2000 minutes. Quoting their documentation:
"Moving forward, all free accounts will have 2000 pipeline minutes per group per month independent of the visibility of the project"
So if it is per group, can I get more CICD minutes if I create different groups and add projects there? Or is this limit is at account level? Can anyone please clarify.

A: Per https://docs.gitlab.com/ee/subscriptions/#purchasing-additional-ci-minutes, if you hit the quota, you can purchase additional minutes for a group or for your personal namespace.  It sounds like there is a group quota, and an account quota.
Also, per the release announcement you mentioned ( https://about.gitlab.com/releases/2020/03/18/ci-minutes-for-free-users/), most people use less than 1,000 minutes.

A: Update 2021: the official documentation is here (with FAQ)

CI pipeline minutes
CI pipeline minutes are the execution time for your pipelines on GitLab shared runners.
Each GitLab SaaS tier includes a monthly quota of CI pipeline minutes for private and public projects in the namespace:

Note the minutes have been reduced from 2000 to... 400.
See:

Changes to GitLab.com public project CI/CD minute quotas

From Jackie Porter:

In the upcoming milestones, we will be extending CI/CD minute usage quotas to non-open source programs on GitLab.com public projects.
In the first half of 2021, GitLab.com and other CI/CD providers faced a large uptick in the abuse of free pipeline minutes to mine for cryptocurrencies.
To discourage and reduce abuse, we announced several changes to help ensure service continued to be reliable for our customers and users. The most recent change was made on 2021-07-17 to "include public projects in pipeline minutes quota for free users."


text:
Q: Google Funding Choices: Suppress only one message e.g. suppress the Ad-Block message Does anyone know how to suppress only one message using Google FC api?
For example, I would like to suppress the ad-block message if a certain condition is met.
Something similar to this pseudo-example. However, message.proceed(false) blocks all messages, not just the ad-block message. Does anyone have any ideas?
Thanks
googlefc.controlledMessagingFunction = (message) => {
  if (isSubscriber) {
    message.proceed(false);
  } else {
    message.proceed(true);
  }
}


text:
Q: Color ggplot by the label For the following plot, I want to color the points according to the label, whereby all labels that contain "1" are red in their string, labels that contain "2" in their string are blue and labels that contain "3" in their string are green.
I'm not sure what the best approach is to achieve this.
label <- c("A1", "B1", "C1", "A2", "B2", "C2", "A3", "B3", "C3")
val <- sample(1:100, 9, replace=FALSE)
d <- data.frame(label, val)
ggplot(d, aes(x=val,y=label)) + geom_point()

A: You can achieve that creating a variable with the categories and ploting them in the colour parameter.. Like this:
d <- data.frame(label, val) %>%
  mutate(category = substr(label, 2,2))

ggplot(d, aes(x=val,y=label)) +
  geom_point(aes(colour = category), size = 15)+
  scale_color_manual(values = c("red","blue","green"))


text:
Q: Go map vs C# Dictionary I wrote a quick and dirty test to check the performance of Go vs C# in the area of concurrent lookup access and was surprised by the results.
It's a very trivial example and I'm no Go expert but the test is simply to perform 1,000,000 lock/check/add/unlock operations on a map, it's only single-threaded because I'm checking just these functions:
package main

import (
    "fmt"
    "sync"
    "time"
)

var mu sync.Mutex

func main() {
    cache := make(map[int]int, 1000000)
    start := time.Now()

    for i := 0; i < 1000000; i++ {
        mu.Lock()
        if _, ok := cache[i]; ok == false {
            cache[i] = i
        }
        mu.Unlock()
    }

    end := time.Since(start)
    fmt.Println(end)

    var sum int64
    for _, v := range cache {
        sum += int64(v)
    }

    fmt.Println(sum)
}

And the same thing in C# (via LINQPad):
void Main()
{
    var cache = new Dictionary<int, int>(1000000);
    var sw = Stopwatch.StartNew();

    for (var i = 0; i < 1000000; i++)
    {
        lock (cache)
        {
            int d;
            if (cache.TryGetValue(i, out d) == false)
            {
                cache.Add(i, i);
            }
        }
    }

    $"{sw.ElapsedMilliseconds:N0}ms".Dump();

    var sum = 0L;
    foreach (var kvp in cache)
    {
        sum += kvp.Value;
    }
    sum.Dump();
}

I sum the elements of both collections to ensure they match up (499,999,500,000) and print the time taken.  Here are the results:

*

*C#: 56ms

*Go: 327ms

I've checked that it's not possible to initialise the size of a map, just the capacity, so I'm wondering if there's anything I could do to improve the performance of the Go map?
It takes Go 32ms to perform 1,000,000 lock/unlock operations without the map access.

A:
[S]o I'm wondering if there's anything I could do to improve the performance of the Go map?

No there is not. Go has basically no performance knobs.
(Note that Go's map type is a very general and robust hash map which uses strong cryptographic hashing (if possible) to prevent attacks and forces random key/iteration order. It is "totally general purpose" and not just "a fast dictionary".)
Just to be totally correct: There is the environmental variable GOGC to "tune" GC.

A: There may be one thing that is overlooked and converts the whole exercise into apples and oranges: synchronization. On Go side you use Mutex which goes down to the kernel on every access. On C# side you use lock(){} that uses a combination of SpinLock and only falls back to kernel calls when needed. Since your tests are performed in a single thread anyways, C# never even goes to kernel.
Use of Mutex is discouraged in Go and channels should be used for synchronization instead.
Couple of suggestions:
1. Remove synchronization if you want to benchmark map/dictionary by themselves.
2. Write your tests using correct constructs and paradigms if you like to benchmark concurrent performance.
Cheers!

A: I compiled your C# example using Mono, and ran it on OS X, just to neutralize any "magic" Microsoft might have added to its Windows implementation of Dictionary.
It appears that C# is indeed faster than Go for this particular test, unless there is some Go performance trick we are overlooking:
dict.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;

public class DictionaryTest
{
    public static void Main()
    {
        var cache = new Dictionary<int, int>(1000000);
        var sw = Stopwatch.StartNew();

        for (var i = 0; i < 1000000; i++)
        {
            lock (cache)
            {
                int d;
                if (cache.TryGetValue(i, out d) == false)
                {
                    cache.Add(i, i);
                }
            }
        }

        sw.Stop();

        Console.WriteLine(string.Format("{0}ms", sw.ElapsedMilliseconds));

        var sum = 0L;
        foreach (var kvp in cache)
        {
            sum += kvp.Value;
        }

        Console.WriteLine("Sum: " + sum);
    }
}

If you have the Mono SDK installed, you can compile the above with mcs dict.cs and execute with mono dict.exe.
I ran it several times, and it takes an average of 47ms compared to my average 149ms for the Go version.

A: I found if I shink  1000000 to 100000,  golang speed would change from 151.0087ms to 10.0005ms (15.1 multiply), while csharp version change  from 65ms to 9ms (7.22 multiply) , so it means golang's hashmap   has difficulty to handle large map ?
I wrote a simple go benchmark program like this
func BenchmarkIntMapGet100(b *testing.B) {
    count := 100
    setupIntMap(b, count)

    b.ResetTimer()
    for i:=0; i<b.N; i++{
        _, _ = intMap[i%count]
    }
}

and I got the result
BenchmarkIntMapGet10-4          100000000           15.6 ns/op
BenchmarkIntMapGet100-4         100000000           17.1 ns/op
BenchmarkIntMapGet1000-4        50000000            25.7 ns/op
BenchmarkIntMapGet10000-4       50000000            32.3 ns/op
BenchmarkIntMapGet100000-4      30000000            39.2 ns/op
BenchmarkIntMapGet1000000-4     20000000            67.2 ns/op
BenchmarkIntMapGet10000000-4    20000000            82.3 ns/op


text:
Q: DNN Profile update on login - existing values not displayed We have recently changed our website configuration to make certain fields mandatory. We also set "Require valid profile for login" to True, so that existing users can fill out the missing information the next time they log in.
The problem is that when users log in, the profile update form displayed to them is totally blank. DNN does not pre-fill the form with information that the user already provided in the past. Even fields such as First Name and Last Name are empty.
Is this the expected behaviour?

A: So I finally figured out the problem.
We had put some custom code in Page_Load event to inspect the initial profile values. Once we removed it, everything works fine.


text:
Q: Notepad++ How to delete carriage return in lines without full stops only I have documents that contain carriage returns in the middle of sentences, like this:
Were there any connections? Or
was all of it

I have found a regex for finding these lines (Find: \w$) and I can insert a full stop if I want (Replace: $0.) but what do I do to insert a space and remove the carriage return/delete it instead so it becomes this:
Were there any connections? Or was all of it

I have a lot of these to replace so it would be helpful to get a replace command that takes care of all of them.
Is there a way to do this?

A: *

*Ctrl+H

*Find what: (?<=\w)\R(?=\w)

*Replace with:    A space

*CHECK Wrap around

*CHECK Regular expression

*Replace all
Explanation:
(?<=\w)     # positive lookbehind, make sure we have a word character before
\R          # any kind of linebreak
(?=\w)      # positive lookbahead, make sure we have a word character after

Screenshot (before):

Screenshot (after):


text:
Q: Shiny - uiOutput and UI layout problems
Right now, I'm encapsulating the UI on the right side as a variable, and I want the UI on the right to change based on the "Module Selected." Here's what I'm doing right now to do this:
ui <- navbarPage('test',
  tabPanel('Analysis',
    fluidRow(
      ui_core,
      uiOutput('ui_module')
    )
  )
)

output$ui_module <- renderUI({
# observeEvent(input$core_module_selection, {
  current_module <- NULL
  if(!is.null(input$core_module_selection) && input$core_module_selection != 'Core') {
    current_module <- rval$module_ui[[match(input$core_module_selection, rval$module_names)]]
    rval$ui_module <<- current_module
  }

  return(rval$ui_module)
})

I'm using reactive values (rval) for the ui_module variable, which holds the UI I want to render:
ui_filetrans <-
tabsetPanel(
  tabPanel('File Transfer',
    p("filetrans")
  )
)
register_module("File Transfer", ui_filetrans)

which should end up like this:
ui <- navbarPage('Granatum',
  tabPanel('Analysis',
    fluidRow(
      ui_core,
      tabsetPanel(
        tabPanel('File Transfer',
          p("filetrans")
        )
      )
    )
  )
)

But, instead, I get this weird text (I'd guess it's a Bootstrap class or something) that supposedly comes from the tag... and not the full object.
What am I doing wrong? Is the object's type being changed once I assign it to a vector?

A: It turns out that by passing Shiny UI elements to a vector, you will implicitly remove some of the information of the object.
The solution is to use lists, and use double square brackets to index:
rval$module_ui <- list(ui_core)

rval$module_ui <- c(rval$module_ui, list(module))

c(), the concatenate function, works very much the same for lists, but ensure that you turn "atoms" or atomic components into a list before concatenation.


text:
Q: How to convert all types (audio*) to mp3 ? Using FFMPEG It is possible to convert all audio to mp3?
System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.EnableRaisingEvents = false;
                    proc.StartInfo.FileName = @"""C:\ffmpeg\bin\ffmpeg.exe""";
                    proc.StartInfo.Arguments = "-i C:\\Matheus\\Matheus_Project\\Matheus_Project\\App_Data\\" + User.Identity.Name + "\\" + fileNameAndType + " -acodec libmp3lame -ab 128k C:\\Matheus\\Matheus_Project\\Matheus_Project\\App_Data\\" + User.Identity.Name + "\\" + fileName + ".mp3";  /* use /y to overwrite if there it exists already or will fail */
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.CreateNoWindow = false;
                    proc.StartInfo.RedirectStandardOutput = true;
                    proc.StartInfo.RedirectStandardError = true;
                    proc.Start();

                    var output = proc.StandardOutput.ReadToEnd();
                    string output_error = proc.StandardError.ReadToEnd();

                    proc.WaitForExit();
                    proc.Close();

Example:

*

*audio/x-m4a to  mp3

*audio/mp4 to mp3

*audio/basic to mp3

*audio/L24 to mp3

*audio/mid to mp3

*audio/x-aiff to mp3

*audio/x-mpegurl to mp3

*audio/vnd.rn-realaudio to mp3

*audio/ogg to mp3

*audio/vorbis to mp3

*audio/vnd.wav to mp3
Any idea ?

A: public void ConvertWavToMp3(string filename)
        {
            try
            {
                string Flacfilename = AppDomain.CurrentDomain.BaseDirectory + "FlacRecording";
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.FileName = AppDomain.CurrentDomain.BaseDirectory + @"lame.exe";
            psi.Arguments = "-b" + "128" + " --resample " + "22.05" + " -m j " +
                           "\"" + filename + "\"" + " " +
                            "\"" + Flacfilename + "\\" + Path.GetFileNameWithoutExtension(filename) + ".mp3" + "\"";

            Process p = Process.Start(psi);
            p.WaitForExit();
            p.Close();
            p.Dispose();

        }
        catch (Exception ae)
        {
        }

    }

download lame.exe and put it in your application and call abover function with passing fullpath with wav file name.


text:
Q: Iphone  image on form altered
Ok so here's my problem, i have 3 buttons that work on both pc and mobile phones, but 1 major difference, on mobile devices the button shrinks by 50% and magically gets round corners. (ignore the fact that the top image has a check and the bottom has a plus sign, they do the same exact thing)
<button type="button" onClick="parent.location='../index.php'" title="Back to Main Menu">

</button>
<button type="reset" title="Reset">

</button>
<button type="submit" title="Done">

</button>
<input type="hidden" value="submit" name="submit" />

is there a quick fix to this problem? Once again both sets of buttons work properly, just look different.
As requested: i've also tried this code.
<button type="reset" style="width:49px; height:33px;">

 </button>

it's the same thing. i've also tried to set to style="width:50px; height:50px, and the button becomes a full circle.

A: Well, i really don't see anyone going to have an answer to my problem, so i just started messing with the height and width on the buttons a little more and got kinda of lucky to land on a middle ground on both browsers.

<button type="reset" title='Reset' style='height:33px; width:50px'>

</button>

This seemed to be the sweet spot for my specific situation. because the pc broswer side was not effected and the iphone/safari side is acceptable to see the icons.


text:
Q: Safe way to delete rows I am writing code to delete a row based on ID from a SQL Server database.  I want to make sure my code is safe from accidentally deleting everything or deleting something other than what it should.  My code at the moment is as follows...
$st = $conn->prepare("if (select count(*) from sometable where id = :id)  = 1
    delete from sometable where id = :id");

$st->bindParam(':id',$id);

$st->execute();

Is this a safe way to delete a single row without accidentally deleting everything?   Is there a better, known best-practices way to do it?
Edit: I am getting an error COUNT field incorrect or syntax error when testing this code.
I have changed my code accordingly to resolve this (I was hoping I could refer to the same field more than once and bind it once but apparently not)
$st = $conn->prepare("if (select count(*) from sometable where id = ?)  = 1
delete from sometable where id = ?");

$st->execute(array($id,$id));

(Might as well use my question to troubleshoot since stackoverflow won't let me delete it)

A:
Is this a safe way to delete a single row without accidentally deleting everything?

Yes, as long as your ID's are unique for each row.

Is there a better, known best-practices way to do it?

No.


text:
Q: How do you define a command to select nested groups? Assuming a pair structure (2-tuple) is defined using groups
{{<tokens1>}{<tokens2>}}

is it possible to define a command \first#1{...} (and \last#1{...}) taking the surrounding group as its single argument which expands to <tokens1> but consumes {<tokens2>} (and vice versa)? If so, how?

By consume I mean expanding to \relax or the empty token list (or whatever is the most appropriate pattern for expand to nothing).
This is for a LISP style recursive list implementation.
TeX-core solutions preferred.

A: %!TEX TS-program = pdftex

\catcode`@=11
\long\def\@firstoftwo#1#2{#1}
\long\def\@secondoftwo#1#2{#2}
\def\first#1{\@firstoftwo#1}
\def\last#1{\@secondoftwo#1}
\catcode`@=12

\first{{+tokens1+}{--tokens2--}}

\last{{+tokens1+}{--tokens2--}}

\bye

Of course, if you don't have (or want) anything to do with LaTeX. There's no need for \@firstoftwo while \firstoftwo would be useful anyways.


text:
Q: Where do you store uploaded user images I am not yet using a service such as Amazon S3, so where in the file structure should I store uploaded user images? I want to avoid the public directory as the images are private.

A: Are you using a plugin to handle your uploads? Many of them allow you to specify a path to store files, if you want to avoid the public folder a reasonable suggestion would be "#{RAILS_ROOT}/uploads/images/"
It's very much a matter of personal taste though.
For example in a carrierwave uploader this will place items in an uploads folder below RAILS_ROOT which is not publicly accessible.
def store_dir
  "#{RAILS_ROOT}/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end

https://github.com/carrierwaveuploader/carrierwave#changing-the-storage-directory


text:
Q: Recommend way to access data file in the app engine python services Have a requirement of accessing large pandas data frame files to run some analytics in the worker of the app engine via google cloud tasks
Can somebody please suggest on what component in google cloud can be used for storing and accessing files quickly ?
Any reference to example would be of great help.

A: I think Google Cloud Storage is the best place to store and accessing the files quickly :
https://cloud.google.com/storage/docs/discover-object-storage-console
GCS can store large files and a big amount of files.
You can also use :

*

*gsutil to move or copy files between buckets.

*Storage transfer service
https://cloud.google.com/storage-transfer/docs/overview
Your application from app engine could use Cloud Storage.


text:
Q: Render Cell into specific element? Is it possible to render a Cell (from CellJS) into a specific element? For example, if you wanted to render a Cell along with some static HTML not managed by cell. Or if I wanted to have 2 independent Cell apps on a single page.
<!DOCTYPE html>

A CellJS App

I don't see anything in the docs that indicates how to do this. Or if its even possible.

A: The official API documentation shows how you can insert components into an existing DOM tree.

However sometimes you may not want to build an entire web page with Cell. You may just want to generate a small component with Cell and inject it into an existing DOM tree.

This can be achieved in two steps:

*

*Set an id on the element you would like to inject into.

*Include the same id in your Cell object definition.

Below is an example of two cell apps on one page:

var el = {
  $cell: true,
  $type: "div",
  id: "cell_container1",
  $components: [{
    $type: "h1",
    $text: "Lorem"
  }, {
    $type: "a",
    $text: "Ipsum",
    href: "https://www.google.com"
  }]
};

var el2 = {
  $cell: true,
  $type: "div",
  id: "cell_container2",
  $components: [{
    $type: "h1",
    $text: "Dolor"
  }, {
    $type: "a",
    $text: "Sit",
    href: "https://www.google.com"
  }]
};

A CellJS App


text:
Q: Limit a table to hold a max of 100 records and delete the oldest Its my intention to implement a History function in my database where users can see what records they've previously worked on. To achieve this initially, I created an extra field in the table they we're looking at and added their name from the login screen and timestamp to the record. This works, but the problem is if another user loads up the record, it overrides the last person since its just one field and its inconsistent.
So instead I created a new table and added their names and timestamps in there as a new line. The issue here is that eventually there's going to be 1000's of records in a table eating away at my hard drive space over time and eventually since the max for a table is 2GB, its just going to break one day.
After researching, Queries have a max limit, but you've still got to link that to a table that holds the data. I would like a table that contains, lets say 100 records, and at the 101st record, the oldest line is overridden and so on.
There's no code to share since my problem isn't with VBA, but rather finding a work around for this, I would of assumed this would be implemented into Access by default. I just have a table called 'History' and in VBA, an 'open recordset' function and '.addnew' 'User' and 'Date'.

A: You could use an After Insert data macro to remove the oldest row when a new one is added:


text:
Q: update problems 18.10 Err:1 http://us.archive.ubuntu.com/ubuntu cosmic InRelease
  Could not connect to 127.0.0.1:8118 (127.0.0.1). - connect (111: Connection refused)
Err:2 http://us.archive.ubuntu.com/ubuntu cosmic-proposed InRelease
  Unable to connect to 127.0.0.1:8118:
Err:3 http://us.archive.ubuntu.com/ubuntu cosmic-updates InRelease
  Unable to connect to 127.0.0.1:8118:
Err:4 http://us.archive.ubuntu.com/ubuntu cosmic-backports InRelease
  Unable to connect to 127.0.0.1:8118:
Err:5 http://archive.canonical.com/ubuntu trusty InRelease
  Could not connect to 127.0.0.1:8118 (127.0.0.1). - connect (111: Connection refused)
Err:6 http://archive.canonical.com/ubuntu bionic InRelease
  Unable to connect to 127.0.0.1:8118:

A:
Unable to connect to 127.0.0.1:8118:

This suggests you have some type of proxy configured.  That proxy is offline and not able to be reached, and since apt is configured to go through that proxy, which is offline, you can't download packages.
You would need to dig into your /etc/apt/apt.conf.d/* settings files to see where the proxy is being defined and try deactivating the proxy requirement; if it still doesn't work then you need to go figure out whether you must have that proxy running in order to get access to the Internet at large for updates, Internet traffic, etc.


text:
Q: Disable xscreensaver when program is running? I find it very annoying that xscreensaver sometimes helpfully starts while I'm playing Urban Terror, and was wondering if there is a better way to solve this than making some script to run Urban Terror which kills xscreensaver first.
My system is Arch Linux, with xscreensaver 5.22.

A: The latest versions of Cinnamon come with their wn screensaver package so these solutions might not work, but they do on my Cinnamon 1.8.8.
lightsOn
LighstOn is a simple BASH script that will inhibit the screensaver when it detects any of a list of user defined programs (mplayer, and therefore smplayer, are on the list by default) running in full screen mode.
Download lightsOn from here. I just tried it and it works perfectly. You might want to make it start automatically by adding it to Cinnamon's start up application list.
caffeine
Caffeine is a system tray applet for Gnome3 (it may or may not work in Cinnamon, I have not tried it). According to this site, you can give it a list of programs and it will inhibit the screensaver if they are running (full screen or not). According to the same site, it can work with both xscreensaver and gnome-screensaver so you may want to check it out.

A: Use caffeine
yaourt -S caffeine-bzr

if yaourt installed
otherwise you will have to build it from here
AUR For caffeine-bzr
after it is running.  Activate it.
It differs slightly based on DM how to set it up.  You just need to add the executable to caffeine.
I am not familiar with Urban Terror, but you might have to include the wine part of the executable when configuring caffeine


text:
Q: Changing Navigation Controller's view on button press I've setup a Navigation Controller which is connected to two View Controllers (B & C). The Navigation Controller is connected to a Container View which is inside a View Controller (A). In this View Controller (A) I also have some buttons which just logs some simple messages to the console.
View Controller A
    -> Container -> Navigation Controller
                                  -> View Controller B
                                  -> View Controller C

Now how can I change the active View controller (B OR C) inside the Navigation Controller when a button is pressed? I'm fairly new to Xcode and my biggest problem here I think, is that I don't know how to access the different views programmatically.

A: use navigation controllers array to access view controllers , i think you should check here

A: #import "ViewControllerB.h"

...

ViewControllerB* vcB = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
[self.navigationController pushViewController:vcB animated:YES];

A: First you need to import viewController which you want to navigate.
ViewController.h Import ViewControllerC
#import "ViewControllerC.h"

ViewControllerB.m file..
 ViewControllerC * gmavc=[[ViewControllerC  alloc]initWithNibName:@"ViewControllerC " bundle:nil];

 [self.navigationController pushViewController:gmavc animated:YES];

Try this code...

A: Solved it using this tutorial
http://sandmoose.com/post/35714028270/storyboards-with-custom-container-view-controllers


text:
Q: Rate exceeded in throttling is thrown on DescribeJobFlows Several days ago all went well, but now, not just one, but three of our servers are throwing these exceptions:

{
  "Error" => {
    "Message" => "Rate exceeded",
    "Code" => "Throttling",
    "Type" => "Sender"
  }
}

This happens when retrieving data from Amazon, while calling DescribeJobFlows on Amazon::Coral::ElasticMapReduceClient, and shows as NFO Exception Retriable invalid response.

A: Every AWS API has dynamic throttling protection.
It's kinda sad but best way it to retry/sleep between API calls :(
There is a configuration for the boto3 client to change max_retries before throwing the exception. There is also the general reference on how to use retries.
Good luck!

A: You should add some retry logic to your code. See this other Stackoverflow question for some ways of implementing that in Python:
Need advice to add exponenital back-off logic in AWS API in python


text:
Q: PHP neo4j OGM - Recursion detected i'm using the entitymanager in my project. I can successfuly read/add my entites and relations between them to the db but have one problem.
I have two nodes Employee and Document and a relationship between them as Employee HAS Document.
php class for Emloyee:
<?php
namespace App\Models;

use GraphAware\Neo4j\OGM\Annotations as OGM;
use \GraphAware\Neo4j\OGM\Common\Collection;

/**
 *
 * @OGM\Node(label="Employee")
 */
class Employee implements \JsonSerializable {

    public function __construct() {
        $this->documents = new Collection();
        $this->addresses = new Collection();
    }

    /**
     * Id
     * @var int
     * @OGM\GraphId()
     */
    protected $id;

    /**
     * name
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $name;

    /**
     * lastname
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $lastname;

    /**
     * personalidnumber
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $personalidnumber;

    /**
     * @var Document[]|Collection
     *
     * @OGM\Relationship(type="HAS", direction="OUTGOING", collection=true, mappedBy="employees", targetEntity="Document")
     */
    protected $documents;

    /**
     * @var Address[]|Collection
     *
     * @OGM\Relationship(type="HAS", direction="OUTGOING", collection=true, mappedBy="employees", targetEntity="Address")
     */
    protected $addresses;

    public function getaddresses() {
        return $this->addresses;
    }

    public function getdocuments(){
        return $this->documents;
    }

    public function getname(){
        return $this->name;
    }

    public function setname($name){
        $this->name = $name;
    }

    function getlastname() {
        return $this->lastname;
    }
    public function setlastname($lastname){
        $this->lastname = $lastname;
    }

    function getpersonalidnumber() {
        return $this->lastname;
    }
    public function setpersonalidnumber($personalidnumber){
        $this->personalidnumber = $personalidnumber;
    }

    public function jsonSerialize() {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'lastName' => $this->lastname,
            'personalidnumber' => $this->personalidnumber,
            'addresses' =>$this->addresses->toArray(),
            'documents' =>$this->documents->toArray()
        ];
    }
}

php class for Document:
    <?php

namespace App\Models;

use GraphAware\Neo4j\OGM\Annotations as OGM;
use GraphAware\Neo4j\OGM\Common\Collection;

/**
 *
 * @OGM\Node(label="Document")
 */
class Document implements \JsonSerializable{

    public function __construct() {
        $this->employees = new Collection();

        $timezone = new \DateTimeZone('Europe/Ljubljana');
        $t = microtime(true);
        $micro = sprintf("%06d",($t - floor($t)) * 1000000);
        $dt = new \DateTime( date('Y-m-d H:i:s.'.$micro, $t));
        $dt->setTimezone($timezone);
        $this->crdate = $dt->format('YmdHis.u');
        $this->validfrom = $this->crdate;
    }

    /**
     * @OGM\GraphId()
     *
     * @var int
     */
    protected $id;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $name;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $uniquename;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $path;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $ext;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $documentid;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $validfrom;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $validto;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $crdate;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $language;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $type;

    /**
     * @var string
     *
     * @OGM\Property(type="string")
     */
    protected $description;

    /**
     * @var DocEmployees[]|Collection
     *
     * @OGM\Relationship(type="HAS", direction="INCOMING", collection=true, mappedBy="documents", targetEntity="Employee")
     */
    protected $employees;

    public function getemployees() {
        return $this->employees;
    }

    public function getid() {
        return $this->id;
    }

    public function getname() {
        return $this->name;
    }
    public function setname($name) {
        $this->name = $name;
    }

    public function getuniquename() {
        return $this->uniquename;
    }
    public function setuniquename($uniquename) {
        $this->uniquename = $uniquename;
    }

    public function getpath() {
        return $this->path;
    }
    public function setpath($path) {
        $this->path = $path;
    }

    public function getext() {
        return $this->ext;
    }
    public function setext($ext) {
        $this->ext = $ext;
    }

    public function getdocumentid() {
        return $this->documentid;
    }
    public function setdocumentid($documentid) {
        $this->documentid = $documentid;
    }

    public function getvalidfrom() {
        return $this->validfrom;
    }

    public function setvalidfrom($validfrom) {
        $this->validfrom = $validfrom;
    }

    public function getvalidto() {
        return $this->validto;
    }

    public function setvalidto($validto) {
        $this->validto = $validto;
    }

    public function getlanguage() {
        return $this->language;
    }
    public function setlanguage($language) {
        $this->language = $language;
    }

    public function getcrdate() {
        return $this->crdate;
    }
    public function setcrdate($crdate) {
        $this->crdate = $crdate;
    }

    public function gettype() {
        return $this->type;
    }
    public function settype($type) {
        $this->type = $type;
    }

    public function getdescription() {
        return $this->description;
    }
    public function setdescription($description) {
        $this->description = $description;
    }

    public function getfullname(){
        return $this->path.$this->uniquename;
    }

    public function jsonSerialize() {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'uniquename' => $this->uniquename,
            'path' => $this->path,
            'ext' => $this->ext,
            'validfrom' => $this->validfrom,
            'validto' => $this->validto,
            'language' => $this->language,
            'crdate' => $this->crdate,
            'type' => $this->type,
            'description' => $this->description,
            'employees' => $this->employees->toArray()
        ];
    }
}

then i have two API endpoints i use the Slim framework for the REST API
basically i have two methods that return the data.
for Employees:
    public function getAllEmployees(){
    $this->logger->info(__CLASS__.':'.__FUNCTION__);

    $employeesRepository = $this->dbentity->getRepository(Employee::class);
    $employees = $employeesRepository->findAll();

    return $employees;
}

for Documents:
    public function getAllDocuments(){
    $this->logger->info(__CLASS__.':'.__METHOD__);

    $documentRepository = $this->dbentity->getRepository(Document::class);
    $documents = $documentRepository->findAll();

    return $documents;
}

So my problem is when i uncomment then line
            'employees' => $this->employees->toArray()

in the Document class
i get a Runtime error Recursion detected
without that line  everything works fine.
Can somebody help me what am i missing?

A: The error happens because in jsonSerialize() of Documents you include all Employees. In jsonSerialize() of Employee you include all Documents so you create an endless nesting of documents which does never end.
When including Documents inside of an Employee record in the API response you should skip serializing all Documents.


text:
Q: Из hex в asm на Linux Есть кусок кода в машинных кодах. Необходимо сконвертировать его в ассемблерный код.
Подскажите, пожалуйста, как это сделать.

Дополнительная информация:

*

*Целевая платформа linux

*Нужно преобразовать именно кусок кода, а не весь бинарник (поэтому gdb и objdump не подходят)
Заранее спасибо за ответы.
A: Отдельные куски кода довольно неплохо дизассемблирует утилита rasm из radare (the reverse engineering framework)
A: Считаю что IDA Pro
может неплохо справиться с поставленной задачей.
A: Лет шесть назад мне требовалось открыть сильно битый ELF, тогда помогла система lida (Linux Interactive DisAssembler). Судя по сайту она давно не поддерживается, к сожалению, не уверен, что работоспособна. Гораздо дольше поддерживалась библиотека libdisasm, на которой основана lida, может, удастся использовать ее напрямую.
A: Я могу посоветовать (Хотя не проверял прокатит ли), открыть нех код под HIEW32, дальше начать изучение самого кхм... кода, кода. Клавиша F4 и выбрать Decode.


text:
Q: Possible to change netStream end time? is it possible to change the netStream end time?
For example I know you can change the start time by using
netStream.play(movieName,20)

The number 20 being the number of seconds to skip and start the video from, I was just wondering if there was something I could call to automatically make the video call or be given the status

NetStream.Play.Stop

when it reaches a time point in seconds.

A: Unfortunately, you'll have to track that yourself and run ns.pause() yourself.  You may want to use onMetaData, which will give you the meta data you may find key (such as for looping a video when it reaches the end duration).
Here's a sample solution:
var stopTimer:Timer = new Timer(20*1000, 1);
stopTimer.addEventListener(TimerEvent.TIMER, stopVideo);

function startVideo(path:String):void {
    ns.play(path);
    ns.seek(0);
    stopTimer.start()
}

function stopTimer(e:Event):void {
    ns.stop()
}


text:
Q: Router Link in VUE JS is not showing active I hope you are having an amazing week. The thing is I'm learning VUE for a couple of weeks now but currently I'm facing an issue with VUE Router. Following is the issue that I'm facing:
1- I have registered 5 routes and their corresponding views are already created. I have created a separate file call "Navbar.vue" where I'm using this route-link as the primary navigation menu. Following are the route links that i have created:

*

*Home

*About

*Movies

*Actors

*Profile

The output is attached below.

*Now the issue is every link is working fine except "Movie", I'm unable to hover over it. But whenever I remove that the adjutant link shows the same problem. Following is the code of the router link:

                      <router-link  class="link" to="/">Home</router-link>
                      <router-link class="link"  to="/about">About</router-link>
                      <router-link class="link"  to="/movies">Movies</router-link>
                      <router-link class="link"  to="/actors">Actors</router-link>
                      <router-link class="link"  to="/profile">Profile</router-link>

ROUTES REGISTRATION
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/about',
    name: 'About',
    component:About,
  },
  {
    path: '/actors',
    name: 'Actors',
    component: Actors,
  },
  {
    path: '/movies',
    name: 'Movies',
    component: Movies,
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

HTML CONSOLE OUTPUT

Can anyone guide me on what exactly I'm missing? PS The corresponding views of each route link are created and each route is registered successfully.
Thanks

A: Step 1: HTML template
 <template>

      <router-link class="link" to="/">Home</router-link>
      <router-link class="link" to="/about">About</router-link>
      <router-link class="link" to="/movies">Movies</router-link>
      <router-link class="link" to="/actors">Actors</router-link>
      <router-link class="link" to="/profile">Profile</router-link>

    <router-view></router-view>

</template>

Step 2: Create router
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../components/Home.vue";
import About from "../components/About.vue";
import Actors from "../components/Actors.vue";
import Movies from "../components/Movies.vue";
import Profile from "../components/Profile.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home
  },
  {
    path: "/about",
    name: "About",
    component: About
  },
  {
    path: "/actors",
    name: "Actors",
    component: Actors
  },
  {
    path: "/movies",
    name: "Movies",
    component: Movies
  },
  {
    path: "/profile",
    name: "Profile",
    component: Profile
  }
];

const router = new VueRouter({
  mode: "history",
  linkExactActiveClass: "active",
  routes
});

export default router;

Step 3: Add style for active class

DEMO


text:
Q: Webpack doesn't render sass correctly when not exporting file I am trying to configure Webpack 4 to use Sass for a MERN project. When I use mini-css-extract-plugin and export a CSS file and then link it in the index.html file it works. However, when I try to bundle the css with the bundle.js file, it will not render the css and the odd thing is, it does not render just some parts of it. I tried following the official bootstrap webpack installation, but it did not work as intended.
Here are the files:
webpack.config.js:
const path = require('path');
// const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  entry: './client/src/index.js',
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.s?css$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              localIdentName: '[name]__[local]__[hash:base64:5]',
              modules: true,
              importLoaders: 1,
              sourceMap: true,
            },
          },
          {
            loader: 'sass-loader'
          },
        ],
      },
        {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: "babel-loader",
            options: {
                presets: ['@babel/preset-env']
            }
        },
        {
          test: /\.jsx$/,
          exclude: /node_modules/,
          loader: "babel-loader",
          options: {
              presets: ['@babel/preset-env']
          }
        }
      ]
  },
  output: {
    path: path.resolve(__dirname, 'client/public'),
    filename: 'bundle.js'
  }
}

./client/src/index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';

import 'bootstrap';
import '../sass/style.scss'
import App from './components/App';

ReactDOM.hydrate(
    <BrowserRouter>
      <App />
    </BrowserRouter>,
    document.getElementById('root')
)

A: I bealive that webpack 4 support MiniCssExtractPlugin , the other loaders that are you trying to use dont work correctly .
Check de Docs and try it :
https://webpack.js.org/plugins/mini-css-extract-plugin/


text:
Q: Number of right angled triangles formed by vertices of a 14-gon Here's a question that I found on the website of International Kangaroo Maths Contest. The question goes like this:

What is the total number of right angled triangles that can be formed by joining the vertices of a regular 14-gon?

Correct Answer: The correct answer as given on the website is $84$.
What I did:
First of all, I calculated the total number off triangles (right angled or not) that can be formed by using the vertices of a regular 14-gon that is $^{14}C_3=364$.
However, I can't figure out how to count which ones of these $364$ triangles are right angled. Please help me in this regard.
Thanks for the attention!

A: Remember that if two points of triangle are makeing diameter of circle circumscribed to this triangle than this one is right.
We have $7$ diameters and for each one we have 6 point on each side. So we have $$7\cdot 12=84$$ right triangles.