text:
Q: How do I represent a world and dynamic objects in a C++ console game? I'd appreciate some help with a small project of mine. It's supposed to be a console game, using elements from roguelikes, RPGs, sandboxes and survival games.
I have attempted about three times so far to get a working architecture. Each time, I hit problems I couldn't solve without hacking my way around it...
I already looked at numerous blogs and tutorials for this, but none of them fit my purpose exactly.
1) http://trystans.blogspot.co.at/2011/08/roguelike-tutorial-01-java-eclipse.html
2) http://www.kathekonta.com/rlguide/index.html
I have already followed Trystan's blog - who uses Java - and recreated his design in Java and AS3.
However, I wasn't quite content with the way he linked the classes together. Commands like World.dig() - To me, it makes more sense to call Player.dig() - or the map representation as a 3d(!) array made me believe that there must be a better way to do this.
The second link I posted is coded in C++, however, there is only one central map. My goal is to be able to have multiple maps, which I can enter with characters, etc.
I will post the code of my newest attempt below. It doesn't feature any movement or interaction at all, since I want to get the design right from the beginning, not failing after hours spent into the project (which I already encountered way too often).
main.cpp:
# include <iostream>

# include "World.h"
# include "Entity.h"

using namespace std;

int main(){

    int testFloor[] = {
        0, 0, 0, 0, 0,
        0, 1, 1, 1, 0,
        0, 1, 0, 0, 0,
        0, 1, 1, 1, 0,
        0, 0, 0, 0, 0
    };

    World world(testFloor, 5, 5);

    //Creating an entity at the top left corner
    Entity nine(9, 0);
    world.addEntity(nine);

    //Draw the entire world
    world.draw(0,0,5,5);

    system("PAUSE");
    return 0;
}

World.h:
# ifndef WORLD_H
# define WORLD_H

# include <vector>

# include "Entity.h"

using namespace std;

class World {
private:
    int* _floor;
    int _width;
    int _height;

    vector<Entity> _entities;

public:
    World(int* floor, int width, int height) :
        _floor(floor), _width(width), _height(height){}

    /*Pushes an Entity to the _entities-vector*/
    void addEntity(Entity e){
        _entities.push_back(e);
    }

    /*Displays the floor at a position, or the glyph of an entity, if applicable*/
    //This "glyph" is just a number here, similar to the contents of the _floor array
    int glyph(int ID){
        int out = _floor[ID];
        for(Entity e : _entities){
            if(e.pos() == ID){
                out = e.glyph();
                break;
            }
        }
        return out;
    }

    //Prints the World as seen from "above" - entities will cover the floor
    void draw(int left, int top, int width, int height){
        system("cls");

        int ID;

        for(int y = 0; y < height; y++){
            for(int x = 0; x < width; x++){
                ID = (x+left)+(y+top)*width;
                cout << glyph(ID);
            }
            cout << endl;
        }
    }
};

# endif

Entity.h:
# ifndef ENTITY_H
# define ENTITY_H

class Entity{
private:
    int _glyph; //Will be a char later, integer for now, since the glyph function returns
                //an int for simplicity
    int _pos;

public:
    Entity(int glyph, int pos) : _glyph(glyph), _pos(pos) {}

    int glyph(){return _glyph;}
    int pos(){return _pos;}
};

# endif

The code compiles and works. A new Entity is spawned at the top left, represented by a "9", the map is drawn as expected and all... but I'm seeing problems even right now.
1) As I create a new Entity, I need to give it the ID (Worldposition) to spawn at - however it has no clue about its actual position in the world.
2) Whenever the Entity would move, it would need a reference to the map it is on, in order to know, where it's going.
To solve these problems, it would probably be beneficial to store a reference to the world inside the Entity.
However, I want to be able to perform a command like World.update(), which automatically updates all the Entities, giving them the opportunity to move, attack, open doors, build barricades, ... The world would then iterate through all the entities, calling their respective update functions.
I found out from a previous attempt, that it causes problems to store a reference to a world in the entity class, and storing an array/vector of entities inside the world class.
So here are my actual questions:
- How can I design my classes in order to have a meaningful relationship between Entities and the World(s)? - Where do I put my references - directly into function calls, maybe (that's going to cost performance, I guess)?
Edit: Please note, that I'm not expecting code samples, I rather want to write the code myself. What would help me most would be hints such as which class should hold which variables.
Thank you all for your time!

A: 1) If I understand your question right, in order to find your 2d position on the map from your 1d coordinate, you can use something like the following:
Point Entity::pos2D(World& world) const {
    int y = _pos / world.width();
    int x = _pos % world.width();
    return Point(x, y);
}

Assuming you have a Point class to aggregate x and y.  Also adding width() and height() accessor functions to the World object here.
You may fnd, however that it is better to store a 2d position in the first place - calculating the 1d position from it would involve a multiply instead of a divide.
2) You could pass in a reference to the world in the various entity manipulation member functions.  e.g.
Entity::update(World& world) {
   // do some stuff
}
Entity::move(World& world) {
   // do some stuff
}

This will save storing a pointer to the world in every entity.  This will reduce memory usage and also give better locality of reference.  i.e. if you have many entities then it will probably improve performance by having more complete entities in the processor cache, depending upon how they are stored.  I would not be worrying about performance at this stage too much though.


text:
Q: Magento Sales Rules Dropdown Missing after upgrade Similar to: Magento Upgrade Issue 1.5.1.0 to 1.9.2.1
I have the following (encountering as I'm upgrading from 1.7.0.2 to 1.8.1.0 in a dev site - also had it going straight to 1.9)
a:5:{i:0;s:96:"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'rule.calculate_subtotal' in 'field list'";i:1;s:4835:"    0 /domains/[hidden]/dev/lib/Varien/Db/Statement/Pdo/Mysql.php(110):         Zend_Db_Statement_Pdo->_execute(Array)
1 /domains/[hidden]/dev/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
2 /domains/[hidden]/dev/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
3 /domains/[hidden]/dev/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT `main_ta...', Array)
4 /domains/[hidden]/dev/lib/Varien/Db/Adapter/Pdo/Mysql.php(428): Zend_Db_Adapter_Pdo_Abstract->query('SELECT `main_ta...', Array)
5 /domains/[hidden]/dev/lib/Zend/Db/Adapter/Abstract.php(734): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select), Array)
6 /domains/[hidden]/dev/app/code/core/Mage/Tax/Model/Resource/Calculation.php(358): Zend_Db_Adapter_Abstract->fetchAll(Object(Varien_Db_Select))
7 /domains/[hidden]/dev/app/code/core/Mage/Tax/Model/Resource/Calculation.php(99): Mage_Tax_Model_Resource_Calculation->_getRates(Object(Varien_Object))
8 /domains/[hidden]/dev/app/code/core/Mage/Tax/Model/Calculation.php(264): Mage_Tax_Model_Resource_Calculation->getRateInfo(Object(Varien_Object))
9 /domains/[hidden]/dev/app/code/core/Mage/Tax/Model/Calculation.php(509): Mage_Tax_Model_Calculation->getRate(Object(Varien_Object))
10 /domains/[hidden]/dev/app/code/core/Mage/Tax/Model/Calculation.php(523): Mage_Tax_Model_Calculation->_getRates(Object(Varien_Object), 'product_class_i...', 'PRODUCT')
11 /domains/[hidden]/dev/app/code/core/Mage/Tax/Helper/Data.php(466): Mage_Tax_Model_Calculation->getRatesForAllProductTaxClasses(Object(Varien_Object))
12 /domains/[hidden]/dev/app/code/core/Mage/Tax/Helper/Data.php(448): Mage_Tax_Helper_Data->_getAllRatesByProductClass(Object(Mage_Core_Model_Store))
13 /domains/[hidden]/dev/app/design/adminhtml/default/default/template/catalog/product/js.phtml(45): Mage_Tax_Helper_Data->getAllRatesByProductClass(Object(Mage_Core_Model_Store))
14 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Template.php(241): include('/domains/hidden…')
15 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Template.php(272): Mage_Core_Block_Template->fetchView('adminhtml/defau...')
16 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Template.php(286): Mage_Core_Block_Template->renderView()
17 /domains/[hidden]/dev/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template->_toHtml()
18 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Abstract.php(919): Mage_Adminhtml_Block_Template->_toHtml()
19 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Text/List.php(43): Mage_Core_Block_Abstract->toHtml()
20 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Abstract.php(919): Mage_Core_Block_Text_List->_toHtml()
21 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Abstract.php(637): Mage_Core_Block_Abstract->toHtml()
22 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Abstract.php(581): Mage_Core_Block_Abstract->_getChildHtml('js', true)
23 /domains/[hidden]/dev/app/design/adminhtml/default/default/template/page.phtml(82): Mage_Core_Block_Abstract->getChildHtml('js')
24 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Template.php(241): include('/domains/a8uk.c...')
25 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Template.php(272): Mage_Core_Block_Template->fetchView('adminhtml/defau...')
26 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Template.php(286): Mage_Core_Block_Template->renderView()
27 /domains/[hidden]/dev/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template->_toHtml()
28 /domains/[hidden]/dev/app/code/core/Mage/Core/Block/Abstract.php(919): Mage_Adminhtml_Block_Template->_toHtml()
29 /domains/[hidden]/dev/app/code/core/Mage/Core/Model/Layout.php(555): Mage_Core_Block_Abstract->toHtml()
30 /domains/[hidden]/dev/app/code/core/Mage/Core/Controller/Varien/Action.php(390): Mage_Core_Model_Layout->getOutput()
31 /domains/[hidden]/dev/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php(269): Mage_Core_Controller_Varien_Action->renderLayout()
32 /domains/[hidden]/dev/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_Catalog_ProductController->editAction()
33 /domains/[hidden]/dev/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('edit')
34 /domains/[hidden]/dev/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
35 /domains/[hidden]/dev/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
36 /domains/[hidden]/dev/app/Mage.php(684): Mage_Core_Model_App->run(Array)
37 /domains/[hidden]/dev/index.php(87): Mage::run('english', 'website')
38 {main}";s:3:"url";s:85:"/index.php/console/catalog_product/edit/id/4965/key/4d7a4458accfaccf439e4b946771a857/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:5:"admin";}

I believe this is the same situation and tried the attached fix, any other ideas?
Regards,
Dan

A: After exhausting most options, I found a module from a theme that caused this.
It wasn't apparent as the module xml was combined with other modules named "All.xml", I disable the one relating to Tax and the Tax dropdown reappeared.
So hope this helps someone else

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does Desura accept Paypal payments? I'm reading through the EULA of Desura to better understand the system and the deal it offers, and there's an entire section dedicated to credit card information and chargebacks; now I'm pretty sure this is also repeated in the Steam EULA, but it did make me wonder - does Desura accept PayPal payments?
Otherwise, it's pretty much a deal breaker for me.

