text:
Q: C# - how do I implement a data structure that contains ListViewItems? So I'm doing a college project and my theme is web shop. What I have so far in C# is quite simple, I have a few ListViewItems (Articles) defined in WPF. Also when I change ComboBox index or click a button "New", other articles get inserted into my listview.
After that I needed to create an on click event that opens a new window with the listviewitem (article) details. I've hardcoded(if that's what it's called) this because I didn't know how to do it better.
The problem arises when I select a ComboBoxItem, which clears the listview and adds different items (articles) . When I click on the new articles, a window from the previous article opens when I click it.
I probably need to implement some kind of data structure that keeps ListViewItems, right? How would I approach doing this?
What I have so far:
namespace TRGOVINA
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void izhod(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void btnNovosti(object sender, RoutedEventArgs e)
        {
            string[] artikli = { "Intel procesor Core i7 6800K", "Intel procesor Core i5 7400", "AMD procesor Ryzen 7 1800X" };

            Artikel artikel1 = new Artikel();
            artikel1.Naziv = artikli[0];
            lvDataBinding.Items.Add(artikel1);

            Artikel artikel2 = new Artikel();
            artikel2.Naziv = artikli[1];
            lvDataBinding.Items.Add(artikel2);

            Artikel artikel3 = new Artikel();
            artikel3.Naziv = artikli[2];
            lvDataBinding.Items.Add(artikel3);
        }

        private void cbKlik_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string[] izbira1 = { "Kingston 2, 5'' SSD disk 480 GB, SATA3", "DELL monitor LED UltraSharp U2412M", "Lenovo IdeaPad 110" };
            string[] izbira2 = { "PCX namizni računalnik Exam i5-7400/8GB/SSD120+1TB/Win10H", "Lenovo prenosnik V310", "Intel procesor Core i7-5820K" };
            string[] izbira3 = { "HP prenosnik Pavilion 17-ab004nm", "Intel procesor Core i7 6900K", "Gigabyte grafična kartica GTX 1080 OC" };
            string[] izbira4 = { "Asus prenosnik FX502VM-DM311T", "HP prenosnik Omen 17-w103nm", "DELL prenosnik Alienware 17" };

            ComboBox cmb = (ComboBox)sender;
            int izbranIndex = cmb.SelectedIndex;

            //lvDataBinding.Items.Clear();
            switch (izbranIndex)
            {
                case 0:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira1;
                    break;
                case 1:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira2;
                    break;
                case 2:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira3;
                    break;
                case 3:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira4;
                    break;
            }
          }

        private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //INSTEAD OF MESSAGEBOX A WINDOW HAS TO OPEN WITH LISTVIEW ITEM DETAILS - messagebox is just a placeholder
            int indeks = lvDataBinding.SelectedIndex;
            if (indeks == 0)
                MessageBox.Show(ime1.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 1)
                MessageBox.Show(ime2.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 2)
                MessageBox.Show(ime3.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 3)
                MessageBox.Show(ime4.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 4)
                MessageBox.Show(ime5.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 5)
                MessageBox.Show(ime6.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void btnKosarica(object sender, RoutedEventArgs e)
        {
            Kosarica kosarica = new Kosarica();
            kosarica.Show();
        }
    }

    public class Artikel
    {
        public string Naziv { get; set; }

        public override string ToString()
        {
            return Naziv;
        }
    }
}

A: I'm goint to use MVVM in this answer since it's almost required for a WPF experience that doesn't include questioning your life choices. MVVM stands for Model, View, ViewModel. Something like this should get you started...
First is the Model. This is your data structure.
class Item
{
    public string Name { get; set; }
    public Item(string name)
    {
        Name = name;
    }
    public override string ToString()
    {
        return Name;
    }
}

Then, your window in XAML. This is considered your view.
<Window x:Class="Wpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Wpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <StackPanel>
        <ListView ItemsSource="{Binding ElementName=_combobox, Path=SelectedItem}"/>
        <ComboBox x:Name="_combobox" ItemsSource="{Binding ItemLists}"/>
    </StackPanel>
</Window>

Last, this is what is called your ViewModel. This binds the View and Model together.
class ViewModel
{
    public List<List<Item>> ItemLists { get; private set; }
    public ViewModel()
    {
        string[] items = { "Intel procesor Core i7 6800K", "Intel procesor Core i5 7400", "AMD procesor Ryzen 7 1800X" };
        ItemLists = new List<List<Item>>();
        ItemLists.Add(new List<Item>());
        foreach (string item in items)
            ItemLists[0].Add(new Item(item));
    }
}


text:
Q: Windows driver, spin lock acquisition and condition test Inside one dispatch routine we have the following code:
if (DeviceExtension->Flag)
{
    KeAcquireInStackQueuedSpinLockAtDpcLevel(&DeviceExtension->SpinLock, &LockHandle);

    //... when we will enter here, DeviceExtension->Flag can already be set to FALSE.

    KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
}

Inside another dispatch routine we have the following code:
KeAcquireInStackQueuedSpinLockAtDpcLevel(&DeviceExtension->SpinLock, &LockHandle);

//...

DeviceExtension->Flag = FALSE;
KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);

So when we will acquire spin lock inside first dispatch routine, DeviceExtension->Flag can already be set to FALSE by second routine. The solution would be to acquire spin lock and then check DeviceExtension->Flag. However DeviceExtension->Flag might be FALSE, and spin lock acquisition seems very heavy in this case.
I am not very familiar multithreading, especially in kernel mode. I know that question is stupid, but I got lost. What would be the right solution in this case? Thank you.

A:
this flag indicates that device is to be removed, so it works one way

for this special exist Run-Down Protection
you need have EX_RUNDOWN_REF RunRef; member in device extension instead bool Flag
initialize it with
ExInitializeRundownProtection(&RunRef);

when you need do some operation, only if device yet not removed you need do:
if (ExAcquireRundownProtection(&DeviceExtension->RunRef))
{
    // do something
    ExReleaseRundownProtection(&DeviceExtension->RunRef)
}

and in IRP_MN_REMOVE_DEVICE handler you need call
ExWaitForRundownProtectionRelease(&DeviceExtension->RunRef);

and important note - despite in msdn stated that ExAcquireRundownProtection and ExReleaseRundownProtection must be called on IRQL <= APC_LEVEL this is false and mistake. ExAcquireRundownProtection simply do some interlocked operations with memory to which point RunRef - so if it in non-paged pool - we can call this routine at any IRQL. device extension is in non-paged pool. the ExReleaseRundownProtection can additional call KeSetEvent with Wait is set to FALSE. as result it can be run at IRQL <= DISPATCH_LEVEL. ExReleaseRundownProtection we typical call from IoCompletion routine (which executes at an IRQL that is less than or equal to DISPATCH_LEVEL) so here all ok.
ExWaitForRundownProtectionRelease of course must be called at <= APC_LEVEL because here we can wait, but The PnP manager sends IRP_MN_REMOVE_DEVICE at IRQL PASSIVE_LEVEL - so again all ok here

of course your here can use and Remove Locks which do almost exactly same as rundown protection. simply rundown-protection - more new api, and much better designed/implemented compare remove locks. however in documentation for IoReleaseRemoveLock and IoReleaseRemoveLock correctly stated that IRQL
<= DISPATCH_LEVEL must be and IoReleaseRemoveLockAndWait must be called at PASSIVE_LEVEL

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the basic physics mechanism behind photosynthesis? Could a similar process be achieved artificially in a laboratory, with the same near perfect efficiency biological systems display.
Is there a sound simple theoretical model on how this works?

A: The mechanism of photosynthesis has been extremely well-studied and is well-understood, but a full explanation would fill a good-sized textbook, of which dozens have been written over the years. Here is the most basic explanation I can come up with:
The beating heart of photosynthesis is an extremely complicated molecule called chlorophyll, in which a mgnesium atom is surrounded by organic molecules that are folded up around the iron in extremely complicated ways.
The shape and proximity of the electron clouds surrounding the those molecules affects the charge distribution of the electrons surrounding the magnesium atom in just such a way as to make it possible for photons of light to excite an electron in the magnesium-organic molecule system, which enables a chemical reaction to take place that stores the energy of the photon in another large and complicated organic molecule.
That stored chemical energy then is the driving force behind a long and extremely complicated cascade of other chemical reactions that constitute the metabolism of the plant containing the chlorophyll. In its simplest form, the overall chemical reaction takes light, carbon dioxide and water and converts it into oxygen and carbohydrate molecules (i.e., plant tissue).
The overall process is highly inefficient from an energy transformation standpoint but extremely effective nonetheless.


text:
Q: Using attribute Id how to get attribute label in magento 2.1 Using attribute Id how to get attribute label in magento 2.1.
example :
    Array
       (
         [93] => 30
         [188] => 26
         [189] => 15
        ).

A:
Use below code:

public function __construct(
    \Magento\Eav\Model\Config $eavConfig,
    array $data = []
) {
    $this->_eavConfig = $eavConfig;
}

$attributeObj = $this->_eavConfig->getAttribute($entityType, $code);
$attributeObj->getFrontendLabel();

For example:
$attributeObj = $this->_eavConfig->getAttribute('catalog_product', 30);
$attributeObj->getFrontendLabel();

A: $_product = $this->objectManager->get('Magento\Catalog\Model\Product')->load($product_id);

$attributes = $product->getAttributes();