A: Yes; they currently accept PayPal, Visa and Mastercard. These options are displayed to you at the checkout screen.


text:
Q: Swift 4 present view controller black screen I'm presenting another view controller like this:
func goToScreen(id : String) {
    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let newViewController = storyBoard.instantiateViewController(withIdentifier: id)
    self.present(newViewController, animated: true, completion: nil)
}

The problem is, there is a cc. 1 second delay between the appearance of the new viewcontroller, and in the meantime the app shows an all black screen. Why is that? It looks really ugly

A: change status of animation to false while move to next view controller this will remove the delay. Delay happening only because of animation: true.
Use below code to solve your issue
self.present(newViewController, animated: false, completion: nil)

Hope this will help you

A: I was inheriting from UITabBarController instead of UIViewController from the screen I was pushing to.


text:
Q: How to capture any key in X? I am building an application for which I need to periodically get information about users keyboard. It is going to be user idle detection application. I have a fairly simple solution to periodically check if the mouse has been moved. But I can't figure any reasonable non root way to detect if the keyboard has been pressed.
I was thinking about registering a hook every timer timeout and on any key press to unregister it. So if there is no key press for a long time then my program will know if the user is idle.
Anyway, I couldn't find any global hooks for any key, including modifiers. Is there an easy way to do this? Or would someone have a better way to detect keyboard idleness?
Thanks

A: After a lot of searching I found this:
bool kbdActivity(Display* display)  // checks for key presses
{
    XQueryKeymap(display, keymap);  // asks x server for current keymap
    for (int i=0; i<32; i++)        // for 0 to 32 (keymap size)
    {
        if (prevKeymap[i] != keymap[i])   // if previous keymap does not
        {                               // equal current keymap
            XQueryKeymap(display, prevKeymap);  // ask for new keymap
            return true;                // exit with true
        }
    }
    return false;                   // no change == no activity
}

When I call it every 100-300ms it detects any pressed key anywhere in X.

A: Have a look at xautolock source, which does exactly what you need, for both keyboard and mouse.
http://www.ibiblio.org/pub/Linux/X11/screensavers/xautolock-2.2.tgz

A: I have some code that can track keyboard activity for you.
#include "stdafx.h"

#include <stdio.h>

#include "windows.h"

#include "iostream"
using namespace std;

int main(void)
 {

HANDLE hStdInput, hStdOutput, hEvent;

INPUT_RECORD ir[128];

DWORD nRead;

COORD xy;
UINT i;

hStdInput = GetStdHandle(STD_INPUT_HANDLE);
hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
FlushConsoleInputBuffer(hStdInput);
hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
HANDLE handles[2] = { hEvent, hStdInput };

while (WaitForMultipleObjects(2, handles, FALSE, INFINITE))
{

    ReadConsoleInput(hStdInput, ir, 128, &nRead);
    for (i = 0; i<nRead; i++)
    {
        switch (ir[i].EventType)
        {
        case KEY_EVENT:
            if (ir[i].Event.KeyEvent.wVirtualKeyCode == VK_ESCAPE)
                SetEvent(hEvent);
            else
            {
                xy.X = 0; xy.Y = 0;
                SetConsoleCursorPosition(hStdOutput, xy);
                printf
                    (
                    "AsciiCode = %d: symbol = %c\n",
                    ir[i].Event.KeyEvent.uChar.AsciiChar,
                    ir[i].Event.KeyEvent.uChar.AsciiChar
                    );
            // note that some keys have a AsciiCode of 0 such as shift, ctrl, and the
            // rest you can try out yourself

            }
            break;

        }
    }
};

return 0;
}

In this code it tracks keyboard activity and for now it shows the key you pressed and its AsciiCode, also for shift,ctrl, etc the key name won't be shown.


text:
Q: M2: How to get Customer Cart Rules in My Account page I want to filter cart rules list in my account page.
I've list cart rules in My Account page "Dashboard". But I want to filter cart rules list by condition.

I've configure the conditions in cart rules by date of birth.  I just want to show the rules if the customer date of birth is same with my conditions.
I got the Data from \Magento\Customer\Block\Account\Dashboard\Info. but I dont know how to filter cart rules list.
$datax = $helper->getSalesRule();
echo '<pre>';
print_r($datax->getData());
echo '</pre>';

and the result
[
    conditions_serialized
]=>{
   "type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Combine",
   "attribute":null,
   "operator":null,
   "value":"1",
   "is_value_processed":null,
   "aggregator":"all",
   "conditions":[
   {
"type":"Magento\\CustomerSegment\\Model\\Segment\\Condition\\Segment",
     "attribute":false,
     "operator":"==",
     "value":"138,110",
     "is_value_processed":false
   }
 ]
}

A: First, you have to get the collection of all rules, then validate those by using validate() function
$rules = $this->ruleFactory->create()->getCollection()

foreach ($rules as $rule) {
            $rule->afterLoad();
            if ($quote->isVirtual()) {
                $address = $quote->getBillingAddress();
            } else {
                $address = $quote->getShippingAddress();
            }
            foreach ($address->getAllItems() as $item) {// total_qty - allowed only in total collection process
                $address->setTotalQty($address->getTotalQty() + $item->getQty());
            }
            if ($rule->validate($address)) {
                $subtotal = 0;
                foreach ($quote->getItemsCollection() as $item) {
                    if ($item->getParentItemId()) {
                        continue;
                    }
                    if ($rule->getConditions()->validate($item)) {
                        $subtotal += $item->getBasePrice() * $item->getQty();
                    }
                }
                if ($subtotal > 0) {
                    return $rule;
                }
            }
        }


text:
Q: Boolean always returns false when called from other class Ok, I am a bit of a noob at Objective C and programing in general, but i'm trying to learn, so i would appreviate a bit of help.
I am making a game with several classes. On the main menu screen I have 2 buttons, easy and hard, and a start game button. At the moment, I have declared a public boolean called "level" in the class MainView, then in the hard button action I set level to true, in the easy button action I set it to false. In a different class I have imported MainView.h and in a method called "numberOfCards" I have:
MainView *view = [[MainView alloc]init];

if(view->level){
   cards = 10;

}

else {
   cards = 20;
}

But level always returns false, I'm guessing that when I initialise my MainView, it resets the variable?
Am I tackling this problem in the wrong way?
Any help would be great.
Heres some more code:
MainView.h
@interface MainView : UIViewController <HostViewControllerDelegate, JoinViewControllerDelegate, GameViewControllerDelegate>
{

@public
BOOL level;

}

@end

mainView.m
- (IBAction)easyButton:(id)sender
{

level = NO;
}

- (IBAction)hardButton:(id)sender
{
level = YES;
}

A: You say, "I'm guessing that when I initialise my MainView, it resets the variable?"
Effectively, yes.  More specifically, it creates a new object that has its own level variable, and the default value of an uninitialized BOOL is NO.
You need to pass a reference to the existing MainView object into the object that needs to request the level information.  Exactly how to do that depends on your program structure and how the two classes are related to each other.


text:
Q: Laravel Telescope adding primary key (id) to telescope_entries_tags and telescope_monitoring tables Good day,
I'm currently facing a problem where the database that I'm supposed to deploy my Laravel app has a restriction on primary keys (every tables must have a primary key).
Refer to below error:
SQLException: Percona-XtraDB-Cluster prohibits use of DML command on a table (mydb.sample_table) without an explicit primary key with pxc_strict_mode = ENFORCING or MASTER
Referring to Laravel Telescope migration file,
https://github.com/laravel/telescope/blob/4.x/database/migrations/2018_08_08_100000_create_telescope_entries_table.php
Both telescope_entries_tags and telescope_monitoring have no primary key.
Question: My question is whether if I can add a primary key ($table->id()) to the migrations, without causing anything to break?
I'm unable to test it out as it is only happening on the production.
I have posted the exact question on Laravel Telescope Discussions ,
https://github.com/laravel/framework/discussions/41818
Any help is much appreciated.


text:
Q: How can I diff two files while ignoring diffs I've already marked as known I'm trying to maintain two parallel versions of the same stuff. Occasionally, I spend some time synching them to each other.
One way I've found to do this is to diff between each pair of files and look at the differences.
The problem is that there are a bunch of differences that I know about. They will continue to be different. I'm looking for the other stuff.
Is there a diff tool out there that will allow me to mark particular diffs are known/ignore?
I'm in the linux env using SVN. I'm fine with using windows based utilities.

A: In Beyond Compare you can select a block of differences and mark it as ignored.  It will switch the coloring and filtering so it's displayed as a match instead, though it doesn't persist across comparisons.  It supports both Linux and Windows.


text:
Q: Git push sub-folders of a commit separately I have a local git repository which contains a root folder and some sub-folders. I know that I can push my project to Github using below commands:
git init
git add .
git commit -m "initialization"
git remote add origin "my github repo"
git push origin master

but because the volume of my repository is about 30 GB (it is a data set), my laptop hangs when compressing data, so I need to push each sub-folder separately to reduce the data I push. How can I push the sub-folders of a commit separately?

A: Since the process hangs, you can reset everything, by removing the .git/ folder created by git init.
Then you can create your repo again, add your remote origin, and this time:
git add folder1
git commit -m "Add folder1"
git push -u origin master

Then repeat for folder2:
git add folder2
git commit -m "Add folder2"
git push

But do consider first if you can add to your .gitignore files/binaries that can be regenerated from sources, or anything which would reduce the size of the Git repo.
Depending on your remote repo hosting service (like github.com for instance), you can have limitation to the size of a commit or of a full repo.
GitHub (again, for instance) documents that in "What is my disk quota?".


text:
Q: Different return value of 'for' loop in JavaScript I am new to JavaScript. Now I am facing an issue in a for loop.
The statement I wrote:
var name = ["John", "Lee", "Alex"];
for( ; x < name.length -1; x++){
    document.write(name[x]);}

I should get the result John, Lee, but I won't.

A: You're just missing the declaration for the var i in your loop syntax right where I put empty quotes:
var name = ["John", "Lee", "Alex" ];
    for(" ";x < name.length -1;x++ ){
        document.write(name[x]);
    }

A: Try the following code:
var name = ["John", "Lee", "Alex"];
for (var x = 0; x < name.length - 1; x++) {
  document.write(name[x]);
}

Where the for loop declares the variable x with initial value 0

A: You need to declare the variable x, so you can use it:
 var name = ["John", "Lee", "Alex" ];
    for(var x= 0;x < name.length -1;x++ ){
        document.write(name[x]);
   }

A: Undeclared variable x and the most important: you're using the window attribute name, so that variable will be cast to String.

*

*Declare the variable x.

*Change the identifier of that array to names for example.

var names = ["John", "Lee", "Alex"];
for (var x = 0; x < names.length - 1; x++) {
  document.write(names[x]);
}


text:
Q: Downloaded theme not functional I have downloaded a theme. The folder contains app, js, media and skin folders.
I have disabled and flushed all the caches. Then I have copied the theme's folders to Magento root (located in local virtual host 'magento.local') overwriting the existing folders. That caused the site to stop working.
Later, I started to manually copy the files from the theme folders to the corresponding Magento locations so as not to delete any of the existing files and I have put down my theme's name in all of the the 'System -> Configuration -> Design -> Themes' inputs. However the site still has the default look.
I would say, that I should delete some of the default folders in the app, js, media or skin folders but I'm not sure which ones.
Is there any way some of you could help my having these information, please?
Thank you very much!

A: You should be able to find corresponding folders in Magento's root for app, skin, js and media.
Theme layout files (app) go in app/design/frontend/THEME_NAME
Skin files (skin) go in skin/frontend/THEME_NAME
The js and media files have their own folders in Magento's root.
Once you have your theme files in place, you should be able to select the theme (THEME_NAME) from admin.
Do NOT delete the base and default theme folders, as these are what Magento falls back on if you have a missing file in your custom theme.

A: Where have you put the theme and assets. The theme should be app/design/frontend/ and assets (JS) in skin/frontend/package
Then you can set the design package via the admin.


text:
Q: unable to send messages From SendPort to ReceivePort in flutter I'm trying to send a message via the IsolateNameServer in flutter.
However, I am unable to receive messages. I've tried checking if the receiver port is listening by calling port.listen() twice, and it says that it is already listening.
Where am I going wrong? [ I am closely following this documentation ]
Here is my main.dart, based on the above doc:
import 'dart:isolate';
import 'dart:math';
import 'dart:ui';
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:flutter/material.dart';

final ReceivePort port = ReceivePort();
const String isolateName = 'isolate';

main() async {
  WidgetsFlutterBinding.ensureInitialized();

  IsolateNameServer.registerPortWithName(
    port.sendPort,
    isolateName,
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
            primarySwatch: Colors.blue,
            accentColor: Colors.pink,
            floatingActionButtonTheme:
                FloatingActionButtonThemeData(backgroundColor: Colors.pink)),
        home: AlarmManagerExample());
  }
}

class AlarmManagerExample extends StatefulWidget {
  @override
  _AlarmManagerExampleState createState() => _AlarmManagerExampleState();
}

class _AlarmManagerExampleState extends State<AlarmManagerExample> {
  @override
  void initState() {
    super.initState();
    AndroidAlarmManager.initialize();
    port.listen((_) async => await workForMe());
  }

  workForMe() async {
    print("Secondary Function Triggered!");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: RaisedButton(
          onPressed: () async {
            await AndroidAlarmManager.oneShot(const Duration(seconds: 5),
                Random().nextInt(pow(2, 21)), callback);
          },
          child: Text(
            "Alarm Manager",
          ),
        ),
      ),
    );
  }

  static SendPort uiSendPort;

  static callback() {
    print("Callbacks Triggered!");

    // This will be null if we're running in the background.
    uiSendPort ??= IsolateNameServer.lookupPortByName(isolateName);
    uiSendPort?.send(null);
  }
}

The output I am getting is :
Callbacks Triggered!

However, the expected output is:
Callbacks Triggered!
Secondary Function Triggered!

A: I do believe that error is caused because the workForMe() function isn't static. Moreover, I don't know if callBacks support Future or async.
With that said, try this, as there is no need to make it async.
 static void workForMe() {
   print("Secondary Function Triggered!");
 }


text:
Q: Method returning from one class to another class I'm currently learning OOP in Java, I have tried to write a mini database system, everything works well but I have two methods which are located in class CivilStatus that are not working well and they keep giving me 0 as a return, the methods are PersonAge(String NationalId) and CountSingle(). I would be grateful if anyone would have solved this bug for me.
public class Person101 {
    String nationalIdString;
    String nameString;
    int Age;
    Boolean marriedBoolean;

    Person101(String newId, String name, Boolean newMarried) {
        nationalIdString = newId;
        nameString = name;
        marriedBoolean = newMarried;
        Age = 0;

    }

    public String getId() {

        return nationalIdString;
    }

    public String getName() {

        return nameString;
    }

    public int getAge() {

        return Age;
    }

    public Boolean getMarriedStatus() {

        return marriedBoolean;
    }

    public void setAge(int newAge) {
        Age = newAge;

    }

    public void setName(String newName) {
        nameString = newName;

    }

    public void print() {
        System.out.println("The name is: " + nameString + " ,Id is: " + nationalIdString);

    }

    public boolean SingleJordanian() {
        if ((nationalIdString.contains("Jor")) && (marriedBoolean == false)) {
            return true;
        } else {
            return false;
        }

    }
public void birthday() {
        Age++;
    }

}

import java.util.ArrayList;

public class CivilStatus1 {
    String nameString;
    ArrayList<Person101> personsArrayList;

    CivilStatus1(String newName) {
        nameString = newName;
        personsArrayList = new ArrayList<Person101>();

    }

    public String getName() {

        return nameString;
    }

    public ArrayList<Person101> getPerson101s() {

        return personsArrayList;
    }

    public int PersonAge(String NationalId) {
        int newAge = 0;
        for (Person101 person101 : personsArrayList) {
            if (person101.nationalIdString.equals(NationalId)) {
                newAge = person101.Age;

            } else {

            }
        }
        return newAge;

    }

    public int CountSingle() {
        int counter = 0;
        for (Person101 person101 : personsArrayList) {
            if (person101.SingleJordanian()) {
                counter = counter + 1;

            } else {

            }
        }
        return counter;
    }
}

Thanks in advance!

A: There are a few things that could be causing issues.
Firstly with the variables of each class it is better practice to specify if they are public
public String nationalIdString;
public String nameString;
public int Age;
public Boolean marriedBoolean;

or private.
private String nationalIdString;
private String nameString;
private int Age;
private Boolean marriedBoolean;

Otherwise the variables are package protected which may causing issues with accessing the variables.
If you set them to private you can access them using getter methods
public String getNationalIdString(){
    return nationalIdString;
}

If you are using getters your method should look something like this
    public int PersonAge(String NationalId) {
    int newAge = 0;
    for (Person101 person101 : personsArrayList) {
        if (person101.getNationalIdString().equals(NationalId)) {
            newAge = person101.getAge();

        } else {

        }
    }
    return newAge;

}

I'm not sure if this is causing the problem but it may be.
The other suggestion is using boolean instead of Boolean unless there is a specific reason why you are using it.
To help debug your code I suggest doing something like this
    public int PersonAge(String NationalId) {
    int newAge = 0;
    for (Person101 person101 : personsArrayList) {
        System.out.println("Looking for: " + NationalID + " current person: " + person101.NationalID);
        if (person101.nationalIdString.equals(NationalId)) {
            newAge = person101.Age;
        }
    }
    return newAge;

}

This should help you locate the problem, you can also add the person's name so you can compare that to the data you inputted. I also removed the else branch of the if statement as it was not used.
Also check that SingleJordanian() is working as expected as that may be root of CountSingle() not working as intended.

A: The problem is the same for both methods. Writing
personsArrayList = new ArrayList<Person101>();

creates an ArrayList, but it's empty, as you have not added any items to  it. Then, when you try looping over the ArrayList
for (Person101 person101 : personsArrayList) {
    if (person101.nationalIdString.equals(NationalId)) {
        newAge = person101.Age;

    } else {

    }
}

It doesn't even enter the loop, as there is nothing to loop over.
You should first add some items to the loop, for instance:
Person101 person1 = new Person101();
personsArrayList.add(person1);

As an aside, I would suggest that you shouldn't include the variable types in the name, e.g. personsArrayList, marriedBoolean. You already specified the type when you declared it
ArrayList<Person101> personsArrayList;

Rather just name them persons, married etc.
Just my 2 cents :).


text:
Q: What am I missing in my RegEx expression? So, regex has been the bane of my existence for some time. I feel that I'm on the cusp of understanding it, but I'm just getting very frustrated. In short:
I'm attempting to scrape data from the following website via PHP:
http://magicseaweed.com/Asbury-Park-Surf-Report/857/
I want to extract the bold wave height at the top of the page (at the moment, it reads 3-5). I understand why this works:
preg_match('/

 (.*)
ft<\/small>   <\/span>
/', $pageMagic,
$height);

But I don't understand why this will not:
preg_match('/

 (/d-/d)|(/d)
ft<\/small>   <\/span>
/', $pageMagic,
$height);

In my mind, logically speaking, it should be looking for a digit, a dash, then another digit OR just one digit. I tested out regex in http://gskinner.com/RegExr/ and it picked up 3-5. Thank you in advance!

A: Your slashes are the wrong way around. It should be:
(\d-\d)|(\d)

Incidentally, you can simplify this to:
\d(-\d)?

...but note that this would change the capture groups. I leave the fix for that as an exercise for you :)


text:
Q: Bootstrap popovers without borders on the clicked element I want to use a Bootstrap popover on a custom element. This element is not a button, and when the user click on the element to display the popover, there is a blue border around the element because it is selected. How to remove the blue border ?

A: Adding the following style on the element overwrite current style with shadows and borders:
a:focus {
     outline:none;
     border:0px;
     -webkit-box-shadow: 0px;
     box-shadow: 0px;
 }

Replace a:focus by div:focus or .myclass:focus depending on your element markup.


text:
Q: How to make Pandas Groupby faster? I have a large volum data
frame = pd.DataFrame(res)
groupedData = frame.groupby(['objectType','userId','actionType']).size()

(pd.DataFrame(data=groupedData)).to_excel(writer,'sheet2')
writer.save()

How can I accelerate it by using multiprocessing or parallel?


text:
Q: Reliably detect if the script is executing in a web worker I am currently writing a little library in JavaScript to help me delegate to a web-worker some heavy computation .
For some reasons (mainly for the ability to debug in the UI thread and then run the same code in a worker) I'd like to detect if the script is currently running in a worker or in the UI thread.
I'm not a seasoned JavaScript developper and I would like to ensure that the following function will reliably detect if I'm in a worker or not :
function testenv() {
    try{
        if (importScripts) {
            postMessage("I think I'm in a worker actually.");
        }
    } catch (e) {
        if (e instanceof ReferenceError) {
            console.log("I'm the UI thread.");
        } else {
            throw e;
        }
    }
}

So, does it ?

A: Quite late to the game on this one, but here's the best, most bulletproofy way I could come up with:
// run this in global scope of window or worker. since window.self = window, we're ok
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
    // huzzah! a worker!
} else {
    // I'm not a worker... sad trombone.
}