foreach ($attributes as $attribute) {
     label => __($attribute->getStoreLabel()),
     'value' => $value, //attribute Value
     'code' => $attribute->getAttributeCode(), //attribute Code
}

If looking for Option Text from OptionId:
$optionId = 30;
$attribute = $_product->getResource()->getAttribute('design_color');
if ($attribute->usesSource()) {
    $optionText = $attribute->getSource()->getOptionText($optionId);
}

If looking for attribute Label from attribute Code:
$_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getText($_product);

NOTE: Inject objectManager from contructor, Direct Use of ObjectManager is not allowed as per Magento

A:
Try to use bellow code

<?php
namespace Namespace\Modulename\Helper;

/**
* Class Helper Data
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $eavConfig;

    public function __construct(
        \Magento\Eav\Model\Config $eavConfig
    ){
        $this->eavConfig = $eavConfig;
    }

    // pass Attribute Code and Option Value
    public function getAttributeOptionLabel($attributeCode, $optionValue){
        $attribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);
        $options = $attribute->getSource()->getAllOptions();
        $key = array_search($optionValue, array_column($options, 'value'));
        return strtolower($options[$key]['label']);
    }
}


text:
Q: Knox OpenID login infinite loop I am trying to configure Apache Knox to use OpenID Connect (the ORY Hydra product).  The callback url is called, with the correct code= parameter, but then the login process loops ad infinitum.
I configured Knox according to this Auth0 guide (same thing, just update the URLs).
The login process just loops.  I think Knox doesn't know what to do with the code= value, that is, how to exchange it for an access_token and refresh_token.  What am I doing wrong?  Using the wrong authentication type, the wrong callback url, something else?


text:
Q: Naming; dynamically create a variable in javascript To avoid a javascript heap problem, I use multiple arrays: family1, family2,family3 ..., dogs1, dogs2, dogs3 ... Use example: 'family1 and dogs1', or 'family132 and dogs132' to create a new array 'results'.
How do I pass the "id" correctly
let  id = 'value here'
this.family + id
this.dogs + id

So far my str itself is pushed int the new array: t-h-i-s-.-f-a-m-i-l-y-1
for (let i = +0; i < +20; i++) {

  const id = 1;
  let str = 'this.family'+id;   // ?
  let str = 'this.dogs'+id;   // ?

  console.log(str);

  const result = {
      familyType: str[i],       // behavior: t-h-i-s-.-f-a-m-i-l-y-1
      protocol: this.dogs1[i],  // expected original behavior
  };

  results.push(result);

}

}

A: You are looking for:
let str = this['family'+id];

But this is generally a bad design pattern. Don't name your variables with incremental numbers. Use 2D arrays (i.e. arrays having arrays as values), like this.dog[id][i]. If you have "a javascript heap problem", then it is caused by some other code.


text:
Q: Can i connect something else to programming pins in STM32 (SWD)? As in the topic: Can i connect something else to programming pins in STM32 (SWD)?
For example a single LED with current limiting resistor connected to SWDIO and SWCLK pins. Will this load affect programming via this interface (SWD)? Should I use a buffer?

A: Yes, you can use STM32 SWD pins as GPIO, and yes, you need to think about the impact of doing so on the SWD functionality.
Likely you want anything else driven by those lines to be behind a buffer with a high impedance input, and you want anything that could drive those lines to be behind a specific enable.
But there's also a risk in re-purposing those lines, especially as GPIO output.  If you do so, you will not be able to connect an SWD probe to the running system.
With a full capability SWD adapter, you should be able to perform a coordinated "connect under reset" where the CPU core is reset and the SWD connection is used to suspend operation before the program can re-purpose the pins and disable SWD.  However, this can be difficult with some setups.
So generally, if you are going to re-purpose the pins, it's best for a program to provide a second or two of delay upon reset before doing so.
You probably also want to make doing so at all dependent on a macro definition, perhaps one passed on the compiler command line.  That way, if you decide you want to use a breakpoint debugger, you can build the code with alternate settings that do not re-purpose the SWD pins (maybe something like arm-non-eabi-gcc -DNO_REPURPOSE_SWD), and so leave them operating in SWD mode to permit the debugger to function.
And of course whatever you connect to those pins needs to not problematically mis-operate if it sees SWD traffic rather than the intended signals.  So things like motor drives are a very bad idea; but status LEDs, or serial advisory message outputs might be okay.


text:
Q: FreeBSD socket close problem I have a problem about xSocket close() method in FreeBSD.Despite of the fact that I search it in Google  I could not find any satisfied solution. Let me explain the problem  a little bit detailed;
I have a code that open ports and listen connection. I use the xSocket for this.Especially this is for multiplayer game.When user wants to set up a game I assign the ports for the user and user can create a game and wait for another players. When player closes his web browser or goes out from the game if the online player size in the created game  is smaller than 1 I close the ports by applying the  ondiscoonect method. This method clear the objects and makes game port close.Despite of the fact that the code says the port is closed it is not exactly closed. After the first game creation if another user wants to create a new game it gets an error that the ports is already in use.(java.net.BindException).The stack trace is below;
INFO: server (0.0.0.0:20051) has been shutdown
Apr 22, 2011 9:20:09 AM org.xsocket.connection.IoAcceptor <init>
WARNING: could not bind server to 0.0.0.0/0.0.0.0:20051. Reason: java.net.BindException: Address already in use
        at sun.nio.ch.Net.bind(Native Method)
        at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:119)
        at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:59)
        at org.xsocket.connection.IoAcceptor.<init>(IoAcceptor.java:117)
        at org.xsocket.connection.IoAcceptor.<init>(IoAcceptor.java:94)
        at org.xsocket.connection.IoProvider.createAcceptor(IoProvider.java:453)
        at org.xsocket.connection.Server.<init>(Server.java:492)
        at org.xsocket.connection.Server.<init>(Server.java:169)
        at           .engine.communication.Game.closeGame(Game.java:246)
        at           .engine.communication.Game.disconnect(Game.java:209)
        at           .engine.communication.Lounge.disconnect(Lounge.java:238)
        at           .engine.Engine.disconnect(Engine.java:102)
        at .engine.communication.gameSocketDataHandler.onDisconnect(gameSocketDataHandler.java:235)
        at org.xsocket.connection.HandlerAdapter.performOnDisconnect(HandlerAdapter.java:334)
        at org.xsocket.connection.HandlerAdapter.access$300(HandlerAdapter.java:42)
        at org.xsocket.connection.HandlerAdapter$PerformOnDisconnectTask.run(HandlerAdapter.java:317)
        at org.xsocket.SerializedTaskQueue.performPendingTasks(SerializedTaskQueue.java:161)
        at org.xsocket.SerializedTaskQueue.access$100(SerializedTaskQueue.java:40)
        at org.xsocket.SerializedTaskQueue$MultithreadedTaskProcessor.run(SerializedTaskQueue.java:189)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
        at java.lang.Thread.run(Thread.java:619)

As it can be seen in the trace the exception is thrown in the code line 246 of Game class.The code of this method is below;
public void closeGame() {
    try {

        server.close();
        System.out.println("Opened?"+server.isOpen());
        LoungeManager.removeGame(loungeId, gameId);
    } catch (Exception ex) {
        String err = "Game.closeGame:" + ex.getMessage();
        err += logGame.exceptionTrace(ex);
        logGame.appendLog(err, Severity.FATAL);
    }
}

Thanks for your help and again thanks the site stackoverflow. The question can be said a little bit long but I want myself to be understandable. I am waiting your advice.
kingspeech

A: FreeBSD is pretty good at closing sockets; I don't think the problem is the operating system.
When you set up your server socket, call setReuseAddress(true) before you bind. The operating system must keep the previous {srcip,srcport,dstip,dstport} tuple around beyond the lifetime of the server socket handle in your process; the reuse address option lets you set up another server socket while this is present.

A: I have the same issues in c++ project in linux.
The only thing that helped me is
setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)

before binding
Update:
It is not a bug, it is a feature


text:
Q: Simple datastore entity with 2 fields that are also unique All I am trying to produce is an entity that holds a unique username, and a unique device ID, and the ability to return an error if either of these conditions are not met on submission.
The only way I can see is to perform a query within a transaction, then filter the results. This however requires an ancestor (which seems unnecessary for a single simple entity).
What is the best method to go about doing this?

A: Here is an example that does what you want.
I put 2 entities to show you also how to make relationships
class Person(ndb.Expando):

    registration_date = ndb.DateTimeProperty(auto_now_add=True)

    @property
    def info(self):
        info = PersonInfo.query(ancestor=self.key).get()
        return info

class PersonInfo(ndb.Expando):

    email = ndb.StringProperty()
    nick_name = ndb.StringProperty()
    edit_date = ndb.DateTimeProperty(auto_now=True)

Later in the controller for register:
class RegisterPersonHandler(webapp2.RequestHandler):

    def get(self):
        user = users.get_current_user() #Stub here
        if not user:
            self.redirect(users.create_login_url(self.request.uri), abort=True)
            return
        person = Person.get_or_insert(user.user_id())
        if not self._register(person, user):
            # more logging is needed
            logging.warning('Warning registration failed')
            return

    @ndb.transactional()
    def _register(self, person, user):
        ''' Registration process happens here
        '''
        # check if the person has info and if not create it
        info = PersonInfo.query(ancestor=person.key).get()
        if not info:
            info = PersonInfo(id=user.user_id(), parent=person.key)
            info.nick_name = user.nickname()
            info.email = user.email()
            info.put()
        return True

To answer also the comment question:

How can you programatically tell whether the returned entity is a new
  or existing one though?

Try checking against a property that is default. Eg creation_date etc.
Though you can also check on something you need or on another entity's existence like I do because I expect the data to be consistent, and if not then create the bond.


text:
Q: Zend Route Regex and optional parameters I want to use a URL like this:
site.com/car-list/param1/value1/param2/value2
"car" is variable and can be anytihng. i solved the "site.com/car-list" part like this:
    $categoryRoute = new Zend_Controller_Router_Route_Regex(
        '(\b.+\-list\b)',
        array(
            'module' => 'default',
            'controller' => 'search',
            'action' => 'index'
        ),
        array(
            1 => 'productType'
        )
    );

I can get "car-list" when i want "productType" param. But i cant get rest of the url with $this->_getParam() in controller.
how can i do this? thanks.

A: Well, i don't see how to make it with Router_Route_Regex, but with Router_Route it would be easier (thought, i replace "-" with "/")
$categoryRoute = new Zend_Controller_Router_Route
    ':car/list/*',
    array(
        'module' => 'default',
        'controller' => 'search',
        'action' => 'index'
    )
);

magic happens due to the "/*" at the end of the string. :car variable can be got with $request->getParam('car');


text:
Q: Bamboo is not running my tests after i renamed the file We have automatic build and deployment, through Atlassian Bamboo. Tests were configured to run along with that. But I renamed a test file, and now Bamboo is running testless build. How to make bamboo to pick my new test file?

A: Go to Bamboo, chose the plan that run the test, go to Configuration setting, you have to drill down stages -> jobs ->tasks and look for what tasks are running that test file and make the appropriate change (Probably change the file name there ). Reading the build log might help narrow down the search.


text:
Q: php container can't connect to mongo container I setup docker compose to locally test my app and it seems that the app can't access the mongo instance even though I'm able to on Studio 3T.
this is what my docker-compose file looks like:
services:
  web:
    image: php-app:latest
    ports:
      - '80:80'
    depends_on:
      - db
    networks:
      - code-network
  db:
    container_name: mongodb_4.4
    image: mongo:4.4
    environment:
      MONGO_INITDB_ROOT_USERNAME: demo
      MONGO_INITDB_ROOT_PASSWORD: secret
    ports:
      - '27017:27017'
    networks:
      - code-network
    volumes:
      - mongodb_data_container:/data/db
volumes:
  mongodb_data_container: {}
networks:
  code-network:
    driver: bridge

this is what shows up in the docker console:
PHP Fatal error:  Uncaught MongoDB\\Driver\\Exception\\ConnectionTimeoutException: No suitable servers found (`serverSelectionTryOnce` set): [connection refused calling ismaster on '127.0.0.1:27017'] in /var/www/html/vendor/mongodb/mongodb/src/functions.php:431
Stack trace:
#0 /var/www/html/vendor/mongodb/mongodb/src/functions.php(431): MongoDB\\Driver\\Manager->selectServer(Object(MongoDB\\Driver\\ReadPreference))
#1 /var/www/html/vendor/mongodb/mongodb/src/Collection.php(230): MongoDB\\select_server(Object(MongoDB\\Driver\\Manager), Array)
#2 /var/www/html/index.php(12): MongoDB\\Collection->aggregate(Array)
#3 {main}\n  thrown in /var/www/html/vendor/mongodb/mongodb/src/functions.php on line 431

I've tried adjusting my php code to connect using localhost and 127.0.0.1 and neither worked.

A: It seems you did not configure your MongoDB client yet, the default DSN is mongodb://127.0.0.1/ (the local host), and it should be mongodb://db/ (the db service you defined) in your case.
Read more about the constructor for MongoDB client:

*

*MongoDB ligrary client

*MongoDB extension manager


text:
Q: how to add days retrieved from database with a date mysql i have start_date and number_of_days_to _complete stored in database.now i want to echo finish_date by adding this two dynamically.i added a constant date as follows
<?php
           $date = strtotime("+7 day");
           echo date('d/m/Y', $date);
 ?>

what should be the syntax for my requirement???
i guessed a syntax but it returns wrong date.the format is as follows
$date=strtotime("+<?php $row->day_number; ?> day");
echo date('Y-m-d', $date); ?>

A: Change it to this :
$requiredDayString = '+'+$row->day_number;
$date=strtotime("$requiredDayString day",strtotime("2016-04-06"));
echo date('Y-m-d', $date); ?>

or to make it more dynamic pass as a variable :
$requiredDayString = '+'+$row->day_number;
$inputDate = "2016-04-06";
$date=strtotime("$requiredDayString day",strtotime($inputDate ));
echo date('Y-m-d', $date); ?>

A: You may use DATE_ADD function in MySQL, For Ex
SELECT DATE_ADD(now(),INTERVAL 2 DAY) AS resultDate  FROM dual


text:
Q: Action fired, but state not updated in reducer I have a basic action which will fire a number of events.
export const ADDED = 'cartridge/ADDED';
export const REMOVED = 'cartridge/REMOVED';
export const SUBSCRIBE = 'cartridge/SUBSCRIBE';
export const UNSUBSCRIBE = 'cartridge/UNSUBSCRIBE';
export const SUBSCRIPTION_READY = 'cartridge/SUBSCRIPTION_READY';
export const SUBSCRIPTION_ERROR = 'cartridge/SUBSCRIPTION_ERROR';

export function subscribe() {
  return (dispatch, getState) => {
    const { meteor: { client: Meteor } } = getState();
    const sub = Meteor.subscribe('cartridges');
    Meteor.ddp.on('added', function (document) {
      const { name, id: _id, fields } = document;
      dispatch({ type: ADDED, payload: { _id, ...fields } });
    });

    dispatch({ type: SUBSCRIBE, payload: sub });

    sub.on('ready', () => dispatch({
      type: SUBSCRIPTION_READY
    })).on('error', payload => dispatch({
      type: SUBSCRIPTION_ERROR,
      payload
    }));
  }
}

finally, on my reducer, I do the following (abridged).
export default function cartridges(state={
  data: {},
  isReady: false,
  isSubscribed: false
}, action) {
  switch (action.type) {
    // ...
    case SUBSCRIPTION_READY:
      return Object.assign({}, state, {
        isReady: true
      });
    default:
      return state;
  }
}

However, while this action DOES fire (can be seen in redux-logger), it never catches the action in the reducer. why would this be?


text:
Q: How to transfer file only when it changed in salt? I am using the following way to provide bundled software project to salt minions:
proj-archive:
  cmd:
    - run
    - name: "/bin/tar -zxf /home/myhome/Proj.tgz -C {{ proj_dir }}"
    - require:
      - file:  /home/myhome/Proj.tgz
      - {{ proj_dir }}
  file:
    - managed
    - user: someone
    - group: someone
    - mode: '0600'
    - makedirs: True
    - name: /home/myhome/Proj.tgz
    - source: salt://Proj.tgz

As far as I can tell, it does the job, but these rules are always active, even when archive have not changed. This brings unnecessary delays in deployment. In a similar situation, for example, service restart with watch clause on a file, it is possible to restart when file changed. How to tell salt to copy file over network only when it changed? Is there any automatic way to do it?
The Proj.tgz in salt directory is a symlink to file location, if it matters.
The archive.extracted is not that useful, because it does not trigger when changes are inside files, no files added or removed in the archive.
Some relevant info https://github.com/saltstack/salt/issues/40484 , but I am unsure of resolution / workaround.

A: You can replace both states with salt.states.archive. It might look like this:
proj-archive:
    archive.extracted:
        - name: {{ proj_dir }}
        - source: salt://Proj.tgz
        - user: someone
        - group: someone
        - source_hash_update: True

The key feature here is source_hash_update. From the docs:

Set this to True if archive should be extracted if source_hash has changed. This would extract regardless of the if_missing parameter.

I'm not sure whether or not the archive gets transferred on each state.apply. But I guess it will not.


text:
Q: boost interprocess message_queue and fork I am trying to communicate with forked child process using message queue from boost interprocess library. When child process calls receive it causes exception with message

boost::interprocess_exception::library_error

I am using GCC 6.3 on Debian 9 x64.
#include <iostream>
#include <unistd.h>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <memory>

int main(int argc, char* argv[])
{
    using namespace boost::interprocess;

    const char* name = "foo-552b8ae9-6037-4b77-aa0d-d4dc9dad790b";
    const int max_num_msg = 100;
    const int max_msg_size = 32;
    bool is_child = false;

    message_queue::remove(name);
    auto mq = std::make_unique<message_queue>(create_only, name, max_num_msg, max_msg_size);

    auto child_pid = fork();
    if (child_pid == -1)
    {
        std::cout << "fork failed" << std::endl;
        return -1;
    }
    else if (child_pid == 0)
    {
        is_child = true;
    }

    if (is_child)
    {
        // does child needs to reopen it?
        mq.reset( new message_queue(open_only, name) );
    }

    int send_num = 0;
    while(true)
    {
        unsigned int priority = 0;
        if (is_child)
        {
            message_queue::size_type bytes = 0;
            try
            {
                int num;
                // Always throws. What is wrong ???????
                mq->receive(&num, sizeof(num), bytes, priority);
                std::cout <<  num << std::endl;
            }
            catch(const std::exception& e)
            {
                std::cout << "Receive caused execption " << e.what() << std::endl;
            }
            sleep(1);
        }
        else
        {
            mq->send(&send_num, sizeof(send_num), priority);
            send_num++;
            sleep(5);
        }
    }

    return 0;
}

Also, in child process is it required to reopen the message queue created by the parent process? I tried it both ways and neither worked. I am getting the same exception on receive.

A: The problem is that your receive buffer is smaller than max_msg_size. Assuming 4-byte integers, this should work:
int num[8];
mq.receive(num, sizeof(num), bytes, priority);
std::cout << *num << std::endl;

Also, I see no reason to play fast and loose with the actual queue instance. Just create it per process:
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <iostream>
#include <memory>
#include <unistd.h>

int main() {
    namespace bip = boost::interprocess;

    const char *name = "foo-552b8ae9-6037-4b77-aa0d-d4dc9dad790b";
    {
        const int max_num_msg = 100;
        const int max_msg_size = 32;
        bip::message_queue::remove(name);
        bip::message_queue mq(bip::create_only, name, max_num_msg, max_msg_size);
    }

    auto child_pid = fork();
    if (child_pid == -1) {
        std::cout << "fork failed" << std::endl;
        return -1;
    }
    bip::message_queue mq(bip::open_only, name);

    if (bool const is_child = (child_pid == 0)) {
        while (true) {
            unsigned int priority = 0;
            bip::message_queue::size_type bytes = 0;

            try {
                int num[8];
                mq.receive(num, sizeof(num), bytes, priority);
                std::cout << *num << std::endl;
            } catch (const bip::interprocess_exception &e) {
                std::cout << "Receive caused execption " << boost::diagnostic_information(e, true) << std::endl;
            }
            sleep(1);
        }
    } else {
        // parent
        int send_num = 0;
        while (true) {
            unsigned int priority = 0;

            mq.send(&send_num, sizeof(send_num), priority);
            send_num++;
            sleep(5);
        }
    }
}


text:
Q: OO Design - Encapsulation question Scenario
Let's say that there is an entity in my domain called Shop. As a shop owner (user), I am able to create rewards that customer users will be able to exchange.
It also could be possible to have some kind of reward creation policy (eg. a maximum number of rewards that as store owner I can create: if that value is 4 -> I won't be able to add more than 4 rewards to my store).
Reward creation (for a shop)
Considering the following 1-to-N relationship: Shop (1)->(N) Reward, what would be the most appropriate way to manage rewards (taking into account that Shop would have a list of Reward's)?
In case there was any reward policy that could be somehow abstracted out by a IRewardCreationPolicy interface and used where needed:
interface IRewardCreationPolicy {
   isAllowed(shop: Shop);
}

Below are some design alternatives that I am taking into consideration.
 Alternative #1
Reward management is fully handled by the Shop class:
class Reward {
   /* props, methods... */
}