A: Emscripten does:
// *** Environment setup code ***
var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';
var ENVIRONMENT_IS_WEB = typeof window === 'object';
var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;

(Emscripten on Github)

A: As noted there is an answer in another thread which says to check for the presence of a document object on the window.  I wanted to however make a modification to your code to avoid doing a try/catch block which slows execution of JS in Chrome and likely in other browsers as well.
EDIT: I made an error previously in assuming there was a window object in the global scope. I usually add
//This is likely SharedWorkerContext or DedicatedWorkerContext
window=this;

to the top of my worker loader script this allows all functions that use window feature detection to not blow up.  Then you may use the function below.
function testEnv() {
  if (window.document === undefined) {
    postMessage("I'm fairly confident I'm a webworker");
  } else {
    console.log("I'm fairly confident I'm in the renderer thread");
  }
}

Alternatively without the window assignment as long as its at top level scope.
var self = this;
function() {
  if(self.document === undefined) {
    postMessage("I'm fairly confident I'm a webworker");
  } else {
    console.log("I'm fairly confident I'm in the renderer thread");
  }
}


text:
Q: Can msmdpump be used for connecting to local cubes? I am trying to configure IIS to connect to a local cube(.CUB file) through msmdpump so I can query the local cube using XMLA. I changed msmdpump.ini to look like this:
<ConfigurationSettings>
    <ServerName>"C:\Adventure Works.cub"</ServerName>
    <SessionTimeout>3600</SessionTimeout>
    <ConnectionPoolSize>100</ConnectionPoolSize>
</ConfigurationSettings>

When I send an XMLA request to IIS server I get internal server error (error code 500) with this message: There is a problem with the resource you are looking for, and it cannot be displayed.
Has anyone successfully configured IIS to point to a local cube rather than an MSAS server?


text:
Q: loading Skin images dynamically (another of my never ending questions...)
I need an image component with states which behaves like a ToggleButton. Rather than build from scratch I thought I would try subclassing ToggleButton and defining a custom Flex skin. I don't have much experience with skinning and have cobbled together the code below.
It seems to work well – binding BitmapImages in the skin to BitmapData loading in the button instance: <s:BitmapImage source="{hostComponent.upImageData}"
Am I on the right track with this approach? Is there a more standard approach to this sort of thing?
ToggleButton Skin
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:fb="http://ns.adobe.com/flashbuilder/2009"
                   minWidth="21" minHeight="21"
                   alpha.disabledStates="0.5">
    <fx:Metadata>[HostComponent("components.EventButton")]</fx:Metadata>

    <!-- host component -->
    <!-- states -->
    <s:states>
        <s:State name="up" />
        <s:State name="over" stateGroups="overStates" />
        <s:State name="down" stateGroups="downStates" />
        <s:State name="disabled" stateGroups="disabledStates" />
        <s:State name="upAndSelected" stateGroups="selectedStates, selectedUpStates" />
        <s:State name="overAndSelected" stateGroups="overStates, selectedStates" />
        <s:State name="downAndSelected" stateGroups="downStates, selectedStates" />
        <s:State name="disabledAndSelected" stateGroups="selectedUpStates, disabledStates, selectedStates" />
    </s:states>

    <s:BitmapImage source="{hostComponent.upImageData}"
                   includeIn="up, disabled"
                   left="0" right="0" top="0" bottom="0" />

    <s:BitmapImage source="{hostComponent.overImageData}"
                   left="0" right="0" top="0" bottom="0"
                   includeIn="over"/>

    <s:BitmapImage source="{hostComponent.downImageData}"
                   left="0" right="0" top="0" bottom="0"
                   includeIn="down, upAndSelected, overAndSelected, downAndSelected"/>
</s:Skin>

ToggleButton
<?xml version="1.0" encoding="utf-8"?>
<s:ToggleButton xmlns:fx="http://ns.adobe.com/mxml/2009"
          xmlns:s="library://ns.adobe.com/flex/spark"
          xmlns:mx="library://ns.adobe.com/flex/mx"
          xmlns:skins = "skins.*"
          skinClass="skins.EventSkin"
          creationComplete="creationCompleteHandler(event)">

    <fx:Script>
        <![CDATA[

            [Bindable]
            public var upImageData:BitmapData;

            [Bindable]
            public var overImageData:BitmapData;

            [Bindable]
            public var downImageData:BitmapData;

            [Bindable]
            public var disabledImageData:BitmapData;

            // image loading code removed

        ]]>
    </fx:Script>
</s:ToggleButton>

A: Yep, you are going in right way. The "Skin mechanism" is really powerful and flexible tool. I had similar task about year ago and I solved it in the same way (just with standard ToggleButton and custom skin). All changes in visual representation of spark component might to be in skin class.

A: As another option, you should be able to use the state variable syntax:
<s:ToggleButton icon.up="{upIcon}"
        icon.over="{overIcon}"
        icon.down="{downIcon}"
        icon.disabled="{disabledIcon}"
        icon.upAndSelected="{upAndSelectedIcon}"
        icon.overAndSelected="{overAndSelectedIcon}"
        icon.downAndSelected="{downAndSelectedIcon}"
        icon.disabledAndSelected="{disabledAndSelectedIcon}" />

See this Apache mailing list thread for more discussion on this.


text:
Q: Exception error in Java while attempting sorting i am doing sorts in java and i have ran into an error. The error is stemming from my class file and then the tester i have in turn, wont work. Here is the class
import java.util.*;

public class CompanyDataBase
{
    ArrayList<Employee> employee = new ArrayList<Employee>();
}

//Default Constructor
public CompanyDataBase()
{

}

//Methods
//Add Employee
public void addEmployee(Employee newGuy)
{
   employee.add(newGuy);
}

//Get the employees
public ArrayList<Employee> getEmployees()
{
   return employee;
}

//Sort by name
public ArrayList<Employee> sortByName()
{
   Collections.sort(employee, new EmployeeNameComparator());
   return employee;
}

//Sort by salary
public ArrayList<Employee> sortBySalary()
{
   Collections.sort(employee, new EmployeeSalaryComparator());
   return employee;
}

//Bubble Sort
public void bubblesortBySalary(int [] employee)
{
    int temp = 0;
    boolean arraySorted = false;

    for (int i = 0; i < employee.length - 1 && !arraySorted;
                            i++ )
    {
    arraySorted = true;   // start a new iteration;
                          //  maybe the array is sorted

    for ( int j = 0; j < employee.length - i - 1; j++ )
    {
       if ( employee[j] > employee[j + 1] )
       {
          // swap the adjacent elements
          //   and set arraySorted to false
          temp = employee[j + 1];
          employee[j + 1] = employee[j];
          employee[j] = temp;
          arraySorted = false;
       }
    }
 }

}
}
Also here is the tester that i am using
public class BubbleSortTester
{
    public static void main(String[] args)
    {
        CompanyDataBase myDb = new CompanyDataBase();

        myDb.addEmployee(new Employee("James, John", 34, 45234));
        myDb.addEmployee(new Employee("Conroy, Mike", 19, 19234));
        myDb.addEmployee(new Employee("Gavigan, Luke", 28, 30234));
        myDb.addEmployee(new Manager("Gates, Bill", 28, 44000, 2000));

        myDb.bubblesortBySalary();

        for(Employee currEmployee: myDb.getEmployees())
        {
            System.out.println(currEmployee.getDescription());
        }

    }
}

The problem i am having is that when i attempt to compile my tester it gives me the following error >>>>
 BubbleSortTester.java:16: error: method bubblesortBySalary in class CompanyDataBase cannot be applied to given types;
      myDb.bubblesortBySalary();
          ^
  required: int[]
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error
I then tried it in Eclipse instead of jGrasp and that advised me to enter null but when i enter null it returns this error >>>
    Exception in thread "main" java.lang.NullPointerException
    at CompanyDataBase.bubblesortBySalary(CompanyDataBase.java:46)
    at BubbleSortTester.main(BubbleSortTester.java:16)
Sorry for the amount of code but any help would be appreciated,
Thanks in advance,
Jason

A: You have called bubblesortBySalary as:
myDb.bubblesortBySalary();

but your definition of the method is
public void bubblesortBySalary(int[] employee){
   ....
}

So the method was expecting an int[] but didn't recieve one
Possible solution
You method appears to expect an array of integers to sort which it calls employees, you also have an instance field called employees which I believe you may be intending to sort. If so you will need to provide some method to compare Employees and remove the passed int[]. If you just want to sort integers you need to provide those integers to the method

A: The function bubblesortBySalary(); requires an argument of type int[]. You need to supply that for this to compile.
Passing null makes the compiler happy, but doesn't solve the fundamental problem that you haven't supplied an array to be sorted. Once you define the array, such as int[] employee = new int[] {1, 2, 3, 4}, pass it to the function as myDb.bubblesortBySalary(employee);.


text:
Q: How to set caret position in contenteditable div relative to innerText When I edit a contenteditable div's innerHTML, it forces the caret to the start of the div. I want to move it back to its position relative to the div's innterText afterwards. I am able to get/store the caret's position, but using selection/range objects to move it back there is too damn confusing for me.
tldr how do you move a caret in a contenteditable div relative to innerText
I found lots of almost-applicable on here but ran into weird bugs with each function I came across.
Would really appreciate any help as this is the final hurdle in my project and I've been stuck for a while


text:
Q: "Schwarz symmetrization" on annulus If $\Omega=\{x\in \mathbb R^n| 0<r_0<|x|<r_1\}$ is an annulus on $\mathbb R^n$, I am looking for a symmetrization result on $\Omega$. To be precise, for any $u \in W_0^{1,2}(\Omega)$, can we find a $u^* \in W_0^{1,2}(\Omega)$ such that 1) $u^*$ is radial, 2) $u$ and $u^*$ have the same distribution function, and 3) $\int_\Omega|\nabla u|^2dx \geq \int_\Omega|\nabla u^*|^2dx $?

A: Such a construction is not possible.
One way to see this is to note that if such a construction was possible, then you would have, by the embeddings for Sobolev spaces of radial functions
$$
  \Vert u^* \Vert_{L^\infty} \le C \Vert \nabla u^* \Vert_{L^2}.
$$
By the assumptions that you have on your rearrangement, this would imply in turn that
$$
  \Vert u \Vert_{L^\infty} \le C \Vert \nabla u \Vert_{L^2},
$$
which is known to fail.


text:
Q: Booting problem after force shutdown My laptop model is HP ProBook 440 GL. My Ubuntu got hanged while I was editing stuffs in gravity designer. And forcefully shut the system by pressing power button for long time. Now whenever I open my system it shows me three options to choose from.

*

*Ubuntu

*Advanced options for Ubuntu

*System setup.

Whenever I click on the above two options and any following options in them (in option 2), the screen shows the pattern without any text in it and get stuck over there.
I have important data and more importantly some works to do. How do I get out of this issue?


text:
Q: parallelization several for loops in julia I have several loops like:
for i = 1 : m
        var1 = 1
        var2 = 12.4
        for j = 1 : n
            var3=8
            var4=array1[1]
                for l = var1 : n
                    var5 = aary1[l]
                    var6 = arry2[l,i]+var5
                    if var6 > var3
                        var7 = var6
                        var8 = array1[l]
                        var1 = l
                    else
                        break
                    end

                end
                array3[j,i] = var7
                array4[j,i] = var8
                println("........")
          end
    end

I want to parallel this code by static scheduling ( @parallel for). How can I Parallel these loops?


text:
Q: Youtube iframe API - hiding controls and related videos not working? have a project where we're trying to jerry-rig a solution for a kiosk. Trying to make it possible to view the videos but hide all controls and related information so they press a button to play, and another button to go back. I'm currently structuring a video like so:
$('#vidPlayer1').on('click', function(){
  player = new YT.Player('player', {
    height: '100%',
    width: '100%',
    videoId: 'MYVIDEOID',
    controls: 0,
    showinfo: 0,
    autoplay: 0,
    rel: 0,
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
  // Make sure we hide view content.
  hideContent(v1c);
});

Supposedly, controls: 0, showinfo: 0, rel:0 should remove all this information, but it's not hiding the information. Is there something I'm missing here? The video views and plays just fine - it's just the additional information is displaying. Thoughts?

A: Video Player Constructors
function onYouTubeIframeAPIReady() {
  var player;
  player = new YT.Player('player', {
    videoId: 'M7lc1UVf-VE',
    playerVars: { 'autoplay': 1, 'controls': 0 },
    events: {
      'onReady': onPlayerReady,
      'onPlaybackQualityChange': onPlayerPlaybackQualityChange,
      'onStateChange': onPlayerStateChange,
      'onError': onPlayerError
    }
  });
}


text:
Q: SQL Query expensive calculation by date filters and column filter expens table contains four fields
(Date(Date),Breakfast(INT),Lunch(INT),Dinner(INT) Expense(INT))

I just need to filter date wise and column wise .

*

*if i select date wise means i will get expense amount on that date
Ex:breakfast+lunch+dinner(Int) on particular date

*If want only breakfast means it must add (breakfast+breakfast)(INT) throught the particular month
Ex:Feb expenses on breakfast

A: Statements s1=c.createStatement();
String query="SELECTS SUM (IF MONTHNAME (date)="February",Breakfast,0),(Breakfast+lunch+dinner) as total
FROM Expense_Traze
WHERE MONTHNAME (date) ="February" OR date="2012-2-11";
S1.execute(query);

Table Expense_Traze
Date(Date)  Breakfast(INT)  Lunch(INT)  Dinner(INT) Total(INT)
2016-2-11         10                  20           30         60
2016-2-11         30                  20           10         60
If it is the month of Feb means adds SUM (Breakfast) is 40 i e Column wise, if not means it will add (Breakfast+Lunch+Dinner) As Total on Particular date like 2016-3-15.


text:
Q: Allow user to customize page sections Is it possible to allow a user to customize sections of our website to match their look and feel? For example, to modify logos and CSS, possibly pointing back to their site for the actual content. Ideally I would also like a third-party (ASP.NET) tool to manage this, rather than coding a hack myself.
Edited: I want a solution where a customer can just use a menu to modify the attributes they want, so that there is no need for me to interact with the customer at all.

A: What you want is a CMS (Content Management System), there are lots out there. Just find one that suits you.
I hear Sitefinity is good.


text:
Q: LocalStorage.getLocalStorage is not a function - JS DOM Manipulation I am creating a program where I am storing the data in local storage. Anytime I click on the add/remove button, I keep getting this error. LocalStorage.getLocalStorage is not a function
Below is my Local Storage class
class LocalStorage {
  constructor(storageKey) {
    this.storageKey = storageKey;
  }

 getLocalStorage = () => JSON.parse(localStorage.getItem(this.storageKey));

 setLocalStorage = (data) => localStorage.setItem(this.storageKey, JSON.stringify(data));
}

export default LocalStorage;

I'm importing this class in this code block below
class SaveAll {

save = (title, author) => {
    let books = [];
    if (localStorage.getItem('book') === null) {
      books = [];
    } else {
      // books = JSON.parse(localStorage.getItem('book'));
      books = LocalStorage.getLocalStorage('books');
    }
    const book = { text1: title, text2: author };
    books.push(book);
    // localStorage.setItem('book', JSON.stringify(books));
    LocalStorage.setLocalStorage(books);
  }

}

This is the extracted code for the UI
static renderBooks = () => {
    bookText.innerHTML = '';
    let books = [];
    if (localStorage.getItem('book') === null) {
      books = [];
    } else {
      books = JSON.parse(localStorage.getItem('book'));

      books.forEach((book) => {
        bookText.innerHTML += `

${book.text1}

${book.text2}

              <button onclick="deleteBook('${book.text1}',
              '${book.text2}')">Remove</button>

            `;
      });
    }
  }

I have tried implementing the code in the home.html file but it didn't work so I opted to extract them into a separate js files and that is still not working

A: you are trying to access class methods without class instance so i suggest make your methods static
class LocalStorage {
  constructor(storageKey) {
    this.storageKey = storageKey;
  }

 static getLocalStorage = () => JSON.parse(localStorage.getItem(this.storageKey));

 static setLocalStorage = (data) => localStorage.setItem(this.storageKey, JSON.stringify(data));
}

this will solve your problem because static methods are accessible without class instance


text:
Q: "It does not get released" vs. "it does not release" Please check both sentences and let me know what exactly difference is between both sentences.

It (a movie) does not get released

Or

It (a movie) does not release.

A: Maulik has given you a good start. What you need to think about are the practical difference between the two options. The clear difference is "get". So what does "get + past participle" give us?
Well, firstly, movies don't release themselves! But I think you knew that. So our second option is not great, as we can't use "release" as an action of the movie itself. For this to work we would need a verb that can be something that a movie does.

If a movie doesn't suck.

Moving on to "get", in your first sentence; this sentence is perfect - it sounds natural and is entirely self-explanatory. "Get" is an extremely flexible verb with many uses and meanings. Its function in this case is to externalise the action. That is, we are saying that the action "occurred" without explaining how, and more importantly by who. This is a form of the passive/causative, which is a vital tool in English.
We use "get + past participle" to externalise an action where the "agent" (who did it) is unknown, unimportant, or self-explanatory.
Here are a couple of other examples:

When a book gets published, it is a nervy time for the author...
If you get arrested, it's important to know your rights...

In the event that you want to explain who performed this "externalised action", you can do so by simply using "by":

If a movie doesn't get released by a movie company, it's likely due to...


text:
Q: How can I analyse signal with discrete wavelet transform? With CWT it's clear enough. We have function of two variables which are scale and translation. But what about DWT?
Here is Matlab code:
x = 0:pi/100:3*pi;
y = sin(x);
[lHaar, hHaar] = dwt(y, 'haar');
[lSym, hSym] = dwt(y, 'sym4');

And then I plot them.
Original signal:

Haar transform with original signal:

And symlet transform:

And how can I get time-frequency domain from the results? Where are scales and time?
How can I plot nice images like this one?

A: I have not used Matlab's DWT functions too much as I mostly build my own functions, but in general the most commonly used DWTs are dyadic, which means they subsample a factor of two for each scale. So you will get discrete "frequencies" : one frequency which is double, one which is x4 one which is x8 and so on. Each time the number of samples will be halved. So say you do a 3 level dwt of a 128 sample signal

*

*1st level: low pass will get 64 samples, high pass 64 samples (what I suspect you are looking at)

*2nd level: low pass on the 64 previously low passed will get 32 low pass, and 32 high pass

*3rd level: low pass on the 32 previously low passed  will get 16 low, pass and 16 high pass

So the result is split into 4 frequency bands: 16,16,32,64 samples. The ones with fewest samples will be containing the "coarsest" details or lowest frequencies.
You can type "help dwt" to see exactly what it does, my suspicion is that it does one level and that you have to call it again with the low frequency one to get second level and so on.


text:
Q: How do I draw a line in Titanium? How Do I draw a line in Titanium that works in both Android and iPhone?

A: To create a line, I use;
var view = Ti.UI.createView({
    height:180,
    width:300
});

var line = Ti.UI.createView({
    height:2,
    bottom:0,
    left:0,
    right:0,
    borderWidth:1,
    borderColor:'#aaa'
 });

view.add(line);

A: Add this to your view.xml
<View class="line"></View>

Add this to your style.tss
".line": {
    height: '2dp',
    bottom: '2dp',
    left: '0dp',
    right: '0dp',
    borderWidth: '1',
    borderColor:'#aaa',
}

A: you could create  webview and use the <canvas> tag to draw in the web view


text:
Q: Apache Validator or Hibernate Validator Alternative I'm trying to find a configurable/dynamic validator for normal Pojo class.
The application I'm developing is pretty simple..
XML -> Pojo Object -> Validation -> insert into database.
I'm trying to make the validation dynamic so I can change it on the fly as long I have written the validation before.
This is a stand-alone application.
1) Each class validation can be configure via XML
2) Custom validation can be written first, something like command object.
I'm doing literature research first. So I am wondering the following questions.
1) Will Apache Validator or Hibernate Validator meet my requirements?
2) Are there alternative that I should consider?
3) If they can't meet my requirement, does it mean I have customize it?
Any help would be greatly appreciated.

A: You should take a look at OVal
It's a validation framework, still maintained, light and extensible.
You can write your constraints using annotations, pojos, or XML
Complex contraints can be written, for exemple dynamic and/or custom checks, based on multiple fields written in script languages (groovy, ruby, javascript, etc)
The userguide is well done
I cannot tell if it's better than apache validator or hibernate validator, I didn't well tested them. But I use OVal for a while now, and I'm quite sure it fulfill your needs

A: Another good alternative for hibernate-validator is Apache BVal
Get the validator factory by the following code
ValidatorFactory validatorFactory = Validation
                       .byProvider(ApacheValidationProvider.class)
                       .configure()
                       .buildValidatorFactory();


text:
Q: TYPO3: content element "plugin" -> custom fluid template I work with EXT:news, inserting the plugin in the backend as content element on a page, I can override the fluid templates of the extension itself with my custom extension.
But I remain with the rendering of a division, the header and 'general data' (if defined) as sort of container which I cannot find how to make custom ...
I want to determine the whole output to suit my template, I'd like to substitute this:

 Header Plugin Content Element

    //

    //
    //

    //        ...
    //

    //
    //

thanks for the attention