class Shop {
   private id: number;
   private name: string;
   private rewards: Reward[];

   constructor(rewardCreationPolicy: IRewardCreationPolicy) {}

   addReward(reward: Reward): void {
      if (!this.rewardCreationPolicy.isAllowed(this)) {
         // throw exception
      }
      this.rewards.push(reward);
   }

   removeReward(id: number): void {
      /* Remove reward with the given id */
   }
}

class AddRewardUseCase {
   constructor(shopStorage: IShopStorage) {}

   execute(request: AddRewardRequest) {
      const shop = this.shopStorage.findById(request.shopId);
      shop.addReward(request.reward);
      this.shopStorage.update(shop);
   }
}

 Alternative #2
Reward management is fully handled outside the Shop class:
class Reward {
   /* props, methods... */
}

class Shop {
   private id: number;
   private name: string;
   private rewards: Reward[];

   constructor() {}

   getRewards(): Reward[] {
      return this.rewards;
   }
}

class AddRewardUseCase {
   constructor(
      shopStorage: IShopStorage,
      rewardCreationPolicy: IRewardCreationPolicy
   ) {}

   execute(request: AddRewardRequest) {
      const shop = this.shopStorage.findById(request.shopId);

      if (!this.rewardCreationPolicy.isAllowed(shop)) {
         // throw exception
      }

      shop.getRewards().push(request.reward);
      this.shopStorage.update(shop);
   }
}