A: I think that HTML comes from the rendering for each content element, although for plugins the DIV wrap and especially the header normally are not rendered.
That might be dependent on definitions of the framework/ package/ site extension you are using.
Look into the global rendering of content elements. There you can override the rendering , or make it dependent on the kind of plugin with your own condition.
For FSC(Fluid Styled Content) you can find (and add) template paths at lib.contentElement.*Paths.
If you want a special solution for your plugin you can add a variant with a specific condition in your copy of EXT:fluid_styled_content/Resources/Private/Layouts/Default.html or you modify EXT:fluid_styled_content/Resources/Private/Templates/List.html to use another layout for all plugins (one without the usual wrapping for all CEs).
Be aware that an anchor might be helpful for any CE.

A: You should define your own Layout template. In your custom template there should be a call to the Layout section. Change this to your custom layout.


text:
Q: Insert a string at specified indexof position using VB.NET I'm trying to insert the string " " or a blank space in a specified index on a textbox like so:
textbox = heybrowhatsup

I want to insert an " " on the indexes 4, 8 and 14, to get "hey bro whats up", but my code just won't work.
My code:
    Dim str As String = sum2.Text
    Dim insStr As String = " "
    Dim strRes As String = str.Insert(15, insStr)

A: Any string manipulation creates a new String object.  What you're doing is working perfectly in that it is creating a new String with the specified substring inserted at the specified position.  As is always the case, if you want that String displayed in your TextBox then you must assign that String to the Text property of that TextBox.

A: Dim str As String = sum2.Text
Dim insStr As String = " "
Dim strRes As String = str.Insert(3, insStr)
strRes = strRes.Insert(7, insStr)
strRes = strRes.Insert(12, insStr)

You must use strRes.Insert for second or more.

A: The Space function is useful for formatting output and clearing data in fixed-length strings.
You can use space function as below.
Dim str As String = "heybrowhatsup"
Dim strRes As String = str.Insert(3, Space(1)).Insert(7, Space(1)).Insert(13, Space(1))

Or
You can do the same with insert function.
 Dim str As String = "heybrowhatsup"
 Dim insStr As String = " "
 Dim strRes As String = str.Insert(3, insStr).Insert(7, insStr).Insert(13, insStr)


text:
Q: Controlling Spotify with AppleScript Essentially what I'd like to do is play an entire album via AppleScript. Right now, you can use their special URIs to load the album, but not play it. You can also play a specific track, but once that finishes playing, your queue resumes what was playing before.
Spotify's scripting dictionary is somewhat thin, does anyone know if there are plans to increase its depth a bit?

A: More recent versions of Spotify have added this to the dictionary. For example:
tell application "Spotify"
    play track "spotify:album:7ppypgQppMf3mkRbZxYIFM"
end tell

A: There's currently no way to do this with the current dictionary. We'd like to expand it in the future, but I'm not aware of any concrete plans to do so at the moment.

A: If you want to play/pause whatever was most recently playing you can use the following scripts. If you save each of them as Automator applications and you can run them from Spotlight or Alfred.
Play:
tell application "Spotify"
    play
end tell

Pause:
tell application "Spotify"
    pause
end tell


text:
Q: Get concurrent user's avatar in SignalR chat This is the ChatHub code:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace BIX
{
    public class ChatHub : Hub
    {
        static ConcurrentDictionary<string, string> dic = new ConcurrentDictionary<string, string>();
        public void Send(string name, string message)
        {
            Clients.All.broadcastMessage(name, message);
        }

        public void SendToSpecific(string name, string message, string to)
        {
            Clients.Caller.broadcastMessage(name, message);
            Clients.Client(dic[to]).broadcastMessage(name, message);
        }

        public void Notify(string name, string id)
        {
            if (dic.ContainsKey(name))
            {
                Clients.Caller.differentName();
            }
            else
            {
                dic.TryAdd(name, id);
                foreach (KeyValuePair<String, String> entry in dic)
                {
                    Clients.Caller.online(entry.Key);
                }
                Clients.Others.enters(name);
            }
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            var name = dic.FirstOrDefault(x => x.Value == Context.ConnectionId.ToString());
            string s;
            dic.TryRemove(name.Key, out s);
            return Clients.All.disconnected(name.Key);
        }
    }
}

It run well, but the problem is it only can pass correct username and message between other chatters , if I use the user's avatar url then only we cannot get the right avatar. So my question is how to use the ConcurrentDictionary to pass one more key (avatar's url) instead of only one Tkey and one TValue.
Please see my picture :

Chat UI 1

Chat UI2

You can see my chat app can pass correct message , but it displayed wrong avatar. Please help!
And this is the script:

A: Came across this when looking for .netCore 6 solution with Blazor. Since I didn't find one I created one. Images are stored as bytes[] in SQL server AspNetUsers table. This is an extension of a Github project you can find here : https://github.com/enetstudio/SignalRServerIdentityAuthentication

*

*Create a service to query the usermanager.

public class UserProfileService
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly AuthenticationStateProvider _authenticationStateProvider;

    public byte[] UserPicture { get; set; }

    public UserProfileService(UserManager<ApplicationUser> userManager, AuthenticationStateProvider authenticationStateProvider)
    {
    _authenticationStateProvider = authenticationStateProvider;
    _userManager = userManager;
    }
    public async Task GetProfilePicture()
    {
        try
        {
             var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
             var user = authState.User;
             var currentUser = await _userManager.GetUserAsync(user);
             UserPicture = currentUser.ProfilePicture;
         }
         catch (Exception ex)
         {
             Debug.WriteLine("Exception Message: " + ex.Message);
         }
    }

Add it as a scoped service in startup.cs
services.AddScoped<UserProfileService>();

*Create a dictionary to hold user name and string representation of image bytes[]

public class ProfileMapping<T>
    {
        private readonly Dictionary<T, HashSet<string>> _profiles = new Dictionary<T, HashSet<string>>();

        public int Count
        {
            get
            {
                return _profiles.Count;
            }
        }

        public void Add(T key, string Avatar)
        {
            lock (_profiles)
            {
                HashSet<string> avatars;
                if (!_profiles.TryGetValue(key, out avatars))
                {
                    avatars = new HashSet<string>();
                    _profiles.Add(key, avatars);
                }

                lock (avatars)
                {
                    avatars.Add(Avatar);
                }
            }
        }

        public IEnumerable<string> GetAvatar(T key)
        {
            HashSet<string> avatars;
            if (_profiles.TryGetValue(key, out avatars))
            {
                return avatars;
            }

            return Enumerable.Empty<string>();
        }

        public IEnumerable<T> GetUsers()
        {
            return _profiles.Keys.ToList<T>();
        }

        public void Remove(T key, string Avatar)
        {
            lock (_profiles)
            {
                HashSet<string> avatars;
                if (!_profiles.TryGetValue(key, out avatars))
                {
                    return;
                }

                lock (avatars)
                {
                    avatars.Remove(Avatar);

                    if (avatars.Count == 0)
                    {
                        _profiles.Remove(key);
                    }
                }
            }
        }
    }

Inject it in the chat.razor component
@inject UserProfileService _profileService

Initialise it in the chat.razor.cs class.
private readonly static ProfileMapping<string> _profiles = new ProfileMapping<string>();
private byte[] _data;

Add/remove user and avatar to/from the dictionary
private async Task OpenForm()
{
    var profile = _profileService.GetProfilePicture();
    string Avatar = Convert.ToBase64String(_profileService.UserPicture);
    _profiles.Add(userName, Avatar);
    await module.InvokeVoidAsync("openForm").AsTask();
}

private async Task CloseForm()
{
    var profile = _profileService.GetProfilePicture();
    string Avatar = Convert.ToBase64String(_profileService.UserPicture);
    _profiles.Remove(userName, Avatar);
    await module.InvokeVoidAsync("closeForm").AsTask();
}

Then grab it in the Chat.razor component
@foreach (var message in messages)
{
    string Sender = message.Before(":");
    string messagecontent = message.After(":");
    var list = _profiles.GetAvatar(Sender);
    foreach (var profile in list)
    {
        _data = Convert.FromBase64String(profile);
    }

        @Sender

@messagecontent

}

where the hubconnection receive is defined as:
hubConnection.On<string, string>("ReceiveMessage", async (user, message) =>
{
    var encodedMsg = $"{user}:{message}";
    messages.Add(encodedMsg);
    await InvokeAsync(() => StateHasChanged());
});

Hope this helps someone.


text:
Q: can pfSense captive portal grant internet access to IP which is assigned by Windows DHCP server only? In our organization we have a wifi access point and IP addresses are assigned by a Windows DHCP server. We have MAC filtering enabled for internet access in the DHCP server but the issue is that if anyone configure static IP address then he can also access the internet, which we want to restrict. I want to configure any captive portal which can only grant access to IP  addresses which are assigned by the DHCP server.
Can pfSense captive portal grant internet access to IP addresses which are assigned by the Windows DHCP server only??

A: One way to solve this is to have multiple WiFi networks. It depends on the type/brand of Access points You have. Enterprise models normally can handle 4 different networks. Allow anyone with the correct CSID and credentials to use Network 1 (i.e. give access to 10.0.1.0/24). Configure another WiFi network 2 with another CSID connected to lets say 10.0.2.0/24.
Configure the firewall to block internet access from Wifi Network 2, and allow from Wifi Network 1.
Now this solutions does not use captive portal at all, but this should also be possible in PFSense Captive portal out-of-the-box. According to PFSense doc
you can filter on MAC addresses and select PASS or BLOCK according to your need.
The captive portal can either/or filter on IP addresses and MAC addresses.


text:
Q: Add some debug to a puppet custom type I have a puppet custom type in /etc/puppet/modules/tipo/lib/puppet/type/customtipo.rb which contents are:
require 'logger'
Puppet::Type.newtype(:customtipo) do
        newproperty(:parametro) do
                log.info("ES UN PARAMETRO")
        end
end

I know that is a dummy custom type but I'm starting with this sort of things, the resource is placed in /etc/puppet/modules/tipo/manifests/init.pp which contents are:
class tipo {
        customtipo {
        "ejemplo":
        parametro => "uno",
        }
}

The case is whether is a "parametro" or not it doesn't show the message "ES UN PARAMETRO" as I could expect. Is there some other way to achieve this using a custom type? Thanks!

A: Note that the log command will run when your type is loaded by the Ruby runtime, not when the compiler encounters a resource of your type.
Also note that Puppet has a logging framework of its own in Puppet::Util::Logging, that is mixed into any type. You can always just Puppet.info or Puppet.debug.
To get an idea of how to debug your type code, you should familiarize yourself with the available hooks. Look at existing types in Puppet's own source code. You could start with something like this:
Puppet::Type.newtype(:customtipo) do
  newparam(:parametro) do
    # no actual validation, just logging to get started
    validate do |value|
      Puppet.info("parameter 'parametro' has value '#{value}'")
    end
  end
end

Note that I changed newproperty to newparam because you don't want to have a property that is named "parameter". That would be way confusing.


text:
Q: Mysql Procedures: SELECT and UPDATE I'm trying to add this procedure. Its giving me error 1064 (42000) SQL Syntax. But I'm not sure where.
DELIMITER //
 CREATE PROCEDURE disable_expired_users
 BEGIN
   DECLARE @disable_this INT;
   SET @disable_this = SELECT id FROM my_users WHERE TIMESTAMPDIFF(SECOND, NOW(), expire_date) <= 0;
   IF NOT @disable_this IS NULL THEN
     UPDATE my_users SET is_active = 0 WHERE id IN @disable_this;
   END IF;
END; //

A: Why not simply
DELIMITER //
CREATE PROCEDURE disable_expired_users
BEGIN
    UPDATE my_users
        SET is_active = 0
        WHERE expire_date < NOW();
END; //

Even better -- don't store redundant data (is_active=0 vs expire_date<NOW()) -- simply use expire_date<NOW() whenever you need to check for expired.
If you are burdened by Workbench's restriction against UPDATE without blah blah, do something like this:
...
BEGIN
    SET @su = @@sql_safe_updates;
    SET sql_safe_updates = OFF;
    ... UPDATEs, etc ...
    SET sql_safe_updates = @su;
END //

A: SET @disable_this = SELECT id FROM my_users WHERE TIMESTAMPDIFF(SECOND,
NOW(), expire_date) <= 0;

I think the problem is here.
Try
SET @disable_this = (SELECT id FROM my_users WHERE
TIMESTAMPDIFF(SECOND, NOW(), expire_date) <= 0);

A: Add parentheses:
SET @disable_this = (SELECT id FROM my_users WHERE
TIMESTAMPDIFF(SECOND, NOW(), expire_date) <= 0);


text:
Q: Emacs inside terminal change cursor color dynamically I'm trying to change the color of my cursor inside Emacs to another color dynamically.
I'm using emacs -nw for the terminal Emacs. The terminal I'm using is Rxvt-Unicode (Urxvt).
Since Emacs can't (I think) make changes to the terminal, (set-cursor-color "red") won't work. In order to change the cursor color of the terminal I can run
echo -ne '\033]12;red\007'. This changes the color of the cursor to red.
What I tried to do in Emacs is to run this command inside it.
M-x shell-command RET echo -ne '\033]12;red\007' RET
However, Emacs will escape the echoed string and print it at the bottom of the window, and not actually make any changes to the cursor.
I really don't know what else I can do from here, I don't want to use the Emacs GUI. Does anyone know a way around this? I want to be able to change the color of my cursor depending on my current mode, which is why it needs to be dynamic. If anyone has any other suggestions I would be happy to hear them!

A: I think you want to use send-string-to-terminal.
E.g. (send-string-to-terminal "\033]12;red\007").

A: This is a very hackish solution -- I hope someone will find a better one:
(suspend-emacs "echo -ne '\\033]12;red\\007'; fg\n")

It works by temporarily suspending the emacs process and stuffing commands into the underlying terminal to make the shell change the cursor color and resume emacs after that. However, this causes the screen to flicker while the emacs frame temporarily disappears.

Here is another very hackish and system-dependent solution:
(shell-command (format "echo -ne '\\033]12;red\\007' > /proc/%d/fd/1" (emacs-pid)))

It works (at least on Linux) by directly sending the ANSI escape sequence to the terminal (which is accessed through the /proc/PID pseudo-filesystem). I don't find this solution more elegant than the previous one, but at least it doesn't make the screen flicker.


text:
Q: calling inline member in derived class from base class of derived instance I've got two classes, let's call them A and B, that look something like this:
class A {
public:
    inline void f1(int n) { f2(n&1); }
    inline void f2(int n) { } // no-op in base class
};

class B : public A {
public:
    inline void f2(int n) { printf("n=%d\n",n); } // printf for debugging only
};

Now I'm instantiating B, then calling f1.
int main() {
    B myB;

    myB.f1(500);
}

What I expect to happen, is that it will call f1() in B, which is inherited from A, which will in turn take the LSB of 500 and pass it to f2() in B, which will print it out.  Instead what happens is that it calls f1() in A.
Why isn't this working?  The compiler knows at compile time that myB is of class B, not A.  I can't make either f1 or f2 be virtual for two reasons: first, because for performance reasons I can't tolerate any function call overhead, and second, making it inline with some constant parameters allows the compiler to often optimize out a lot of the code.  I have tried making f1() be inline virtual in A, but even with -O3 I am seeing (in one particular test with slightly more code which is irrelevant to this example) about about 500 bytes of assembled code versus 8 bytes if I simply do the equivalent of the following:
class A {
public:
    inline void f1(int n) { f2(n&1); }
    inline void f2(int n) { } // no-op in base class
};

class B : public A {
public:
    inline void f1(int n) { f2(n&1); }
    inline void f2(int n) { printf("n=%d\n",n); } // printf for debugging only
};

Now obviously I could just copy/paste f1 from A to all derived classes, but in the actual code this will wind up being about 10 classes and around 35 functions each instead of 1, and it seems rather hokey to keep #includeing the same code over and over to avoid the incredible maintenance issues with replicating this code in lots of places.

A: There are two problems here:

*

*calling f2() in the context of A actually calls A::f2() - period. If you want polymorphic behaviour you must make f2 virtual.

*You have assumed that making f2 virtual will add runtime overhead. In actual fact, if the compiler can prove that you are calling f1() on a B, there will be no overhead whatsoever.
Proof here: https://godbolt.org/g/2OWPo2
As a bonus, the inline keywords are unnecessary. If you define the body of a method at the point of declaration, that method is implicitly inline.
In addition (and counterintuitively), inline does not cause generation of inlined code. It simply warns the compiler that it might see the definition more than once.
Inlining is an optimisation that the compiler will do on its own.
Finally, look again at the generated assembly. You will see that the compiler didn't even bother to emit a vtable or any vtable construction. Optimisers these days are really good.

A: It's actually very common that you can't afford a virtual function. In that case you need a bit of redesign:
template<typename Impl>
class ABase {
public:
    inline void f1(int n) { f2(n&1); }
    inline void f2(int n) { static_cast<Impl*>(this)->f2(n); }
};

class AReal : public ABase<AReal> {
    inline void f2(int n) { } // no-op here
};

class B : public ABase<B> {
public:
    inline void f2(int n) { printf("n=%d\n",n); } // printf for debugging only
};

Note that you still can't expect dynamic polymorphism and that AReal and B are now unrelated. (If the latter is not desired, it can be fixed by adding a non-template base to ABase; the former can't be fixed w/o the overhead comparable to a virtual.)


text:
Q: Can bound states have zero energy? Suppose a system is under the influence of a potential which vanishes at $\pm \infty$. Now we know that if the energy of the system is negative ($E<0$) then the system is in a bound state and the bound state energy spectrum is discrete. For $E>0$, the system is in scattering states (with continuous energy spectrum). My question is:
What happens at $E=0$? Can we consider it a discrete bound state or should we consider it as a scattering state and why?


text:
Q: Python multithreading for separate mutually exclusive tasks Say you have 4 numbers, and you need to print the multiplication table of all the numbers from 1 to 100 using multithreading in Python. The code that I came up with is
from threading import Thread

def multable(r, number):
    for i in range(1,101):
        mul = number*i
        print "\n%d x %d = %d" %(number, i, mul)

def Main():
    t1 = Thread(target = multable, args = (1, 2))
    t2 = Thread(target = multable, args = (1, 3))
    t3 = Thread(target = multable, args = (1, 4))
    t4 = Thread(target = multable, args = (1, 4))
    t1.start()
    t2.start()
    t3.start()
    t4.start()

if __name__ == '__main__':
    Main()

Partial Output -
4 x 60 = 240

4 x 61 = 244

4 x 62 = 248

3 x 48 = 144

2 x 78 = 156
4 x 63 = 252
3 x 49 = 147

3 x 50 = 150

2 x 79 = 158
3 x 51 = 153

4 x 64 = 256

My questions regarding this are -

*

*Why is there uneven spacing, as I think there should only one line gap between two outputs, by the \n in the print statement?

*Why can't I just pass only one variable as parameter in the thread, the error I get in doing so asks me to give an iterative, so I gave an useless value?

*In a quad-core CPU, how can I edit this program to make use of all four CPUs, each for one number/thread. disregarding the order of output?

A:
Why is there uneven spacing, as I think there should only one line gap
  between two outputs, by the \n in the print statement?

I think you get the spacing issue because python flushes the standard output buffer on each new line.  Since you are doing it in multiple threads there is no guarantee of ordering which leads the data written in each flush to be written in a random order.

Why can't I just pass only one variable as parameter in the thread,
  the error I get in doing so asks me to give an iterative, so I gave an
  useless value?

If you place single a value in () such as (5) it really just means 5.  You need to add a comma for python to think it is a tuple (5,).  Or you can use lists [5].

In a quad-core CPU, how can I edit this program to make use of all
  four CPUs, each for one number/thread. disregarding the order of
  output?

This should happen automatically.  It will be up to the operating system to schedule it.  If it sees 4 separate threads it should place one on each core (depending on the task scheduler.)  You will likely not be able to see all 4 cores at 100% in your task manager for two reasons.  First is that the python interpreter does not really support multi-threading.  Every python statement is locked so only one statement can execute at a time.  You can get around this if you are creating C extensions for python, but all calls to the python interpreter need to be locked.  Secondly even if you wrote the same thing in C I doubt you would see this burning up all cores in your task manager.  It is a very light and IO heavy process which does not use very much CPU.

A: Since you're using threading each thread has its own output, this leads to the fact that every once in a while they will pass \n to the console at the same time. This behavior is causing the varying empty lines you see.
As for passing arguments you can pass a tuple in the following way:
from threading import Thread

def multable(number):
    for i in range(1, 101):
        mul = number * i
        print "%d x %d = %d\n" % (number, i, mul)

def Main():
    t1 = Thread(target=multable, args=(2,))
    t2 = Thread(target=multable, args=(3,))
    t3 = Thread(target=multable, args=(4,))
    t4 = Thread(target=multable, args=(4,))
    t1.start()
    t2.start()
    t3.start()
    t4.start()

if __name__ == '__main__':
    Main()

Thus removing the redundant parameter. I would suggest you use a Queue for printing out the output, that way you can control it better.
Something like:
from threading import Thread
from Queue import Queue

def multable(number):
    for i in range(1, 101):
        mul = number * i
        q.put("%d x %d = %d\n" % (number, i, mul))
        q.task_done()