Questions
In this case there is class (Shop) that holds a list of objects (Reward's). Should any possible action on this list be encapsulated inside the holder class? In this case, I assume that if we had any other list aside from the rewards it would be also managed by the holder itself too.
I understand that we would be talking about encapsulation here, so in that case I guess the Alternative #1 would be the best choice. What are your thoughts on this?

A: It depends, and more specifically it depends whether or not it makes sense that a RewardCreationPolicy is linked to a Shop or not.
Let's substitute this scenario with a simpler example:

*

*Your problem is that you need to create a list of a random subset of another list. You instanciate your target list as empty, and add elements based on a random predicate function. This predicate have no reason to belong to a list implementation. Most lists don't need predicates to be built.

*Your problem is that you need to provide a list implementation that size is limited to 4, and being used as a normal list by your program. The list must be able to know if it adds an element to itself or not: the predicate is part of the custom list implementation.
So based on your usage of Shop and RewardCreationPolicy, and the link between them, it makes sense or not to tie them by implementation.
Additional context is needed, but based on the existing context, making Shop responsible does provide stronger encapsulation and does sound more appealing. It wouldn't be so if you realize after a while there is several more predicates you need to add to it to make the rewards being managed properly.

A: From your example, I think it is pretty clear that Rewards are part of the transactional consistency boundary of Shop aggregate.
In DDD lingo, the Aggregate should preferably satisfy all invariant rules at all time. To ensure that a Shop object meets all business rules (including the limit of 4 rewards) at all times, you have no alternative but to manipulate rewards via the shop object.
How you establish, validate, and enforce the invariants (like the check for the current number of rewards vs. limit) is flexible and can change over time. But what cannot change is the fact that these invariants should be fully satisfied by the time you persist the shop object.
The only condition that may lead you in a different path, one of eventual consistency/validation, could be if you end up having to load a huge number of reward objects as part of your shop object. Since you are establishing a clear limit in your case, and that limit is pretty small, this condition may not be applicable.


text:
Q: How to build a register live api successfully on heroku? How to fix this, mongo error MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.
const db = require('./configs/config').get(process.env.NODE_ENV);

my code is:
index.js
mongoose.Promise = global.Promise;
mongoose.connect(db.DATABASE, { useNewUrlParser: true, useUnifiedTopology: true }, function (err) {
    if (err) console.log(err);
    console.log("database is connected");
})

config.js code:
const config = {
    production: {
        SECRET: process.env.SECRET,
        DATABASE: process.env.MONGODB_URI

    },
    default: {
        SECRET: 'mysecretkey',
        // DATABASE: 'mongodb://localhost:27017/eduInternJan'
        DATABASE: 'mongodb+srv://Sagarkumar:Sagar457@cluster0.96hmj.mongodb.net/loginapi?retryWrites=true&w=majority'
    }
}
exports.get = function get(env) {
    return config[env] || config.default
}


text:
Q: Which regions do twilio programmable chat support? I have built a chat app using twilio to completion but I have noticed initializing it is pretty slow on an EDGE connection, averaging to 10-15 seconds (Whatsapp and telegram takes about 3 seconds on the same connection).This is without having set any region via properties on the sdk. Am looking to achieving a snappy startup time like that of telegram/whatsapp.
To go around this issue I thought it might be network latency issue and I thought maybe setting different regions might resolving it. So far I have tried setting the regions provided here https://www.twilio.com/docs/api/client/regions but am getting an error message request to EMS service has failed unable to set FPA token and error code 0.
Am in africa and my target audience will mostly be running on edge connections.
Please help resolve.
Thanks.

A: Twilio developer evangelist here.
Twilio Programmable Chat does not currently take a region option, like Twilio Client v1.4 does. In fact, when initializing a chat the only option you can set right now is the logLevel.
If you are interested in multi-region chat services, I suggest you get in touch with Twilio support to register that this is an issue for you.


text:
Q: Create Executable Jar that includes all the dependencies as packaged jars I'm trying to understand how to include all of the dependencies in an executable jar file as packaged jars (i.e. include jars within a jar) but I'm failing miserably.
Could someone point me in the right direction please?
Note that I wan't the resultant fat jar to have jars packaged within it not the un-packaged equivalent that you get using the maven-assembly-plugin

A: What you want to create is called a fat jar. You can generate it by doing next steps.
Add Build section in your POM file as follows:
<build>
    <finalName>example</finalName>
    <plugins>

        <!-- Set a compiler level -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>${jdk.version}</source>
                <target>${jdk.version}</target>
            </configuration>
        </plugin>

        <!-- Maven Assembly Plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4.1</version>
            <configuration>
                <!-- get all project dependencies -->
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <!-- MainClass in mainfest make a executable jar -->
                <archive>
                  <manifest>
                    <mainClass>com.example.Main</mainClass>
                  </manifest>
                </archive>

            </configuration>
            <executions>
              <execution>
                <id>make-assembly</id>
                <!-- bind to the packaging phase -->
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
              </execution>
            </executions>
        </plugin>

    </plugins>
</build>

Above "Maven Assembly Plugin" is bind to the Maven's packaging phase, to produces the final Jar, just package it using:
mvn package

Two jar files will be created in the target folder.

*

*example.jar – Only your project classes

*example-jar-with-dependencies.jar – Project and dependency classes in a single jar.
You can now check the contents of your fat jar with:
jar tf target/example-jar-with-dependencies.jar

A: Include dependencies in the pom.xml. Build the project using mvn clean install and the result will have these dependencies.
You can then run the jar using
java -cp <jar Filename> <main class name>


text:
Q: MonoDevelop with Unity 2018.3.1 and .NET 4.X I don't know if there are still people who use MonoDevelop with Unity, but I love it and not willing to switch to visual studio.
I downloaded MonoDevelop for unity since it's not built in with unity and used it with no problems so far, however, since I updated my project to use .NET 4.X from unity's player settings (Scripting runtime version) MonoDevelop stopped working well. It does open my script and I edit them with no problems, but autocomplete doesn't work anymore at all and the syntax highlighting is barely there with only object type name is in one color and everything else is in white. I used a syntax highlighting called Monokai which I'm absolutely in love with.
How can I fix MonoDevelop to work with .NET 4.X because when I tried to change the Scripting runtime version from the player settings everything worked as expected with MonoDevelop

A: I don't know if you can actually. As this Unity blog post states:

On Windows, we ship Visual Studio 2017 Community with Unity and it already supports the latest C# features and C# debugging on the new .NET 4.6 scripting runtime. MonoDevelop-Unity 5.9.6 will be removed from the Unity 2018.1 Windows installer, as it does not support these features.

There may be some way of doing it, but I don't think it would be worth the trouble. There are plenty of other IDEs other than Visual Studio out there. I personally used JetBrains Rider for a long time before switching to VSCode and finally back to Visual Studio proper.


text:
Q: Certicate and Service token in gitlab pipeline for kubernetes service I am a neophyte, I'm trying to configure my project on gitlab to be able to integrate it with a kubernetes cluster infrastructure pipeline.
While I am configuring gitlab asked for a certificate and a token. Since kuberntes is deployed on azure, how can I create/retrieve the certicate and required token?
Possibly which user / secret in the kuberntes service does it refer to?

A: You can get the default values of CA certificate using the below steps :
CA Certificate:
CA certificate is  nothing but the Kubernetes certificate that we use in the config file for authenticating to the cluster.

*

*Connect to AKS cluster,az aks get-credentials — resource-group <RG> — name <KubeName>

*Run kubectl get secrets , after you run command in output you will
get a default token name , you can copy the name.

*Run kubectl get secret <secret name> -o jsonpath="{['data']['ca\.crt']}" | base64 --decode to get the
certificate , you can copy the certificate and use it in setting the
runner.

Output:

Token :
The token will be of the service account with cluster-admin permissions which Gitlab will use to access the AKS cluster , so you can create a new admin service account if not created earlier by using below steps:

*

*Create a Yaml file with below contents :
apiVersion: v1
kind: ServiceAccount
metadata:
  name: gitlab-admin
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: gitlab-admin
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
  - kind: ServiceAccount
    name: gitlab-admin
    namespace: kube-system

*Run kubectl apply -f <filename>.yaml to apply and bind the service
account to the cluster.

*Run kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep gitlab-admin | awk '{print $1}') to get the token
for the Gitlab Admin we created in the file and bind with the
cluster in the previous step. You can copy the token value  and use it in
the runner setting .
Output:


text:
Q: Are repeatable performance tests possible on a VM? My application does a lot of database inserts, so disk I/O is a big part of the workload. QA does almost all testing on VM's. I'm concerned that tests intended to detect performance regressions won't give valid repeatable results in a VM environment, since other activity on the physical machine will affect the application performance.
Is this a legitimate concern, or do modern virtual environments have a way of truly isolating an application's environment which would allow for repeatable performance tests?
I want to put my application and database on a "machine", run a test and note how much time it took (which will be some number of hours/minutes, not seconds/milliseconds). Later in my development cycle, I want to run the same test and check whether performance has regressed due to code changes. When running on a dedicated physical machine, I get reasonably consistent results. My question is, if I run this test on a virtual machine, might I get significant differences in run time due to work being done by other VM's on the same physical box? Is there any way to configure the VM to control for this, considering that disk I/O is a major part of the workload?

A: Much of what you are asking is highly dependent on the environment.  There are vendors that allow the apportioning of min and max CPU and IO to a VM among a really large number of other options.  The downside of this is that as you start chopping up the resources like this, you will generally end up with lower utilization rates.  Most applications do not use CPU continually at the same rate all the time so by letting VMs use what they need from a shared pool, you tend to be able to achieve an average utilization (as a percentage of all CPU available) that is higher than if you were to allocate min and max for each.
In general my experience with performance results is that performance can vary for many reasons that can be hard to control.  I think it makes more sense to think of performance in more statistical terms.  If you are going to be running this application on a VM in production, I would say you should absolutely run it in a VM in performance testing and configure it the way you plan to configure it in prod.  Run lots of tests at different times of the day without changing anything and see what variance you get in results.  This, by itself is useful info.  You may find that you want to reconsider your configuration for production in order to reduce variability in performance.
If you are planning on running this on dedicated hardware in production, then the best option is to, again, run the performance tests on as close to a similar setup as you can.  If you are going to VMs for testing because of resource constraints, then I would suggest setting apportioning resources to your VM so that they are fixed as they would be on the dedicated hardware.

A: To address some of the comments first, yes all the hypervisors worth building a VM environment upon have the ability to limit resource consumption and also guarantee minimums. You can leverage these settings to establish performance service levels. Establish the minimum requirements and translate that into a VM sizing. For example, a 2 core vCpu and 4GB RAM, and allocate a VM that cannot be given anymore and validate the app performance is within the requirements.
This guide from vmWare explains from that products perspective:
https://www.vmware.com/files/pdf/partners/tap/directions-vmware-ready-testing-application-software.pdf
A key point in that guide is to do your performance testing while also monitoring the hypervisor to make sure the CPU < 70% and memory is not starved so that virtual swapping is happening.
A general rule of thumb is when either of those things happen (CPU of the hypervisor > 70% or physical memory exhausted on the hypervisor) you can expect to see a degradation of performance of the VMs.
You can do the same for the storage and net IO dimensions, but this is going to be driven by the investment made in the underlying architecture. My organization puts VMs on SAN with multiple 10GB uplinks to the SAN, and that results in the VMs seeing higher storage IO than they would see with local disk.
Ideally, the organization your app will be deployed has a managed VM infrastructure with monitoring of the hypervisors being done and being proactive to manage such that the hypervisors aren't pushed to the point that creates VM slow down. If you can, get metrics on the hypervisor to understand its general performance trends, and then also track that while testing and state your app's requirements based on the assumption that the hypervisor will be managed to stay within those same parameters.
If you can't get metrics about the hypervisors resource and performance, then really all you can do is measure resource used by your OS and make that the requirement that needs to be guaranteed by the hypervisor.
Since your concern is mainly around storage IO, this blog focuses on measuring IOPs:
https://blog.synology.com/?p=146


text:
Q: Kafka : Generating unique IDs for strings across partitions I'm trying to asses if Kafka could be used to scale-out our current solution.
I can identify partitions easily. Currently, the requirement is there to be 1500 partitions, each having 1-2 events per second, but future might go as high as 10000 partitions.
But there is one part of our solution which I don't know how would be solved in Kafka.
The problem is that each message contains a string and I want to assign a unique ID to each string across the whole topic. So same strings have the same ID while different strings have different IDs. The IDs don't need to be sequential, nor do they need to be always-growing.
The IDs will then be used down-stream as unique keys to identify those strings. The strings can be hundreds of characters long, so I don't think they would make efficient keys.
More advanced usage would be where messages might have different "kinds" of strings, so there would be multiple unique sequences of IDs. And messages will contain only some of those kinds depending on the type of the message.
Another advanced usage would be that the values are not strings, but structures and if two structures are same would be some more elaborate rule, like if PropA is equal, then structures are equal, if not, then structures are equal if PropB is equal.
To illustrate the problem: Each partition is a computer in a network. Each event is action on the computer. Events need to be ordered per-computer so that events that change the state of the computer (eg. user logged in) can affect other types of events, and ordering is critical for that. Eg. the user opened an application, a file is written, a flash drive is inserted, etc.. And I need each application, file,  flash drive, or many others to have unique identifiers across all computers. This is then used to calculate statistics down-stream. And sometimes, an event can have multiple of those, eg. operation on a specific file on the specific flash drive.

A: There is a very nice post about kafka and blockchain. This is collective mind work and I think this could solve your IDs scalability issue. For solution refer to "Blockchain: reasons." part. All credits goes to respective authors.

*

*Idea is simple, yet efficient:

*

*Data is hash based, with link to previous block

*Data may be very well same hashes, links to respective blocks of types

*Custom block-chain solution means you in control of data encoding/decoding

*Each hash chain is self-contained, and essentially may be your process (hdd/ram/cpu/word/app etc.)

*Each hash chain may be a message itself

*Bonus: statistics and analytics may be very well stored in block-chain, with high support for compression and replication. Consumers are pretty cheap in that context (scalability).

Proc:

*

*Unique identifier issue solved

*All records linked and thanks to kafka & blockchain highly ordered

*Data extendable

*Kafka properties applied

Cons:

*

*Encryption/Decryption is CPU intensive

*Growing level of hash calculation complexity

Problem: without problem context it's hard to approximate the limitations that need to be addressed further. However, assuming calculated solution has a finite nature you should have no issues scaling the solution in a regular way.

Bottom line:
Without knowledge of requirements in terms of speed/cost/quality it's hard to give a better, backed answer with working example. CPU cloud extension may be comparably cheap, data storage - depends on time for how long and what amount of data you want to store, replay-ability, etc. It's a good chunk of work. Prototype? Concept in referenced article.


text:
Q: Waiting until animation is over until replacing data inside the div I am having trouble changing the contents of a div. What I want to achieve is wait for the animation to end and then change the content to launch the animation to reveal the new info. This code works from time to time, meaning sometimes it hangs (isWorking never becomes false, because animation freezes or animation never has the time to finish from the constant looping inside the while.) Is there a way to wait for the animation to end and then change the content? (The way you see it below allows me to browse for the new content while the animation is ongoing which saves time for the end user.) Is there a way to catch when the animation ends?
 function DesignResults(InnerHTML) {
            while(isWorking){
            }
            $("#holder").html(InnerHTML);
            ShowSearch(true);
    }
    var isWorking = false;
    function ShowSearch(show) {
            isWorking = true;
            var outer = $("#outer");
            var inner = $("#inner");
            var height = 0;
            if (show == true)
                height = inner.outerHeight();
            var loaderHeight
            if (height > 0) {
                loaderHeight = 0;
            } else {
                loaderHeight = 31;
            }
            outer.animate({
                'height': height + "px"
            }, 1600, function () {
                $("#loading").animate({ 'height': loaderHeight + "px" }, 900, function () { });
                isWorking = false;
            });
    }

I understand that $(elem).is(':animated') will give me if the animation is still in progress, but that still freezes everything due to the constant looping of the while. Can anyone point me to the right direction?
EDIT:
I guess I am misunderstood. Here is the plan I want to achieve:

*

*Start hiding animation.

*While the animation is hiding I am launching another function to get the content
If I get the content faster I wish to wait for the animation to end then change the content and show the layer again.
There isn't a issue here if the data takes more than a second to return

I agree that i can do it after the animation completes as you suggested, but I have put the animation to almost 1 second execute time and that time can be used for the data to be pulled from the database. I am looking for the most effective code.

A: The last parameter in this function:
$("#loading").animate({ 'height': loaderHeight + "px" }, 900, function () { });

Is the 'complete' function. This function is called when the animation is complete.
So, you can do something in this function when it's complete, like so:
$("#loading").animate({ 'height': loaderHeight + "px" }, 900, function () {
    alert('animations complete!');
});

----Edit----
Based on your edits, you probably want to do something like this.

*

*Have a variable that will let you know when both are finished:
var signal = 0;

*Have a function to change your content with this in it:
function changeContent() {
    signal++;
    if (signal === 2) {
        // change the content code here
        signal = 0;
    }
}

*When the animation is finished, call:
changeContent();

*When you've grabbed the data, call:
changeContent();

When changeContent() is called the first time by either function, it will increment signal to 1 and exit the function. Then on the second time, it will increment signal to 2. Since signal === 2, you know that both the animation and grabbing the data is complete, so you can now change your content.
The good part about using an integer to do this, is if you want to have 3, 4, 5+ functions finish working before changing your content. In this case you just have to change the condition by increasing the number in if (signal === 2).

A: Just add the additional task here
$("#loading").animate({ 'height': loaderHeight + "px" }, 900, function () { /* Change Content */ });

Than it would be execute after the animation


text:
Q: How do I get FlashDevelop to show the right api documentation? I have been working with Flixel in FlashDevelop for quite some time, and I recently updated my Flixel library to the latest version. Some things have changed names or have been moved or had their inputs changed. For some reason, FlashDevelop is still showing me the documentation from the old version of Flixel as I type things in, so I keep trying to use variable and functions etc that no longer exist.
I've searched around for a solution, and I'm sure it will be painfully easy/obvious once I get it fixed, but so far I've had no luck finding one.
And I also wonder if I'm calling it the wrong thing (which might be why I can't find the solution).

A: FlashDevelop shows the documentation as extracted from the libraries you have included in your project, is it possible you have both the old and the new versions added to your project?


text:
Q: How can I get email of the last user who modified each cell Trying to add a 'rolling' note of changes at each cell, including user email, time, old and new values, so I wrote the below script:
/**
 * The event handler triggered when editing the spreadsheet.
 * @param {Event} e The onEdit event.
 */
function onEdit(e){
  // Set a comment on the edited cell to indicate when it was changed.
  var range = e.range;
  var row = range.getRow();
  var column = range.getColumn();

  // Get the email address of the person running the script.
   var email = Session.getActiveUser().getEmail();

  Logger.log("data changed");
  range.setNote(range.getNotes().concat('Last modified at: ' + new Date() + ' by: ' + email + ' from: ' + String(e.oldValue) + ' to: ' + range.getValue() + "\n"));
}

I'd the below notes, that are not as I expect:

*

*User email not displaying at all,

*If I made copy/paste of multiple cells, then old value appear as undefined, and new value for all cells shows only the new value of the first cell.

My sheet can be opened here

A: The info that you are adding is already automatically recorded and available by right clicking on a cell and selecting the corresponding menu item, anyway, the simple on edit trigger is very limited compared with the installable on edit trigger but the Session.getActiveUser().getEmail() only returns an email if the script is ran by using G Suite accounts or by the owner of the spreadsheet / script or the user created the installable on edit trigger that called the script. Somehow this is already documented in the official docs.
Reference

*

*https://developers.google.com/apps-script/reference/base/session#getactiveuser
Related

*

*Determine current user in Apps Script (oldest +7 at this time with an answer with +12)

*Google Spreadsheets: Can't Fetch User Email via Session.getActiveUser().getEmail()

*Session.getActiveUser().getEmail() returns no Value

*Set Permission for getEmail to Work for Users on Same G Suite Domain


text:
Q: How to move X number of files randomly in Mac terminal? How can I move 100 random files from one directory to another in the Mac terminal? I would use shuf in linux.

A: Based on glenn's commend, here's the answer (this would move 100 random files in the current directory):
shuf -zen100 * | xargs -0 -J % mv % /New_Dir/