def main():

    t1 = Thread(target=multable, args=(2,))
    t2 = Thread(target=multable, args=(3,))
    t3 = Thread(target=multable, args=(4,))
    t4 = Thread(target=multable, args=(4,))
    t1.start()
    t2.start()
    t3.start()
    t4.start()

    q.join()

    while not q.empty():
        print '{}\n'.format(q.get())

if __name__ == '__main__':
    q = Queue()
    main()


text:
Q: creating record via command line in Rails - not sure about this error I am trying to create a tag via:
[14] pry(main)> Tag.create! {"phrase" => "here is my phrase" }
SyntaxError: unexpected tASSOC, expecting '}'
Tag.create! {"phrase" => "here is my phrase" }
                        ^
[14] pry(main)> d = {"phrase" => "here is my phrase"}
=> {"phrase"=>"here is my phrase"}
[15] pry(main)> Tag.create! d                        ^

I don't know what's wrong but I can't get this to work. Any idea what I'm doing wrong?
thx

A: actually you forgot the bracket
try

Tag.create!({"phrase" => "here is my phrase" })

A: try this
Tag.create{:phrase => "here is my phrase"}


text:
Q: Сброс настройки маршрутизатора SilkWorm 3250 Нужно взломать (или сбросить) или восстановить пароли маршрутизатора SilkWorm 3250 на WinXP. На оф сайте есть способ восстановления пароля на Линуксе.
A: На оф сайте есть способ восстановления пароля на Линуксе.Приведите ссылку на способ восстановления.Посмотрите вот здесь: Восстановления паролей к Brocade Silkworm switches 4100. В вашем случае, там где идет речь про загрузку в привилегированном режиме. Или еще один момент искать заводской пароль.
A: В руках подобный аппарат не держал, но не уж то нету кнопки "ресет" ?


text:
Q: I am making a Discord bot that needs some Powershell code translated into Javascript I found this code (Powershell) somewhere online that gives you all the video URL's of a Youtube playlist. That is exactly what I was looking for but I need to use it in Javascript.
I don't know how to code in Powershell so that is why I am asking it here.
I am going to use this code in my Discord bot to play music. It will take a Youtube playlist and put all the URL's into the queue. I already have the code for playing individual videos.
I have already tried using a plugin for Javascript called 'node-powershell'. This plugin runs Powershell code in Javascript. This method did not work for me.
$Playlist = ((Invoke-WebRequest "https://www.youtube.com/playlist?list=PLvl4I7g6dfPRLP6etCkU8ZsIben8PWBmI").Links | Where {$_.class -match "pl-video-title-link"}).href ForEach ($Video in $Playlist) { $s ="https://www.youtube.com" + $Video $s
=$s.Substring(0, $s.IndexOf('&'))   Write-Output ($s) }

The 'node-powershell' method gave me errors. So I want that Powershell code translated into Javascript.

A: I threw-up in my mouth a little reading this question. The same part of me that tells kids not to use dirty needles is urging me to tell you to just convert the Powershell to JavaScript. That said, to your question:
const { spawn } = require("child_process");

const cmd = `$Playlist = ((Invoke-WebRequest "https://www.youtube.com/playlist?list=PLvl4I7g6dfPRLP6etCkU8ZsIben8PWBmI").Links | Where {$_.class -match "pl-video-title-link"}).href; ForEach ($Video in $Playlist) { $s ="https://www.youtube.com" + $Video; $s=$s.Substring(0, $s.IndexOf('&')); Write-Output ($s); }`

const cp = spawn('C:\\Program Files\\PowerShell\\6\\pwsh.exe',['-Command', cmd]);
cp.stdout.on("data", (data) => { console.log("Data: " + data); } );
cp.stderr.on("data", (data) => { console.log("Errors: " + data); } );
cp.stdin.end();
cp.on("exit", () => { console.log("Powershell Script finished"); });
cp.stdin.end(); //end input


text:
Q: Angular modular object property binding to ngModel I have an object with 1 set properties and X modular ones which are added depending on at array, the array elements are the object names. This works perfectly to display the elements in my table. My issue comes when I want to bind the textboxes to my model, as I am getting an error saying the object properties does not exist. I have included an *ngIf to check if the property is there and in theory it finds it.
This is part of my HTMl code trying to use one of the modular property names, I have used one which I know will exists to simplify the debugging, next step will be to change this to be fully modular:
<ng-container *ngIf="newWaste[0].hasOwnProperty('Metal')">
 <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns  | slice:2 let i = index">
  <th mat-header-cell *matHeaderCellDef>{{ displayedColumns[i+2] }}</th>
  <td mat-cell *matCellDef="let emp">
   <input type="text"  matInput placeholder="" value="{{ emp[column] }}" [(ngModel)]="newWaste[0].Metal" />
  </td>
 </ng-container>
</ng-container>

I have also tried counting the number of properties instead of directly checking if it exists, no difference neither.
This is my error:
src/app/pages/waste/containers/waste-page/waste-page.component.html:33:132 - error TS2339: Property 'Metal' does not exist on type '{ measuredDate: Date; }'.

33                                     <input type="text"  matInput placeholder="" value="{{ emp[column] }}" [(ngModel)]="newWaste[0].Metal" />
                                                                                ~~~~~

  src/app/pages/waste/containers/waste-page/waste-page.component.ts:19:16
    19   templateUrl: './waste-page.component.html',
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component WastePageComponent.

I create the object with Date parameters, the rest added later.
Binding to Date works perfectly.
Any suggestions?

A:
I create the object with Date parameters, the rest added later

Here's the problem. Initialize newWaste with Metal property already there (no problem if it's initialized to undefined), and probably adjust the TS typing of newWaste so Metal property is non-optional. Angular objects to ngModel pointing at a property which potentially doesn't exist.

A: Thinking about the whole initialization issue, I have tried to initialize an empty array, instead of an array with the object including the "measuredDate" property.
So instead of this:
public newWaste = [{measuredDate: Date}];

I am just using this, and add all properties in the code:
public newWaste = [];

ngOnInit(): void {
    //add the measureDate property
    this.newWaste.push({measuredDate: new Date()});
    //in other methods I add the more specific properties such as Metal
}

It workpes perfectly the way like that.


text:
Q: Google Apps Script only works when manually triggered, not by any other trigger I'm a bit struggling to understand this matter:
My code meant to delete rox X if the colour of a cell in row X column Y is RED (f4c7c3).
For example :

The code works great thanks to a few questions I saw around here that helped me make it better, but it will only work when I click run. If I'm using any trigger (I want to use a time-driven trigger every day between midnight and 1 AM, but I've tried them all), it shows that it was completed, but nothing happens to the spreadsheet.

Here is my code, I'd appreciate your help with that issue:
function DeleteRow(column,color) {   //Delete row if the color in the Date column is F4C7C3
  var column = (typeof(column)!='undefined')?column:4;
  var color = (typeof(color)!='undefined')?color:'#f4c7c3';
  var ss = SpreadsheetApp.openById("1Ichlawob5EHzSK4ljRSJfViugFWugTzHOMId3q5LL6w");
  var sht = ss.setActiveSheet(ss.getSheets()[0]);
  var rng = ss.getDataRange();
  var rngA = rng.getBackgrounds()
  for(var i=rngA.length-1;i>-1;i--)
  {
    if(rngA[i][column-1]==color)
    {
      sht.deleteRow(i+1);
    }
  }
}

BTW, just got a summary that shows the error even though the executions indicate successfully-

A: Try to replace the line:
var column = (typeof(column)!='undefined')?column:4;

To:
var column = (typeof(column)=='number')?column:4;

Or just:
var column = 4;

Explanation
Whenever you're firing a function via a trigger the function gets an 'event object' as a first and only argument. You're actually calling DeleteRow(e) instead of DeleteRow(). Where the e is the event object. It's not undefined and its not a number.


text:
Q: Absolute positioned DIV element spreads over and blocks buttons, how to hide the invisible block? I have an absolute positioned logo on the bottom left of my website... BUT the problem is that ive positioned it to stick to the right of the page but it leaves a invisible barrier to the left of it that spreads across the page. So lets say a link is placed in alignment with that footer element, I won't be able to click it, the absolute positioned layer is spreading over it (even though nothings in it)
Heres my CSS for the logos position:
#basemenu {
margin-right: auto;
position: fixed;
bottom:0px;
width: 100%;
height: 40px;
text-align:right;
right:1%;
}

A: It sounds like you have an img inside of a

. Is that right?
We could really use a block of HTML if you wouldn't mind posting it.
What I don't understand is why you can't target the logo itself with a bit of CSS like this:
#basemenu img {
  height: 40px;
  position: fixed;
  bottom: 0px;
  left: 0px;
}

A: Use the following block property display : none; to hide the block


text:
Q: Помогите оценить время работы функции помогите рассчитать (формально) время работы функции :
for (i=n;i >= 3; i-- {
     for (j=1;j < ln(i) ;j++) {
         for (k=0 ;k <= n; k +=j)
          z++
printIn (z)

Спасибо !

A: Для оценки времени работы метода или еще чего используй такую конструкцию:
    System.out.println("Starting: ");
    long start = System.currentTimeMillis();

    // Здесь какой-то код

    long end = System.currentTimeMillis();
    System.out.println("Time take: " + (end - start));


text:
Q: HiveQL string function questions I'm using HiveQL to run the below query.
The intention is that the case statement removes the last XX characters from the end of the domain, dependent on the suffix (.com, .co.uk).
This doesn't seem to work as there is no change to the strings in the 'domainnew' column in the output.
Can anyone advise how I would make this work?
I also then need to take the output of  'domainnew' and take only the characters to the right of the first '.' when reading from the right handside.
domain  = mobile.domain.facebook.com
domainnew = mobile.domain.facebook
newcalc = facebook
Any advice on this would be brilliant!!
Thank you
select domain, catid, apnid, sum(optimisedsize) as bytes,

          CASE domain
            WHEN  instr(domain, '.co.uk')  THEN substr(domain,LENGTH(domain)-6)
            WHEN  instr(domain, '.com')  THEN substr(domain,LENGTH(domain)-6)
            ELSE domain
          END as domainnew

from udsapp.web

where dt = 20170330 and hour = 04 and loc = 'FAR1' and catid <> "0:0" group by domain, catid, apnid sort by bytes desc;

A: with t as (select 'mobile.domain.facebook.com' as domain)

select  regexp_extract(domain,'(.*?)(\\.com|\\.co\\.uk|)$',1)      as domainnew
       ,regexp_extract(domain,'.*?([^.]+)(\\.com|\\.co\\.uk|)$',1) as new_calc

from    t
;

+------------------------+----------+
|       domainnew        | new_calc |
+------------------------+----------+
| mobile.domain.facebook | facebook |
+------------------------+----------+