text:
Q: Maximum Likelihood Estimation - Symbol Change I'm trying to understand why when simplifying the exponential likelihood function, the symbol changed from a product of sequences to summation and why isn't the theta in the exponential to the power of n?.
$$
\ p(y | \theta) = \prod_{i=1}^{n} (\theta \cdot exp(-\theta \cdot y_{i})
$$
$$
\ p(y | \theta) =  \theta ^ {n} \cdot \prod_{i=1}^{n} exp(-\theta \cdot y_{i})
$$
$$
\ p(y | \theta) =  \theta ^ {n} \cdot exp(-\theta \cdot \sum_{i=1}^{n} y_{i})
$$


text:
Q: Container not changing color until file is refreshed I want to change color of container onTap from shade of grey to white and everything works alright in my FeedScreen file but in filter file I need to exit and then go back to see the change even tho i did everything exactly same in FeedScreen and Filter file. i think the problem has something to do with the fact that i enter filter menu from feed screen on tap of the button but im not sure.
this is filter file that doesnt work properly:
class _ExampleState extends State<Example> {
  int _selectedindex = 0;

  void _onItemTapped(int index) {
    setState(() {
      _selectedindex = index;
    });
  }

  int index = 0;
  var random = Random();
  List<Color> myColors = [
    Colors.white,
    Colors.grey.shade900,
    Colors.green,
    Colors.cyan,
    Colors.pink,
  ];

  void changeColorsIndex() {
    setState(() {
      index = random.nextInt(4);
    });
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Container(
      width: size.width,
      height: 40,
      color: Color.fromARGB(255, 28, 28, 28),
      child: Row(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 1.5),
            child: IconButton(
              onPressed: (() {
                setState(
                  () {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return SingleChildScrollView(
                          scrollDirection: Axis.vertical,
                          child: Container(
                            width: size.width,
                            height: size.height,
                            child: Scaffold(
                              backgroundColor: Colors.black,
                              body: SingleChildScrollView(
                                scrollDirection: Axis.vertical,
                                child: Padding(
                                  padding: const EdgeInsets.only(bottom: 30),
                                  child: Column(
                                    children: [
                                      Center(
                                        child: Padding(
                                          padding:
                                              const EdgeInsets.only(top: 5),
                                          child: IconButton(
                                            onPressed: () {
                                              Navigator.pop(
                                                context,
                                                MaterialPageRoute(
                                                  builder: (context) =>
                                                      TopTab(),
                                                ),
                                              );
                                            },
                                            icon: const Icon(
                                                Icons.arrow_drop_down),
                                            iconSize: 45,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                      const Gap(15),
                                      Container(
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            InkWell(
                                              onTap: () {
                                                setState(() {
                                                  changeColorsIndex();
                                                });
                                              },
                                              child: Container(
                                                width: 199,
                                                height: 50,
                                                color: myColors[index],
                                                child: const Center(
                                                  child: Text(
                                                    'Men\'s',
                                                    style: TextStyle(
                                                        fontSize: 14,
                                                        fontWeight:
                                                            FontWeight.w600,
                                                        color: Colors.white),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        );
                      },
                    );
                  },
                );
              }),
              icon: Icon(Ionicons.options_outline),
              iconSize: 20,
              color: Colors.white,
            ),
          ),
          const Gap(6),
          Text(
            'Filter by size',
            style: TextStyle(
                color: Colors.grey.shade600,
                fontSize: 14,
                fontWeight: FontWeight.w700),
          ),
        ],
      ),
    );
  }
}

and this is FeedScreen file that works normally:
class _FeedScreenState extends State<FeedScreen> {

  int index = 0;
  var random = Random();
  List<Color> myColors = [
    Colors.white,
    Colors.grey.shade900,
    Colors.green,
    Colors.cyan,
    Colors.pink,
  ];

  void changeColorsIndex() {
    setState(() {
      index = random.nextInt(4);
    });
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      body: ListView(
        children: [
          Container(
            width: size.width,
            height: size.height,
            color: Colors.black,
            child: Column(
              // this column is start of everything and container below is filter part just below app bar
              children: [
                Example(),
                InkWell(
                  onTap: changeColorsIndex,
                  child: Container(
                    width: size.width,
                    height: 450,
                    color: myColors[index],
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: const [
                        Padding(
                          padding: EdgeInsets.only(top: 15, left: 15),
                          child: Text(
                            'Air Force 1 x Premium Goods',
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 17,
                                color: Colors.white),
                          ),
                        ),
                        Gap(5),
                        Padding(
                          padding: EdgeInsets.only(left: 15),
                          child: Text(
                            'The Sophia',
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 30,
                                color: Colors.white),
                          ),
                        ),
                        Gap(50),
                        Image(
                          image: AssetImage('assets/AF1xPGmain.png'),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

i tried with GestureDecoration also even tho its same thing but it just doesnt work

A: you have written different onTap method in the filter file
change
      onTap: () {
          setState(() {
             changeColorsIndex();
           });
         },

To
       onTap: changeColorsIndex,

In filter file wrap your dialog with stateful builder as shown here

A: you can add a StatefulBuilder Widget to make your showDialog able to use setState
try it and let me please know if it works
class _ExampleState extends State<Example> {
  int _selectedindex = 0;

  void _onItemTapped(int index) {
    setState(() {
      _selectedindex = index;
    });
  }

  int index = 0;
  var random = Random();
  List<Color> myColors = [
    Colors.white,
    Colors.grey.shade900,
    Colors.green,
    Colors.cyan,
    Colors.pink,
  ];

  void changeColorsIndex() {
    setState(() {
      index = random.nextInt(4);
    });
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Container(
      width: size.width,
      height: 40,
      color: Color.fromARGB(255, 28, 28, 28),
      child: Row(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 1.5),
            child: IconButton(
              onPressed: (() {
                setState(
                  () {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return StatefulBuilder(builder: (context, setState) {
                          return SingleChildScrollView(
                            scrollDirection: Axis.vertical,
                            child: Container(
                              width: size.width,
                              height: size.height,
                              child: Scaffold(
                                backgroundColor: Colors.black,
                                body: SingleChildScrollView(
                                  scrollDirection: Axis.vertical,
                                  child: Padding(
                                    padding: const EdgeInsets.only(bottom: 30),
                                    child: Column(
                                      children: [
                                        Center(
                                          child: Padding(
                                            padding:
                                                const EdgeInsets.only(top: 5),
                                            child: IconButton(
                                              onPressed: () {
                                                Navigator.pop(
                                                  context,
                                                  MaterialPageRoute(
                                                    builder: (context) =>
                                                        TopTab(),
                                                  ),
                                                );
                                              },
                                              icon: const Icon(
                                                  Icons.arrow_drop_down),
                                              iconSize: 45,
                                              color: Colors.white,
                                            ),
                                          ),
                                        ),
                                        const Gap(15),
                                        Container(
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              InkWell(
                                                onTap: () {
                                                  setState(() {
                                                    changeColorsIndex();
                                                  });
                                                },
                                                child: Container(
                                                  width: 199,
                                                  height: 50,
                                                  color: myColors[index],
                                                  child: const Center(
                                                    child: Text(
                                                      'Men\'s',
                                                      style: TextStyle(
                                                          fontSize: 14,
                                                          fontWeight:
                                                              FontWeight.w600,
                                                          color: Colors.white),
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          );
                        });
                      },
                    );
                  },
                );
              }),
              icon: Icon(Ionicons.options_outline),
              iconSize: 20,
              color: Colors.white,
            ),
          ),
          const Gap(6),
          Text(
            'Filter by size',
            style: TextStyle(
                color: Colors.grey.shade600,
                fontSize: 14,
                fontWeight: FontWeight.w700),
          ),
        ],
      ),
    );
  }
}


text:
Q: Django Cannot auto focus on this form but can on forms I have a login, register and password reset pages both login and register pages auto focus on the username field however on my password reset page auto focus is not working. I have tried widget_tweaks within my template but to no avail like so:
{{ fieldValues.email|attr:"autofocus" }} and {{ form.email|attr:"autofocus" }}

I just cannot get my head around why auto focus works on my other forms but not on password reset. My code is as follows:
View
class RequestPasswordResetEmail(View):
    @method_decorator(check_recaptcha_form)
    def get(self, request):
        return render(request, 'password/reset-password.html')

    @method_decorator(check_recaptcha_form)
    def post(self, request):

        email = request.POST['email']

        context = {
            'values': request.POST
        }

        current_site = get_current_site(request)

        user = User.objects.filter(email=email)
        user_by_email = User.objects.filter(email=email).first()

        if not user.exists():
            messages.error(request, 'Please supply a valid email')
            return render(request, 'password/reset-password.html', context)

        if user.exists() and request.recaptcha_is_valid:
            uid = urlsafe_base64_encode(force_bytes(user_by_email.pk))
            token = PasswordResetTokenGenerator().make_token(user_by_email)

            email_subject = 'WFI Workflow System - Password Reset'
            email_body = 'password/password_reset_email.html'
            to_email = [user_by_email.email]

            send_email(user, request, email_subject, email_body, uid, token, to_email)

            messages.success(
                request, mark_safe(
                    'We've emailed you instructions for setting your password, if an account exists with the email you entered. You should receive them shortly.'
                    '
 If you don't receive an email, please make sure you've entered the address you registered with, and check your spam folder.
'))

        return render(request, 'password/reset-password.html')

Template
{% extends 'base.html' %}

{% block title %}Password Reset{% endblock %}

{% block content %}

Password Reset

    Forgotten your password? Enter your email address below, and we'll email instructions for setting a new one.

        <form action="{% url 'request-password' %}" method="POST">
            {% csrf_token %}

                    <input type="email" name="email" placeholder="Email" class="form-control"
                           value="{{ fieldValues.email }}"/>

                {% include 'recaptcha.html' %}

                <input class="btn login_btn" type="submit" value="Submit">

        </form>

    {% include 'messages.html' %}

            Already have an account? Login

            Don't have an account? Sign Up

{% endblock content %}

I even tried the following javascript but again did nothing:

A: Just add autofocus attribute to your input field:
<input type="email" name="email" placeholder="Email" class="form-control" value="{{ fieldValues.email }}" autofocus>


text:
Q: Downloading a file with webforms and EPPlus I am implementing a small export feature for a legacy webforms application.
My export code right now is only headers (just testing the that I can successfully create a file):
public MemoryStream Export()
{
    var result = new MemoryStream();
    using (var p = new ExcelPackage())
    {
        var ws = p.Workbook.Worksheets.Add("Contacts");
        var col = 1;
        ws.Cells[1, col++].Value = "ID";
        ws.Cells[1, col++].Value = "First Name";
        ws.Cells[1, col++].Value = "Last Name";
        ws.Cells[1, col++].Value = "Email";
        ws.Cells[1, col++].Value = "Phone";
        ws.Cells[1, col++].Value = "Address";
        p.SaveAs(result);
    }

    return result;
}

Here is the button handler:
var ms = Export();
ms.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", $"attachment;filename=Contacts_{DateTime.Now:yyyyMMddhhmmss}.xlsx");
HttpContext.Current.Response.StatusCode = 200;
// HttpContext.Current.Response.End();

So one issue is that all the examples I find have the HttpContext.Current.Response.End() call at the end of the method, but if I do this, it throws an exception.  Commenting this line out seems to work fine but that leads me to my main problem: when the file is saved and then opened in excel, Excel complains there is a problem with the file.  My impression is that EPPlus makes well formed files, so what am I missing?
Update #1
I tried directly saving the EPPlus package to disk.  That seems to work without issue.  So the problem lies somewhere between writing the package to the memorystream and returning the result.

A: Here is the code that is working for me
var ms = Export();
Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", $"attachment;filename=Contacts_{DateTime.Now:yyyyMMddhhmmss}.xlsx");
Response.AddHeader("Content-Length", ms.Length.ToString());
Response.BinaryWrite(ms.ToArray());
Response.End();


text:
Q: Error using hoistNonReactStatics, withApollo, withContext and React-Navigation I am trying to run a graphql query (and store the response in my context). But, when I do that, my react-navigation header is not rendering. I researched on the internet and understand we can use hoistNonReactStatics to preserve the statics.
I am unable to get the code to work. What I have done so far is given below, I am unable to run my graphql query.
How should I structure my code in order for it to work? Thanks :)
class HomeScreen extends React.Component {
render() {
   return ...
}

hoistNonReactStatics(
  HomeScreen,
  compose(
    withContext,
    withApollo
  )(HomeScreen)
);

export default HomeScreen;


text:
Q: Two way communication between one master and multiple nodes I have an architecture like this:

Master - It contains an RF communication chip. All nodes rely on Master to receive and send data to a central unit.
Node - It has some basic GPIO functionality. There can be 4-5 different types of nodes, each requiring a different GPIO count. For the sake of design simplicity, I am planning to throw a cheap microcontroller on each node and handle all GPIO locally. That way I just need a pre-defined control data packet from the master to do any task. Similarly, the node will send a pre-defined packet which the master will understand. The packet definition will contain the node type.
Nodes can change in number and preferably should be hot-swappable. Communication works like this:
Two nodes do not communicate directly.
Master can have a data packet which it wants to send to any particular node.
Any node can have a data packet which it wants to send to the master.
Max distance between a node and master will be less than 50 cm.
After some thought, this is the plan I came up with:
Make all nodes communicate over i2c. 16 nodes per master seems to be a good number so I can put a 4 bit DIP switch to set the i2c address of each node. Basically I will be doing a digital read on 4 gpio and setting the address accordingly.
This will be perfect when master wants to read or write data to the nodes.
For the time when node wants to send data, I need to have an additional GPIO per node which alerts the master that some data is present. Alternatively, I can keep reading all nodes in the loop and keep checking if some data is available.
Is there a better solution to this problem?

A: An alternative to I2C, you could consider CANbus for this solution.  It is arguably more complex, but slaves would be able to communicate back to the master on the same bus without needing a GPIO to indicate they have data available.  Also, collision detection is built into the design of the physical layer and protocol.
CAN controllers are available relatively cheap, although you need a transceiver for each node.
Other common multidrop buses you could consider:
RS-485: Simple to use, but you would be responsible for all the addressing.  I2C at least builds that in.
SPI: Useful if you have the I/O to spare for a slave select line for each node.  Based on your description above, this would probably not be the best route.

A: Your polling solution is probably the most classic.
One other solution is to do a broadcast poll.
Basically send a message that everyone hears which causes them to send a pulse a set delay after receiving the poll if they have data. The delay length being set by the devices address.
The master can then monitor the return signal and decode who has data to send and ask it directly.
Another technique is to build in a short delay between master transmission and slave acknowledge. Then use that window to allow slaves to squawk a single pulse that acts like an interrupt to the master. You would then need to poll them.


text:
Q: AJAX request not sending to URL I tried to send an ajax request to a URL, expecting to get a json response, however, the request doesn't seem to be sending to /login. Instead, it remains on the current url and add the formData params to it. It is also not sensing "POST". What's wrong:
$(document).ready(function() {
  $("#login").click(function() {
    var formData = {username: username, password: password}
    $.ajax({
      type: "POST",
      url: "/login",
      dataType: 'json',
      data: formData,
      success: function (data) {
        var json_x = data;
        alert(json_x['data']);
      }
    });
  });
});

html:
<form>
  <input type="text" name="username">Username</input>
  <input type="password" name="password">Password</input>
  <button type="button" id="login">Login</button>
</form>

A: Try:
$(document).ready(function() {
  $("#login").click(function() {
    // you forgot to get value of username and password
    var formData = {username: $('#username').val(), password: $('#password').val()};
    $.ajax({
      type: "POST",
      url: "/login",
      dataType: 'json',
      data: formData,
      success: function (data) {
        console.log(data);
      }
    });
  });
});

<form>
  <input type="text" name="username" id="username">Username</input>
  <input type="password" name="password" id="password">Password</input>
  <button type="button" id="login">Login</button>
</form>

A: UPDATE3:
See the new declaration of formData.
var formData = {
    username: $("input[name='username']").val(),
    password: $("input[name='password']").val()
};

A: Use this code
alert(json_x.data);
instead of
alert(json_x['data']);
also change this line
var formData = {username: username, password: password}
into
var formData = $(this).parent().serialize();

A: The correct answer is to use $("button") instead of $("#login").
I've solved it.


text:
Q: C# Making program wait until browser finish loading webpage How do i make my program to wait until webpage finish loading before executing next statement. I tried Process::WaitForInputIdle(); but it doesn't wait.
ProcessStartInfo pInfo = new ProcessStartInfo("firefox.exe");

pInfo.Arguments = "http://example.com";

Process p  = Process.Start(pInfo);

p.WaitForInputIdle();

pInfo.Arguments = "http://example.net";

p = Process.Start(pInfo);

p.WaitForInputIdle();

A: You can't. The problem here is that Firefox does not communicate back when the web page has loaded. You will for example see issues when Firefox wants to update itself before it opens the web page. How is it going to communicate back when the page is loaded? In between, the entire firefox.exe executable has been replaced, and the connection with your Process has been long lost.
The WaitForInputIdle does a very specific job, and this is not what you expect. Windows works through a message pump. When you e.g. move the mouse over a window, a message is send to that window. WaitForIdleInput returns when the application has processed the first message it has received, so when Windows knows it is 'responsive'.


text:
Q: Filling gaps between polygons using QGIS Here are my polygons of town blocks.

The colored towns are considered as areas where they have the same post code.
What I eventually want is to make seamless polygons where there are no gaps between polygons (please see the screenshot below)

What functions should I use to complete my mission?

A: @Pil Kwon, since you have the same "post-code", therefore in QGIS I can suggest using a "Convex Hull":

Vector > Geoprocessing Tools > Convex Hull

Hint: Create Convex Hulls based on a field.

A: Wouldn't you want a concave hull? A convex hull will give you a large amount of area that isn't part of the block. For example, a convex hull would fill in that big gap in the "hook" park of block 1.

A: You can do a morphological closing (buffering outwards and then inwards by the same amount) to close the gaps. It will cause slight distortions to inner corners, though, so your final areas will be changed.


text:
Q: Temperature loss of a moving object I would like to know how to calculate the temperature change of a moving object. For example if I throw a ball that is warmer than the surrounding air, how much would it lose form it's temperature in every second? I searched for two days now, but I have only partial solutions :(. I would need a formula that takes in account the followings:

*

*The material of the ball (Iron, heat conductivity?)

*Area of the ball

*Speed of the ball (true airspeed)

*Material of the surrounding material (air, heat conductivity?)

*And ofc temperature of the ball and the surrounding material.

*anything else I forgot and neccessary :):)

It dosen't need to take in account friction generated heat and other things, I only need the temperature loss :)

A: If the speed of ball is large most of the time, then speed of air flow across the ball (as seen from reference frame attached to the ball) is large most of the time, which means that heat transfer from ball to air is predominantly due to forced convection rather than free convection. With this assumption, you may use forced convection relations for heat transfer, which depends on air-speed across the ball, surface temperature of the ball, and thermodynamic properties of air. However these relations are empirical and are usually for constant air-speed, while in your case air-speed is changing with time. You may assume some average value of heat transfer coefficient to get an estimate. If thermal conductivity of the ball is high enough that entire ball is nearly at uniform temperature at all times, then you won't have to solve for temperature field inside the ball (to find its surface temperature, which is what is required ultimately). Regarding this last point read up lumped-system analysis and Biot number.

A: If you can take that object's temperature loss in terms of radiation just as a black-body, you can have your answer in wikipedia easily.
In equilibrium, for each frequency the total intensity of radiation that is emitted and reflected from a body (that is, the net amount of radiation leaving its surface, called the spectral radiance) is determined solely by the equilibrium temperature, and does not depend upon the shape, material or structure of the body.[17] For a black body (a perfect absorber) there is no reflected radiation, and so the spectral radiance is due entirely to emission.  Here, you take total output by ball minus total input by surrounding.
(so the temperatures of ball and environment are important with the surface area of ball)
https://en.wikipedia.org/wiki/Black-body_radiation

Ofcourse friction is important that how fast that object is relevant. That was already asked and answered below link.
(area of ball, material of ball, material of surrounding, speed of ball, structure of ball(flat surface or noisy surface))
After what speed air friction starts to heat up an object?

I want to add some more parameters, electric charge of object and magnetic field of the surrounding. When you move a charged object in a magnetic field that is not parallel to velocity of object, object is under a force. If it is fast enough and is in a constrained orbit, it will get hotter because electric charge on it will get affected and move to one side of object thus making the object to have a voltage-potential between two poles. When charges move to these poles, it has conduct a curent that heated it. If you change direction of flight of obejct, opposite polarisation happens and heats more. So even discontinuity of velocity is important if there are parameters such as charge and magnetic field.

Lets take bigger objects like planets. When two objects move close, they strain each other with gravity and get hotter. Especially the closermost parts.

Lets take smaller object, they are so small that even time is a parameter. You dont even need to move that. There is always a possibility of a molecule to change its state, angle of bond, direction of bond, polarisation (like inversion of NH3) which makes them resonate with a power source which could be even the infrared-band . If you take a small group of these, their natural-state-changing becomes more important thanks as Quantum-Physics shows.
Again for small objects, if those are fast enough(coming near speed of light), their mass increase and make the time go slower so the expected temperature would be smaller or I am wrong.

As Nathaniel reminds, heat change with conduction become more important as the heat transfer constant of surfece between ball and surrounding material increases(fluid density can be important too), surface area of ball is also important. When fluid passes faster, it takes heat faster. Pressure of surrounding fluid on the surface can be important too(maybe multiplies the transfer constant)

After speed of sound, some phasechanging can occur near surface and that could affect heat conduction too.