text:
Q: Is there a general thesaurus for conceptual fields? My question is about ways to find out about, or remind oneself of, related concepts. Say I'm writing an article and I'm stuck finding the right expression.

*

*I want to say that the author is confused about a concept, but I don't want to use the word "confused", for stylistic, syntactical or any other reasons. I would like to find other words like "muddle", "is not clear about", or "does not distinguish".

*I want to say that I reject an objection to a given view. I would like to find other expressions like "riposte", "rejoinder", but also sentence templates such as "Contra N.N., I hold that"

*What are different ways to express the concept opposition? "In contrast", "Whereas .., ...", "On the other hand".

*What are different ways to make an enumeration of arguments? "First, ...; Second, ...", "For one thing, ...", "for another", ....

What I'm looking for is similar to a thesaurus, but many of these reference works (such as this one) only list expressions of roughly the same lexical category: "contrast" -- "comparison", but not "despite the similarities, ..." etc. "By contrast" is not even listed. Often what you need is just to be pointed in the right direction. Is there anything - a dictionary, thesaurus, list of schematic sentences, web site, ... - that fits my description?

A: I am not sure there is a thesaurus as complete as the one you are looking for.
I like Wordnik, which included lots of examples for each word proposed, as well as related words (and not just synonyms or antonyms).
But the results remain close to the ones found with www.thesaurus.com (thesaurus that you mention in your question).

A: This reference source is a thesaurus, dictionary, encyclopedia, and a specialist reference all at the same place, so it might help.


text:
Q: How to change Android title bar text color programmatically? In my app I populate title bar label from each activity but the text color in the activity and text color in title bar is same. How do I change the title bar text color to a different one?

A: In your onCreate-method add the following:
setTitleColor(YOUR PREFERED COLOR);

A: You can implement a custom title bar (then you have to change the color of a simple TextView). Please check this: How to change the text on the action bar

A: you can do it from 2 places either in style.xml or proramatically
1.From style.xml : by Modifying TitleTextStyle -setting the android:textColour value as desired
2.Or in code    Programatically:
int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView)findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.myColor));

A: use this one
setTitleColor(Color.BLUE);
you can choose different color from Color class.

A:     ActionBar ab = getActionBar();
    TextView tv = new TextView(getApplicationContext());
    LayoutParams lp = new RelativeLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, // Width of TextView
            LayoutParams.WRAP_CONTENT);
    tv.setLayoutParams(lp);
    tv.setTextColor(Color.RED);
    ab.setCustomView(tv);

For more information check this link :
http://android--code.blogspot.in/2015/09/android-how-to-change-actionbar-title_21.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Suggestions for Firebase Firestore Data Structure I've done a lot of reading lately through the documentation but have only just begun using Firebase and could use some suggestions on setting up the data structure for my first web app leveraging Firestore.
I've seen many examples online of code samples, but am having a hard time finding examples of data structures that are similar to what I'm looking to do.
The first project I'm working on (for fun, not commercial use) is to keep track of available conference rooms across multiple offices.
I was thinking of setting it up something like this;
Office Location A
  Room 1
    Available: Yes/No
    Employee: ____
    ReservedAt: ____
  Room 2
    Available: Yes/No
    Employee: ____
    ReservedAt: ____
  Room 3
    Available: Yes/No
    Employee: ____
    ReservedAt: ____
Office Location B
  Room 1
    Available: Yes/No
    Employee: ____
    ReservedAt: ____
  Room 2
    Available: Yes/No
    Employee: ____
    ReservedAt: ____

I come from the world of SQL and PHP, no noSQL databases are very new to me and I'm trying to think outside the usual box of how I would set up a SQL database.
Any input or feedback appreciated.


text:
Q: Set access permissions of ArcGIS Server Map Service with ArcPy I have a number of Map Services I create with an ArcPy script.
After publishing, I have to go to ArcGIS Server Manager to set the access permissions to "Everyone" by clicking on the heads symbol for every Map Service.

I would like to have an automatic solution to set the permissions with ArcPy after the Map Service is published.
Any idea how this could be achieved?


text:
Q: MySQLi not working I know this question is pretty frequent but I wasted so much time on this and still it doesn't work. We're trying to insert a row but it just doesn't work.
This is the code:
<?php
    class DAL{
        private $srvname='localhost';
        private $username='i110546';
        private $password='2349058';
        private $bdname='i110546';

        function insert_log($url){

            $conn = new mysqli($srvname, $username, $password, $bdname);
            if (mysqli_connect_errno()) {
                printf("Conexao falhada: %s\n", mysqli_connect_error());
                                return NULL;
            }

                        $query = "INSERT INTO `log` (`url`) VALUES (?)";
                        $test = $conn->prepare($query);
                        $test->bind_param('ss',$url);
                        $test->execute();
                        $test->close();
                        $conn->close();
                }
    }
?>

Anyone knows what's up?

A: You have only one parameter, but in your bind call you have 2 strings parameter ss.
Should be one:
$test->bind_param('s',$url);

And check for errors.

A: $test->bind_param('ss',$url);

You're binding two two strings (ss) but only supplying one, while your statement only contains one placeholder, my guess is that your desired line is
$test->bind_param('s',$url);

Also, you're addressing your properties the wrong way, they need to be addressed using $this->variable_name inside methods (functions) so modify your line to this
$conn = new mysqli($this->srvname, $this->username, $this->password, $this->bdname);


text:
Q: Jquery flex slider For some reason the nav buttons are being cut off instead of sittin ontop of the slider here is a screen shot screenshot of nav buttons cut off Ive tried all sorts and can't get it to work am I missing something

A: Just to let you know I solved the problem. I hadn't set the flex-container up correctly. After scanning the code with fresh eyes I saw the mistake.


text:
Q: How many numbers between $1$ and $123456789$ have digital root equal to $5$? $S(n)$ is a function. If applied to a number, it sums up all the digits until a single digit is obtained.
  e.g.: $S(919)=S(9+1+9)=S(19)=S(1+9)=S(10)=1+0=1$
Find how many such numbers exists if $1\lt n\lt 123456789$ and $S(n)=5$.

A: The function $S$ gives the remainder when dividing the number by $9$, except that it gives $9$ instead of $0$ when the number is divisible by $9$; this is also known as the digital root of $n$. So your question is exactly the same as asking how many numbers of the form $9k+5$ are there strictly between $1$ and $123456789$.

A: I think this is relevant. It's complementary to Arturo's (excellent and arguably sufficient) answer.
Have you ever heard of the arithmetic technique Casting Out Nines? It's the old gradeschool (though I still use it now) technique to check your sums, differences, products, and quotients by finding the 'digit sums' aka digital roots and making sure they are the same for the question and answer. For example,
$\begin{align}
\quad \; 111 & \qquad (1 + 1 + 1 = 3) \\
+ \; 234 & \qquad (2 + 3 + 4 = 9 \to 0) \\
= \; 345 & \qquad (3 + 4 + 5 = 12 \to 3)
\end{align}$
Since both have digital sum 3, we have additional suspicion that the answer is correct. This is the exact idea that needs to be employed here, and that Arturo used.
Why does it work? It's entirely because we use base 10 arithmetic. So taking the digit sum of 1 = the digit sum of 10 (9 + 1) = the digit sum of 100 (99 + 1), i.e. modding by 9 doesn't change the digit sum. If we were in base 16, we might cast out 15s. And that would be annoying, so thank goodness. The base 2 case, though, doesn't help too much (casting out 1's... not a good idea).


text:
Q: What is the meaning of class myClass? What is the meaning of class myClass<String> in java?
class myClass<String>
{

}

What does this expression mean?

A: This is using generics, a type can be decided at run time. This helps for type safety.
http://en.wikipedia.org/wiki/Generics_in_Java

A: class myClass<String> {}

This creates a class called myClass with a generic type parameter called String. This is a terrible name for a type parameter by the way, since it hides the class called String.
class MyClass<T> {}

would be a better way to express the same thing.
Basically generics allow you to reuse the same class with different types in a type-safe manner. You can read more about generics in the Java Tutorials.

A: It is a generic class . A generic class is defined with the following format:
class name<T1, T2, ..., Tn> { /* ... */ }
The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.

A: This syntax use for defining Generic.
 myClasee means your myclass is create with generic type String.
As for example- If you ever use ArrayList means you are creating arraylist which are holding String objects only.


text:
Q: How to give folder permissions in Helm v4? I have a website, and I'm trying to give folder permissions with FTP Filezilla software, since I can't find this option in Helm web hosting portal.
CHMod seems to be a unrecognized command on FileZilla.
Does helm have an option to set write permissions to a folder?

A: Ok, I think you just can't using Helm web based interface. My hosting support had to manually set these permissions. I really don't like this Plesk and Helm stuff.


text:
Q: Single apex message coming in red but not multiple apex messages Couple of days back , I had a problem like  i have a page message and I want the text to be in red color.
after applying some css it worked out well.But if i am showing more than one error ,then only a heading "messages" comes in red and the messages are coming in normal color.I have added the image for your reference
CSS

and the page message is like
<apex:outputPanel id="errordisplayPanel" >
        <apex:outputPanel Id="errorspanel">
            <input id="isDiscountCheckPrfmd" type="hidden" name="isDiscountCheckPrfmd" value="{!isDiscountCheckPrfmd}" />
            <c:Displayerror id="errordisplay" errorList="{!lstAllError}"  />

        </apex:outputPanel>

        <apex:pageMessages id="msg2" />
    </apex:outputPanel>

A: For multiple messages , salesforce doesnot renders like a single message so the structure is different.
Use below code, for both single and multiple:

Possible duplicate of Want to make page message text red


text:
Q: How to solve offset of screenshot_share_image package in flutter (only ios)? Hello I have an issue during long time, but not found solution. I tried to make a screenshot and share. To do this, I use the package https://pub.dev/packages/screenshot_share_image
But there is an issue when share is launch, and only if I make fall the keyboard and after I publish or cancel, I have an offset in bottom of my ios device. ( no offset with android )
This offset can be remove without close the app

It can be reproduce with package exemple :
https://pub.dev/packages/screenshot_share_image#-example-tab-
  import 'package:flutter/material.dart';
import 'dart:async';

import 'package:screenshot_share_image/screenshot_share_image.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // Platform messages may fail, so we use a try/catch PlatformException.
    Future.delayed(const Duration(seconds: 5), () {
      ScreenshotShareImage.takeScreenshotShareImage();
    });

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Container(
          color: Colors.red,
          child: Center(
            child: Container(
              width: 200.0,
              height: 200.0,
              color: Colors.green,
            ),
          ),
        ),
      ),
    );
  }
}


text:
Q: How to run selenium+chrome on Raspberry PI 4? I have a brand-new out of the box Raspberry Pi 4 that I'd like to run python selenium on.  However, I don't have the path to use for this command: any tips?
driver = webdriver.Chrome("path-to-chromiumdriver")

I am also happy to run it with Firefox if someone has the path for that!
Thanks,
/yga

A: Aha - looks like https://ivanderevianko.com/2020/01/selenium-chromedriver-for-raspberrypi has the answer!
sudo apt-get install chromium-chromedriver

And then in the python code:
from pyvirtualdisplay import Display

display = Display(visible=0, size=(1600, 1200))
display.start()
driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver')

(I wanted to run a headless version; hence the pyvirtualdisplay)


text:
Q: Erlang workflow How do you organize your erlang workflow? I'm learning some Erlang now and I'm using Rebar, recompiling, rebuilding and restarting an entire release (I'm trying to keep things OTP'ish) after each edit. I'm pretty sure that there is a smarter way to do this.

A: In Etorrent, I am using a little trick you may like:
When you have built a development release, you can execute the command make console which has the following definition:
console:
    dev/etorrent-dev/bin/etorrent console \
            -pa ../../apps/etorrent/ebin

basically, it uses the release ebins for most stuff, but overrides the application ebin to be outside at the point where you normally build the software. Now, running a console, you can edit your code, run make (I hit a key combination in Emacs), fix errors, run make again and so on. When you are satisfied with your change, you go into the console (erlang shell) and execute l(ModuleToLoad) at which point the running system gets the new code injected. OTP will automatically pick up the hot-deployed code change and alter the processes. Essentially you only have to restart fairly rarely when working on the code.
Nowadays, we also have tests, so you can execute make test in etorrent to have the test framework run on your newly formed code before injection if you want a bit more guarantee that the new code works.

A: With Chicago Boss you just hit "Refresh" in your web browser:
http://www.chicagoboss.org/
Even if your goal isn't web development, it might be a way to learn Erlang that is more fun than your current workflow. CB pretty-prints compilation and run-time errors right in the browser.

A: I have been using Sync to avoid the dreaded edit/recompile/restart loop. It watches for changes to your source files then recompiles and reloads only the changed module. It prints errors and warnings to the console and sends them to notify-send/growl if available.
It's as easy as running sync:go().
Take a look at this rebar template for a better example.
If you are developing on a cluster another great feature is sync's "patch mode". With "patch mode" every time sync successfully compiles a module it sends the compiled code to every node connected to the cluster and reloads the module!

A: For automatic reloading of src files with each edit, You can try auto plugin in rebar3.
I have recently moved to rebar3 and found it to have much easier to work with compared to rebar.


text:
Q: Jbox2d Issues with positioning platforms I am working on developing a platformer, and everything's working fine, except, I seem to be unable to position the bodies for the static platforms.
    // creating all the bodies
    BodyDef bdef = new BodyDef();
    bdef.position.set(x, y);
    bdef.type = BodyType.STATIC;
    Body body = world.createBody(bdef);

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(width, height);
    FixtureDef fdef = new FixtureDef();
    fdef.friction = 0.3f;
    fdef.shape = shape;
    body.createFixture(fdef);

This is general code that's used to create every body in the map. The bodies work fine, but they don't line up with the width nor the coordinates of the map that I've set. I've noticed that I must specify the bottom left point as starting point for it to make body, but what else I am missing? Why bodies tend to be bigger and go past the starting point of X and Y?

A: Bodies in box2d are made from their center points. When you define it's position, you are setting it's center and when you define it's width/height, you are actually setting half the width/height (i.e. the size ends up double what you intended).


text:
Q: How get string of current Url in protractor? i want to write some condition for protractor autotest.
Example:
if (currentUrl == comparedUrl) {// do first;}
else {// do second;}

For this one i tried to use code:
 var currentUrl = browser.getCurrentUrl().then( function( url ) {
            return url;
            });
    console.log("current url = " + currentUrl);

i get response:
current url = ManagedPromise::122 {[[PromiseStatus]]: "pending"};

but next code  works well:
var currentUrl = browser.getCurrentUrl().then( function( url ) {
        console.log(url);
    });

I don't understand why, and that one isn't what i need. I need to get a string of the URL.

A: if you just want to compare the current url with comparedUrl then you can just use browser.getCurrentUrl();
var currentUrl = browser.getCurrentUrl();

if(currentUrl === comparedUrl) {
 //do first
} else {
 //do second
}

A: Use async await
(async()=>{
var url = await browser.getCurrentUrl();
console.log(url)
})()

await will force browser.getCurrentUrl() to return a promise. Using async await you can avoid then callbacks.

A: Have you tried something like this?
    var urlText = '';
    var currentUrl = browser.getCurrentUrl()
         .then(function(text){
             urlText = text;
             if (urlText == comparedUrl) {
                 // do first;
             }
             else {
                 // do second;
             }
    });

Hope it helps.

A: Promises and browser.getCurrentUrl()
Please review how promises work. In the following example:
var currentUrl = browser.getCurrentUrl().then( function( url ) {
  return url;
});
console.log("current url = " + currentUrl);

browser.getCurrentUrl() and the following chained callback both have the same return type Promise<string>. This means that currentUrl does not have a value of string. You will either need to continue chaining your thenables or change this to async / await.
Setting async / await
You'll need to add the SELENIUM_PROMISE_MANAGER: false in your Protractor configuration. Then in your test you'll be able to await Promises.
it('should do something', async () => {
  const currentUrl = await browser.getCurrentUrl(); // promise is awaited, result is a string.
  console.log(`current url = ${currentUrl}`);
});


text:
Q: Touchpad debugging - Opinion needed I'm trying to debug an odd touchpad problem with Ubuntu 14.04.4 on a Lenovo e460. I have followed this touchpad debugging tutorial, but it doesn't directly address the symptoms I am experiencing.
Sometimes when I start the computer, the touchpad doesn't work at all. When this happens, "cat /proc/bus/input/devices" shows no entry at all for a touchpad/mouse/pointer. No matter how many times I restart, the result is the same. It is also the same for all three kernel versions I have installed (4.2.0-27, 4.2.0-35, and 4.3.6-040306). However, if I connect a USB mouse, the mouse works fine.
If I pull my single-boot Ubuntu SSD and reinstall the Windows hard drive that came with the computer, the touchpad works just fine in Windows. And, if I then put the Ubuntu SSD back into the computer and start Ubuntu, the touchpad starts working again.
This has happened twice in a month. It does not happen immediately after updates, other software changes, or changes to BIOS/UEFI configuration. And there are no touchpad/pointer-related settings in the BIOS/UEFI.
I am at a loss. Any ideas?


text:
Q: Find Azure AD groups that have a sensitivity label applied We have a requirement to check any group that has used a particular sensitivity label.
I've looked at the Advanced query capabilities on Azure AD directory objects to try to build a filter clause, but I haven't had any luck.
Is this possible? There are +10,000 groups in this tenant, so it's not ideal to call the list groups endpoint without a filter.

A: Here are the Microsoft Graph service-specific throttling limits:

Please refer this document for reference:https://learn.microsoft.com/en-us/graph/throttling-limits#pattern
Hope this helps.


text:
Q: Call to a member function success() on boolean in CakePHP I am running into a problem with CakePHP 3.0 that does not make sense to me and would like your help solving. I am having a table name called users with a controller named the same (UsersController). I can view the users in the table without any problem, but when I insert, modify or delete a user I am getting an error.
When I do an insert I get the error message: Call to a member function success() on boolean UsersController.php on line 56
If I look into the controller class it looks like
public function add()
{
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->data);

        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));

            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('user'));
    $this->set('_serialize', ['user']);
}

Line 56 is $this->Flash->success(__('The user has been saved.'));
The user is inserted, updated or deleted from the database (depending on the requested action)
What is puzzling me is why would the code return an error and most important is, how could I solve this?
Thank you very much for your time.

A: It seems that the Flash component is not loaded in the parent class AppController. Therefor you need to either add it manually to the AppController or to your custom controller class, in my case UsersController.
In case you want to add it to the parent class AppController open the AppController file and add the following PHP code snipper in side of the class.
public function initialize()
{
    $this->loadComponent('Flash');
}

Incase you want to load the Flash component only in your custom class then add the following code snipper inside your custom class.
public function initialize()
{
    parent::initialize();
    $this->loadComponent('Flash');
}

This will make the Flash component available to you and removed the error as described in the initial post.


text:
Q: How can I do calculations in base 12 in PHP I have built a simple modular scale calculator, where I can enter a base number (say font size or line height) and an important number (maybe column width, page width, or another font size) and select a ratio (golden ratio for example) and the calculator will display a double stranded scale for use in page layout. see example below
I have been toying with the idea of allowing users to input points and picas and then displaying the scale in one or the other.
The problem is that picas are base 12 numbers (12 points to a pica), I figured if I could just convert the input (something like 16p6) to base 12 I could do the calculation and go from there.
I just can't work out how to do basic calculations in another base. I'm really just messing around to see what I can come up with, let me know if you think I'm barking up the wrong tree.
So my question is this how do I do calculations in base 12?
<?php
// basic modular scale calculation
$goldenRatio = 1.618;
$baseNumber = 16;

$i = 0;
while ($i <= 10) {
    echo round($baseNumber,1). "
";
    $baseNumber = $baseNumber * $goldenRatio;
    $i++;
}

echo "

";

// Attempt at base 12 calculation

$a=base_convert(16,10,12);
$b=base_convert(12,10,12);

$r = ($a*$b);

echo $a."*".$b."=";
echo $r;

I'm really just messing around to se what I can come up with, let me know if you think I'm barking up the wrong tree.
Update
To solve the problem of converting Picas to base points from a string like '12p6' I ended up using regex to first test if Picas and Points had been supplied the split the Picas and Points.
function isPica($data) {
    if (preg_match('/^[0-9]+(?i)p([0-1]?[0-9])?$/i',$data)) {
        return true;
    }
    return false;
}

function makePoints($data) {
    $data = preg_replace('/^([0-9]+)((?i)p)(([0-1]?[0-9])?)$/i','$1.$3',$data);
    $data = explode('.',$data);
    $points = floor($data[0] * 12);
    $points = $data[1] + $points;
    return $points;
}

Modular Scale Calculator
Git Hub — Modular Scale Calculator

A: base_convert just converts the string representation. You can't do calculations using strings of numbers in base 12 in php. When dealing with imperial units, you usually have multiple "bases" to deal with. So it has to be done manually. When you're doing calculations, the base doesn't matter.

*

*Convert all the different units to the smallest one (points). $a = 3*12 + 7;//3picas, 7points.

*Do the calculations.

*Convert back to original units.
$points = (int)$val % 12;
$picas = (int)($val / 12);
or
$picas = floor($val / 12);
$points = $val - 12*$picas;


text:
Q: Command-delete shortcut is not working for me How do you delete a file you have selected in a Finder window, without using the mouse?
delete doesn't do it.
When I looked it up, I was said that command-delete is supposed to do it, but it doesn't work for me.

A: It should work in Finder by default, but did you press the right delete key?

*

*Delete (⌫) is the key that is called backspace on other platforms

*Forward delete (⌦) is the key that is called delete on other platforms

A: *

*Look into "System Preferences → Keyboard keys" and make sure Command is enabled and mapped to the Cmd key. Check also custom shortcuts in the "Keyboard Shortcuts" panel.

*Go to Finder, select a file, open the "File" menu and see what shortcut is associated to "Move to Trash".

A: tl;dr: If ⌘-delete doesn't work, try ⌘-⌥-delete (command-option-delete) instead.
I had this problem on a new iMac with a standard Apple keyboard running the latest version of OS X (Mavericks 10.9.3 as of this writing). This was driving me crazy because I use ⌘-delete frequently, and I often switch between the iMac and my MacBook Air (running the same version of OS X) on which ⌘-delete works fine. I just discovered by chance and desperation that, for some reason, ⌘-⌥-delete (command-option-delete) does work. It's not as good as having the same keystrokes work on both machines, but at least now there's some keyboard shortcut I can use on the iMac.
UPDATE: For no apparent reason, ⌘-delete has started working.

A: I had the same problem. Later I discovered that it was my own mistake. But also a mistake from Apple. On the extended keyboard with numeric pad there is a button says DELETE. (It's not on the short wireless keyboard) This is NOT the delete button for the combination Cmd-Delete. You have to use the button with the backarrow! So Cmd-Backarrow.

A: I experience that before. and my accidental solution is command + delete after that press command + backspace.

A: This may not help many, but here is how I restored "Command+delete".
A while back, I was convinced that this key combination for "Move to Trash" was not working in my macOS Sierra. So, in System Preferences > Keyboard > Shortcuts > App Shortcuts, I attempted to manually define a shortcut "Move to Trash". But, I was never allowed to assign the same "Command+delete" key combination.
A frustrating few weeks have passed until this morning. But, this morning, I was determined to restore "Command+delete" and once again went into the App Shortcuts pane. There, it occurred to me to DELETE the very shortcut and key combination I had been trying to define. So, I selected my "Move to Trash" Finder shortcut and clicked on the "minus" button to delete it.
Upon returning to the Finder, I was stunned to see "Command+delete" appearing to the right of "Move to Trash" again.
So, if you have tried many things to restore the "Command+delete" key combination for "Move to Trash", one thing I would like for you to try is this:

*

*In System Preferences > Keyboard > Shortcuts > App Shortcuts, create a Finder shortcut for "Move to Trash" and assign whatever key combination that the system accepts.

*Go back to the Finder and confirm that your key combination works.

*Now, return to the App Shortcuts pane, select the shortcut you created, and press the "minus" sign to delete the shortcut.

*Go back to the Finder and see if "Command+delete" has return to "Move to Trash.

A: For Macs (Macbooks only) using Logitech MX series, perm delete shortcut is: Cmd+Opt+Del (macOS is Monterey v12.X)

A: I accidentally discovered that Fn + Delete did the job for me in macOS Sierra.

A: Command-backspace seems to work.  But lots of confusion is caused by the fact that Apple insists on being "special" when it comes to backspace and delete keys.
Let's be clear, the ASCII standard has a BS (ASCII code 08) and DEL (ASCII code 127).
Most keyboards have both a key labelled Backspace, and a key labelled Delete.  (Or something similar.)
Most systems (Windows, Linux, etc.) interpret the Backspace key to mean "Delete the character left of the cursor," and Delete means "Delete the character under, or to the right of, the cursor".
On my mabook pro keyboard (which I almost never use), there is only a Delete key.  It functions as the rest of the universe expects Backspace to work.

A: CmdOptBkSp did it for me for macOS Monterey with a 101+ keyboard.


text:
Q: C random number generator making the same number How do i get the random number generator in c to give me different numbers when ever my function is called.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {

printf("%i",num());
printf("%i",num());

}
int num() {
    int MAX = 100;
    srand ( time(NULL));
    int num = rand() % MAX;
    return num;
}

No matter how many times i call the num function, it always prints the same number. How do i fix this so the number is different for every call.

A: The time function typically returns the time in second resolution, which means that if you call time(NULL) twice within one second then you will get the same result.
That will of course mean that you set the same starting seed to the random-number generator, which means the sequence will be the same.
You typically only call srand once, early in the main function.

A: Move
srand ( time(NULL));

to main() . You need to call srand() once in main() and keep calling rand()


text:
Q: Update field permission in permission set via Apex I am trying to expose a REST API so the field permission of permission set(s) can be updated.
I am trying to use MetadataService as below:
@RestResource(urlMapping='/updateFieldPermission')
global class UtilitiesAPI {
    @HttpPost
    global static String updateFieldPermission(List<FieldPermisionPutRequestWrapper> fieldPermisionPutRequestWrapperList){
        try{
            System.debug('Started updateFieldPermission');

            MetadataService.MetadataPort service = new MetadataService.MetadataPort();
            Map<String, FieldAccess> objectFieldToFieldAccessMap = new Map<String, FieldAccess>();
            service.SessionHeader = new MetadataService.SessionHeader_element();
            service.SessionHeader.sessionId = UserInfo.getSessionId();

            return null;
        }
        catch(Exception exceptionObject){
            System.debug('Exception occurred. Error message=' + exceptionObject.getMessage());
            System.debug('Stack trace=' + exceptionObject.getStackTraceString());
            return null;
        }
    }
}

But getting error like this:
16:23:51.781 Starting SFDX: Deploy Source to Org

=== Deploy Errors
PROJECT PATH                                     ERRORS
───────────────────────────────────────────────  ───────────────────────────────────────────────────────────
force-app\main\default\classes\UtilitiesAPI.cls  Invalid type: MetadataService.MetadataPort (7:13)
force-app\main\default\classes\UtilitiesAPI.cls  Invalid type: MetadataService.SessionHeader_element (9:37)
force-app\main\default\classes\UtilitiesAPI.cls  Variable does not exist: service.SessionHeader (10:13)
force-app\main\default\classes\UtilitiesAPI.cls  Variable does not exist: service (9:13)

16:23:54.589 ended SFDX: Deploy Source to Org

Can someone please help me know what I am missing here or should try other approach?

A: I have two ways to resolve your problem -

*

*Via Metadata Api using the library from FinancialForce, your errors are showing that you haven't imported the library.
you can get it at - https://github.com/financialforcedev/apex-mdapi/tree/master/apex-mdapi/src/classes
All you need to do is copy the MetadataService class and save it into your org.
once done add the below method to your UtilitiesAPI class-

    public static MetadataService.MetadataPort createService()
        {
            MetadataService.MetadataPort service = new MetadataService.MetadataPort();
            service.SessionHeader = new MetadataService.SessionHeader_element();
            service.SessionHeader.sessionId = UserInfo.getSessionId();
            return service;
        }

Now, your errors will be resolved.
Get the profile and update custom permission -

       MetadataService.MetadataPort service = createService();
        MetadataService.Metadata[] records = readResult.getRecords();
        MetadataService.Profile prfile =  new MetadataService.Profile();
        prfile.fullName = 'profile name';
        prfile.custom = false;
       MetadataService.ProfileFieldLevelSecurity fieldSec = new MetadataService.ProfileFieldLevelSecurity();
            fieldSec.field='Account.Phone';
            fieldSec.editable=false;
            prfile.fieldPermissions  = new MetadataService.ProfileFieldLevelSecurity[] {fieldSec} ;
                List<MetadataService.SaveResult> results =
                service.updateMetadata(
                    new MetadataService.Metadata[] { prfile });
            handleSaveResults(results[0]);

    public static void handleSaveResults(MetadataService.SaveResult saveResult)
        {
            // Nothing to see?
            if(saveResult==null || saveResult.success)
                return;
            // Construct error message and throw an exception
            if(saveResult.errors!=null)
            {
                List<String> messages = new List<String>();
                messages.add(
                    (saveResult.errors.size()==1 ? 'Error ' : 'Errors ') +
                    'occured processing component ' + saveResult.fullName + '.');
                for(MetadataService.Error error : saveResult.errors)
                    messages.add(
                        error.message + ' (' + error.statusCode + ').' +
                        ( error.fields!=null && error.fields.size()>0 ?
                         ' Fields ' + String.join(error.fields, ',') + '.' : '' ) );
                if(messages.size()>0)
                    System.debug(' message '+messages);
            }
            if(!saveResult.success)
                System.debug(' failure ');
        }

*Via FieldPermission - I can't say this will be a perfect solution but it'll allow you to add and update the permission -

Add Permission -
FieldPermissions fp= new FieldPermissions();
fp.Field='Account.Phone';//the name of new field
fp.ParentId='0PS5g000009W5BH';// id of permission set
fp.PermissionsEdit=true;//
fp.PermissionsRead=true;
fp.SobjectType='Account';
Insert fp;

Update Permission -
FieldPermissions fps = [SELECT SobjectType, Field, PermissionsRead, Parent.Name FROM FieldPermissions WHERE SobjectType='Account' AND Field='Account.Phone' AND ParentId='0PS5g000009W5BH' LIMIT 1];
fps.PermissionsEdit = false;
update fps;

To grant a user access to a field, associate a FieldPermissions record with a PermissionSet that's assigned to a user. FieldPermissions records are only supported in PermissionSet, not in Profile.


text:
Q: session-manager plugin on amazon linux 2 not found Following the docs for installing the session-manager-plugin:
https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html
On Amazon linux 2:
curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_64bit/session-manager-plugin.rpm" -o "session-manager-plugin.rpm"

sudo yum install -y session-manager-plugin.rpm

session-manager-plugin
bash: session-manager-plugin: command not found

A: The command is probably not in your path. Try /usr/local/bin/session-manager-plugin.


text:
Q: Is shared object compiled for 32bit or 64bit machine? Is there a command in Linux that we can run on a compiled shared object(.so) in /usr/lib and know whether it is compiled for 64 bit or 32 bit system? (I mean to know ELF class, like ELFCLASS32)

A: You can use the file command. E.g.:
[myuser@mycomputer]$ file /usr/lib/libcurl.so.4.1.1
/usr/lib/libcurl.so.4.1.1: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped


text:
Q: sysfs folder symbolic link behavior I encountered this behavior that I can't explain. In the sysfs, there is a symbolic link but it looks impossible to me:
me@test:/sys/block/sde$ ll
...
lrwxrwxrwx 1 root root    0 Oct  1  2019 device -> ../../../8:0:0:0
...

me@test:/sys/block/sde$ cd ../../../8:0:0:0
me@test:/sys/devices/pci0000:00/0000:00:17.0/usb2/2-1/2-1:1.3/host8/target8:0:0/8:0:0:0$

but obviously three level up gets me to the root folder, so how does this happen?
me@test:/sys/block/sde$ cd ../../../
me@test:/$

A: Had the same question. The symbolic link to /sys/block/sda/device is relative to /sys/devices because /sys/block/sda is itself a symbolic link. Examples:
SATA drive connected to a USB -> SATA adapter
# ls -l /sys/block/sda
/sys/block/sda -> ../devices/pci0000:00/0000:00:08.1/0000:06:00.3/usb5/5-2/5-2.2/5-2.2:1.0/host0/target0:0:0/0:0:0:0/block/sda/

# readlink /sys/block/sda/device
../../../0:0:0:0

# readlink -e /sys/block/sda/device
/sys/devices/pci0000:00/0000:00:08.1/0000:06:00.3/usb5/5-2/5-2.2/5-2.2:1.0/host0/target0:0:0/0:0:0:0

/sys/block/sda is a symlink to that device in /sys/devices, so
when you apply ../../..../ to that full path it gets you to /sys/devices/pci0000:00/0000:00:08.1/0000:06:00.3/usb5/5-2/5-2.2/5-2.2:1.0/host0/target0:0:0/, within which is the 0:0:0:0 directory referenced by the suffix of the /sys/block/sda/device symlink.
Side note: /sys/devices is derived from the UDEV path for that device, which can be obtained via udevadm:
# udevadm info --query=path /sys/block/sda
/devices/pci0000:00/0000:00:08.1/0000:06:00.3/usb5/5-2/5-2.2/5-2.2:1.0/host0/target0:0:0/0:0:0:0/block/sda

Another example, this time for an NVME drive that's attached to a planar (motherboard) NVMe port:
# ls -l /sys/block/nv*
/sys/block/nvme0n1 -> ../devices/pci0000:00/0000:00:02.1/0000:01:00.0/nvme/nvme0/nvme0n1/

# readlink /sys/block/nvme0n1/device
../../nvme0

# readlink -e /sys/block/nvme0n1/device
/sys/devices/pci0000:00/0000:00:02.1/0000:01:00.0/nvme/nvme0

# udevadm info --query=path /sys/block/nvme0n1
/devices/pci0000:00/0000:00:02.1/0000:01:00.0/nvme/nvme0/nvme0n1


text:
Q: Backbone: Multiple views subscribing to a single collection's event? Is this a bad practice? I have a question, really basic stuff I think but:
I've only seen examples with a collection view and single view dependent on a collection being updated.  What if you have multiple views trying to subscribe to a collections events, ie reset, addOne, addAll etc...
Am I missing some point about doing/not doing this? Do you have any examples of this? Does that even make sense?
Any info is MUCH appreciated
    var Coll = Backbone.Collection.extend({
        model: SingleModel,
        url: 'service',
        initialize: function(){
            console.log('collection inited')

        }

    });

    var SingleModel = Backbone.Collection.extend({});

    var CollView = Backbone.View.extend({
        el: 'ul',
        template: Handlebars.compile(someContainerTemplate),
        init: function(){
            _.bindAll(this, 'render', 'addAll', 'addOne');
            this.collection.bind("reset", this.addAll);

            this.collection.fetch();
        },
        render: function(){
            $(this.el).append(this.template())
        },

        addAll: function(){
            this.collection.each(this.addOne);
        },

        addOne: function(model){
            var view = new SingleView({ model: model })
        }
    })

    var SingleView = Backbone.View.extend({
        tagName: "li",
        events: {
            "click .delete": "remove"
        },
        template: Handlebars.compile(someTemplateForSingleItem),
        initialize: function() {
        _.bindAll(this,'render');

            this.model.bind('save', this.addOne);
            this.model.bind('destroy', removeEl);
        },

        remove: function(){
          this.model.destroy();
        },

        removeEl: function(){
          $(this.el).remove();
        },

        render: function() {
            var context = this.model.toJSON();
            return $(this.el).append(this.template(context));
        },
    })

    // standard so far (excluding any bad practices),
    // but what if you have another view dependent on
    // say the number of length of the collection, and
    // you want it to update if any single models are destroyed

    var HeaderView = Backbone.View.extend({
        tagName: "div#header",
        template: Handlebars.compile(someHeaderTemplate),
        initialize: function() {
        _.bindAll(this,'render');

        this.model.bind('save', this.addOne);
        },

        render: function() {
            //assigning this collection length

            var context = this.collection.length;
            return $(this.el).append(this.template(context));
        },
    });

    var coll = new Coll();
    new CollView({ collection: coll });
    new HeaderView({ collection: coll});

A: What you're doing is perfectly fine and part of the reason for using Backbone. From the Backbone introduction:

Whenever a UI action causes an attribute of a model to change, the model triggers a "change" event; all the Views that display the model's state can be notified of the change,

Note that they say "all the Views", not "the view".
One example of multiple views for a single collection would be a chat system. Suppose you have a collection of users that are online; then you might have one simple view in the header that displays the number of people that are online and another view (of the same collection) that lists the users:
var User = Backbone.Model.extend({});
var OnlineUsers = Backbone.Collection.extend({
    model: User
});

var CounterView = Backbone.View.extend({
    tagName: 'span',
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.on('add', this.render);
        // other interesting events...
    },
    render: function() {
        this.$el.text(this.collection.size());
        return this;
    }
});
var ListView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.on('add', this.render);
        // other interesting events...
    },
    render: function() {
        var html = this.collection.map(function(m) {
            return '<p>' + m.get('name') + '</p>';
        });
        this.$el.html(html.join(''));
        return this;
    }
});

Then you'd have one OnlineUsers instance but both your CounterView and ListView instances would be watching it. When people come online or go offline, both views will be updated as desired.
Simple demo: http://jsfiddle.net/ambiguous/eX7gZ/
The above example situation sounds like exactly the sort of thing you're doing and it is exactly the sort of thing that Backbone is for. Good job.

A: We had the same problem. We needed to use multiple jQuery Templates with unique internal events for each model without using multiple holder views. This is the solution that we came up with:
var myHolderView = Backbone.View.extend({
    el: '#views',
    render: function(){
        // This is because 'this' change inside the collection.each
        var $this = this;

        // If you want a wrapper template
        var wrapperHtml = $('#view-wrapper-template').tmpl();
        $this.$el.append(wrapperHtml);
        $wrapper = $this.$el.find('> div'); // If wrapper is a div

        $this.collection.each(function(model){
            // Render and append the viewA with internal events
            var viewA = new myViewA({model: model});
            viewA.render();

            // Use this to add the views content (viewA.el) to this views element ('#views')
            //$this.$el.append(viewA.el);

            // Use this to add the view content (viewA.el) to this views wrapper element ($wrapper)
            $wrapper.append(viewA.el);

            // Render and append the viewB with internal events
            var viewB = new myViewB({model: model});
            viewB.render();
            //$this.$el.append(viewB.el);
            $wrapper.append(viewB.el);

            // Add more views here...
        });
    }
});

Full source and working example:
http://jsfiddle.net/HLv5z/9/


text:
Q: In-App Purchase Dynamic Subscription Price I'm currently releasing our new app and it's using a subscription-based to avail the premium version of the app. But the price of the subscription will be based on how many products the user avail on that subscription. For example, the user subscribes for 5 products, so the recurring bill will be 5 x $10 (Price per product) = $50. Can this be obtained via IAP of Apple? I'm currently using Stripe as payment gateway to handle this but the app was rejected due to
"3. 1.1 Business: Payments - In-App Purchase". Any suggestions will be good. Thanks!

A: The prices of products in App Store Connect must be fixed, so you would need to create a unique product Id for every quantity of products that the user could subscribe to.


text:
Q: Is complexity of the following two recurrances same? I have two recurrance relations as:
T(n) = T(n/2) + c       // complexity O(logn)

T(n) = 2T(n/2) + c      // is the complexity O(logn)????

c is a constant in both case i.e. we are doing constant work in the merge part of recurrance.
First recurrance is of Binary Search where we are continuously discarding one half of array.
Let say second recurrance finds the max element from an array that is unsorted and we are dividing the array in two parts in each step, then comparing the result of each part to give a single max value.
In the first case we are not traversing the whole array. In the second we are traversing the whole. Now if i build a recursion tree for both i would get a complexity of O(logn) as the height of both the trees are same. If i am wrong please correct me. It is a confusion in my mind, so please help me clear it.

A: It's not the same complexity. The second one would be something like O(n)
A simple way to see this is to fix c = 0 and T(1) = a (whare a is a constant).
Then:
T(2) = 2T(1) = 2a
T(4) = 2T(2) = 4a
T(8) = 2T(4) = 8a
...
T(n) = n*a

You can see a linear complexity.


text:
Q: Cannot read property 'toJSON' of undefined + backbone I am really new to backbone, and in a world of confusion behind it. Right now I am trying to render a view of a single person, preferably without iterating through the entire collection, using the collection.get() method.
Here is the user collection:
App.Collections.UserCollection = Backbone.Collection.extend({
    url: "/users",
    model: App.Models.User,

    initialize: function(){
        console.log('users collection');
    },

});

The user model:
 App.Models.User = Backbone.Model.extend({
        rootURL: '/users',
        initialize: function(){
            console.log('User model being generated');
        }

    });

the Users View (all users):
App.Views.Users = Backbone.View.extend({
        el: "body",
        model: 'user',

        initialize: function(){
            console.log('User view rendering');
            this.collection.fetch();
            this.listenTo(this.collection, 'reset', this.addAll);
        },
        clearDiv: function(){
            var container = $('#render-area');
            $('body').removeClass('homepage');
            $('#main-nav').fadeIn(100);
            container.empty();
            this.addUser();
        },
        addUser: function(){
            var current_user_model = this.collection.get(currentUser);
            var user = new App.Views.ViewUser({ model: current_user_model });
            $('#render-area').append(user.el);
        },

        events: {
            'click #view-profile' : 'clearDiv'
        }

});

and the viewUser view (single user):
App.Views.ViewUser = Backbone.View.extend({

        initialize: function(){
            console.log("single user view");
            this.template = HandlebarsTemplates['user_profile'];
            this.render();
        },
        render: function(){
            $('#render-area').html(this.template(this.model.toJSON()));
        },
});

I thought that I was grabbing the single user model in the Users view, and passing it to the ViewUser view with these lines
var current_user_model = this.collection.get(currentUser);
var user = new App.Views.ViewUser({ model: current_user_model });

But it seems that I am not. Any help and/or explanation is appreciated, thanks!

A: did you check the this.collection.get is return an object?
Maybe it can not fetch the currentUser?
before render the view you should
a) check the model is a valid model before calling the view and render a "not found" view  or
b) in the view check if the model is valid and render a "not found" view
c) or you can handle it in handlebars template
Example A (untested):
var current_user_model = this.collection.get(currentUser);
if (current_user_model) {
    var user = new App.Views.ViewUser({ model: current_user_model });
} else {
    new AppViews.ViewUserNotFound();
}

Example B :
App.Views.ViewUser = Backbone.View.extend({

        initialize: function(){
            console.log("single user view");
            this.template = HandlebarsTemplates['user_profile'];
            this.templateNotFound = HandlebarsTemplates['user_profile_not_found'];
            this.render();
        },
        render: function(){
            if(this.model) {
                $('#render-area').html(this.template(this.model.toJSON()));
            } else {
                $('#render-area').html(this.templateNotFound());
            }
        },
});
var current_user_model = this.collection.get(currentUser);
var user = new App.Views.ViewUser({ model: current_user_model });

Example C:
App.Views.ViewUser = Backbone.View.extend({

        initialize: function(){
            console.log("single user view");
            this.template = HandlebarsTemplates['user_profile'];
            this.templateNotFound = HandlebarsTemplates['user_profile_not_found'];
            this.render();
        },
        render: function(){
            if(!this.model) {
                this.model = new this.model(); // create model with defaults
            }
            $('#render-area').html(this.template(this.model.toJSON()));
        },
});
var current_user_model = this.collection.get(currentUser);
var user = new App.Views.ViewUser({ model: current_user_model });

all examples untested..
hope this helps a little bit,
best Carsten

A: I would do that:
App.Views.Users = Backbone.View.extend({
        el: "body",
        model: 'user',

        initialize: function(){
            console.log('User view rendering');
            this.listenTo(this.collection, 'reset', this.addAll);
        },
        clearDiv: function(){
            var self = this;
            this.collection.fetch({
               success: function() {
                   var container = $('#render-area');
                   $('body').removeClass('homepage');
                   $('#main-nav').fadeIn(100);
                   container.empty();
                   self.addUser();
               }
            });
        },
        addUser: function(){
            var current_user_model = this.collection.get(currentUser);
            var user = new App.Views.ViewUser({ model: current_user_model });
            $('#render-area').append(user.el);
        },

        events: {
            'click #view-profile' : 'clearDiv'
        }

});


text:
Q: LandSat Land Surface Temperature - Python I'm trying to determine if my code for determining land surface temperature is correct.  The imagery contains a fire in the middle of October with snow mixed in so temperatures show be nice and contrasting but when I go to view the created image in QGIS, the image is showing up as black.  I realize that this doesn't mean there isn't anything there, I just want to make sure it's the code that is or is not the issue.
import os
import rasterio
import glob
from rasterio.merge import merge
import matplotlib.pyplot as plt
from rasterio.plot import show
import numpy as np

# Directory
# These directories are listed as "A" and "B" because one image doesn't cover the
# area of interest. So there are two sets and we will mosaic them later. "A" and "B"
# don't mean anything more than to organize them and show they are two different datasets

# Band Specifications - Surface Reflectance
# Band 1 = Coastal Aerosol
# Band 2 = Blue
# Band 3 = Green
# Band 4 = Red
# Band 5 = NIR
# Band 6 = SWIR 1 (1.57 - 1.65)
# Band 7 = SWIR 2 (2.11 - 2.29)

# Thermal Band
# Band 10 = TIRS 1 (10.6 - 11.19)

# Lists and Bands
# I decided to read in all of the bands from the datasets before the scripts that create
# our products for analysis before the section that would create those products.  This
# was done so that access to all the data is in one place rather than sporadically located
# throughout the script.  This way also ensures common and organized variable naming
# conventions.

# Like the "A" and "B" directories, the lists and bands are named to match the directory.

duringA = [
    'LC08_L2SP_035031_20201013_20201105_02_T1_SR_B1.TIF',
    'LC08_L2SP_035031_20201013_20201105_02_T1_SR_B2.TIF',
    'LC08_L2SP_035031_20201013_20201105_02_T1_SR_B3.TIF',
    'LC08_L2SP_035031_20201013_20201105_02_T1_SR_B4.TIF',
    'LC08_L2SP_035031_20201013_20201105_02_T1_SR_B5.TIF',
    'LC08_L2SP_035031_20201013_20201105_02_T1_SR_B6.TIF',
    'LC08_L2SP_035031_20201013_20201105_02_T1_SR_B7.TIF',
    'LC08_L2SP_035031_20201013_20201105_02_T1_ST_B10.TIF'
    ]

duringAband1= rasterio.open(os.path.join(duringDirA, duringA[0]), mode = 'r')
duringAband2= rasterio.open(os.path.join(duringDirA, duringA[1]), mode = 'r')
duringAband3= rasterio.open(os.path.join(duringDirA, duringA[2]), mode = 'r')
duringAband4= rasterio.open(os.path.join(duringDirA, duringA[3]), mode = 'r')
duringAband5= rasterio.open(os.path.join(duringDirA, duringA[4]), mode = 'r')
duringAband6= rasterio.open(os.path.join(duringDirA, duringA[5]), mode = 'r')
duringAband7= rasterio.open(os.path.join(duringDirA, duringA[6]), mode = 'r')
duringAband10= rasterio.open(os.path.join(duringDirA, duringA[7]), mode = 'r')
# 1.) TOA

# Radiance Multiplicative rescaling factor.
rmb= 3.3420E-04

#radiance additive rescaling factor
rab = 0.10000

#band 10 'A' top of atmostphere
b10ATOA = (duringAband10.read()*rmb)+rab

# 2.) Conversion of radiance at sensor (BT))
#BT = (k2)/(np.log((k1/TOA)+1))

k1 = 774.8853
k2 = 1321.0789

bT1 = ((k2)/(np.log((k1/b10ATOA)+1))-273.15)

# 3.) Calculate NDVI

# ndvi = ((nir(band5) - red(band4))/(nir(band5) + red(band4)))

#ndvi
ndvi1 = ((duringAband5.read() - duringAband4.read())/(duringAband5.read() + duringAband4.read()))

# 4.) Calculate the proportion of vegetation (pv))

#pv = square((ndvi - ndvi.min)/(ndvi.max - ndvi.min))
pv1 = np.sqrt(((ndvi1 - np.min(ndvi1))/(np.max(ndvi1) - np.min(ndvi1))))

# 5.) Calculate Land Surface Emissivity
# referred to as 'e' for emissivity
# Equation
# 0.004 * pv + 0.986

# emissivity 1
e1 = 0.004 * pv1 + 0.986

# Land Surface Temperature
lst1 = (bT1 / (1 + (0.00115 * bT1 / 1.4388) * np.log(e1)))

#creating the tifs
#LST 1 stack
lst1file = rasterio.open(
    os.path.join(duringTempDir, 'lst1file.tif'), mode = 'w',
    driver = 'GTiff',
    height = '7981',
    width = '7871',
    count = 1,
    dtype = 'float64',
    crs = duringAband10.crs,
    transform=duringAband10.transform
    )

lst1file.write(lst1[0], 1)
lst1file.close

lst1file = rasterio.open(os.path.join(duringTempDir, 'lst1file.tif'), mode = 'r')


text:
Q: Scrolllock controller, switch shortcut if else Halo,
i want to program for cmd, powershell, VBS which working as switch for Scroll lock key. If schroll lock is off my ethernet interface is on and wlan interface is off, else scroll lock is on, ethernet is off and wlan is on. And after this program install as service to computer.
Is something like that possible and functiona?
Thnx for all answer.

A: Halo all!
I solved my problem, use AutoHotKey with my progam:
~ScrollLock::  ; detect ScrollLock without blocking it (~)
if (GetKeyState("ScrollLock", "T"))  ; get the toggle-state of ScrollLock
    Run, "C:\Users\%username%\desktop\off.bat"
else
    Run, "C:\Users\%username%\desktop\on.bat"

Have a nice day


text:
Q: Python strptime : time data 'January 03 2017' does not match format '%b %d %Y' dateCreated = datetime.strptime(item['dateCreated'].replace(',',''), '%b %d %Y')

^^ code ^^
Python strptime : time data 'January 03 2017' does not match format '%b %d %Y'

^^ error ^^
Running Python 2.7
I know that similar questions have been asked, but none of the answers matched my situation.

A: Take a closer look at the docs (emphasis mine):

%b - Month as locale's abbreviated name. (Jan, Feb, …, Dec)
%B - Month as locale's full name. (January, February, …, December)

You want '%B %d %Y', not '%b %d %Y'.

A: %b is for the abbreviated month name.  You want %B.


text:
Q: How correctly aggregate and lookup mongo data to models Consider two collections:

*

*users (can be both, organizer and participant in other meetings)

*meetings

For the sake of simplicity, I show here only the basic data, in my code i have emails, passwords, etc.
User (easier part)
{ "_id": "ObjectId('user0_id')", "username": "Paul" }

and model:
type User struct {
    Id primitive.ObjectID `bson:"_id" json:"id,omitempty"`
    Username string `json:"username"`
}

Meeting:
{
  "_id": "ObjectId('meeting0_id')",
  "organizer": "ObjectId('user0_id')",
  "participants": [ "ObjectId('user1_id')", "ObjectId('user2_id')", "ObjectId('user3_id')"]
}

and model:
type Meeting struct {
    Id primitive.ObjectID `bson:"_id" json:"id,omitempty"`
    Organizer primitive.ObjectID `json:"organizer"`
    Participants []primitive.ObjectID  `json:"participants,omitempty"
}

Everything works if I extract only the basic data from mongo, but it seems ineffective...  Because if I want to present this data in a readable form, I can't use only ObjectID, but with mongo "$lookup" I would like to get more data about users right away.
Another problem, in some cases I need a different dataset. Once to show a list I need only
the name of the users assigned to the meeting.
However, in the case of data administration or sending notifications, I need more (all?) User data.
How to correctly (what are the best practices) to store data like this in Go models?
Create one super-struct "meeting" with all possible data? Eg.with Participants []User instead of ID's ?
But what next? Get a complete set of data from the database each time, then filter it on the code side? Or filter on mongo side, but in most cases almost all fields in struct will be empty (eg. LastPasswordChangeDate in simple meeting participants list). Especially since there may be more "lookup" data, e.g. meeting place, invitations, etc., etc.
How finally save this super struct to two collections?
P.S. Create different models for different "views" of meetings seems super stupid...


text:
Q: Exception Exception is not compatible with throws clause in Server.main(String[]) I'm running the Lip reading code on Eclipse Indigo from the following link :
https://github.com/sagioto/LipReading/blob/master/lipreading-core/src/main/java/edu/lipreading/WebFeatureExtractor.java
package main.java.edu.lipreading;

import com.googlecode.javacpp.BytePointer;
import com.googlecode.javacv.cpp.opencv_core;
import main.java.edu.lipreading.vision.AbstractFeatureExtractor;
import main.java.edu.lipreading.vision.NoMoreStickersFeatureExtractor;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.logging.Logger;

import static com.googlecode.javacv.cpp.opencv_core.CV_8UC1;
import static com.googlecode.javacv.cpp.opencv_core.cvMat;
import static com.googlecode.javacv.cpp.opencv_highgui.cvDecodeImage;

/**
 * Created with IntelliJ IDEA.
 * User: Sagi
 * Date: 25/04/13
 * Time: 21:47
 */
public class WebFeatureExtractor extends Server {

    private final static Logger LOG = Logger.getLogger(WebFeatureExtractor.class.getSimpleName());
    private final static AbstractFeatureExtractor fe = new NoMoreStickersFeatureExtractor();

    public WebFeatureExtractor(int port) {
        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(port);
        addConnector(connector);

        WebSocketHandler wsHandler = new WebSocketHandler() {
            public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
                return new FeatureExtractorWebSocket();
            }
        };
        setHandler(wsHandler);
    }

    /**
     * Simple innerclass that is used to handle websocket connections.
     *
     * @author jos
     */
    private static class FeatureExtractorWebSocket implements WebSocket, WebSocket.OnBinaryMessage, WebSocket.OnTextMessage {

        private Connection connection;

        public FeatureExtractorWebSocket() {
            super();
        }

        /**
         * On open we set the connection locally, and enable
         * binary support
         */
        @Override
        public void onOpen(Connection connection) {
            LOG.info("got connection open");
            this.connection = connection;
            this.connection.setMaxBinaryMessageSize(1024 * 512);
        }

        /**
         * Cleanup if needed. Not used for this example
         */
        @Override
        public void onClose(int code, String message) {
            LOG.info("got connection closed");
        }

        /**
         * When we receive a binary message we assume it is an image. We then run this
         * image through our face detection algorithm and send back the response.
         */
        @Override
        public void onMessage(byte[] data, int offset, int length) {
            //LOG.info("got data message");
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            bOut.write(data, offset, length);
            try {
                String result = convert(bOut.toByteArray());
                this.connection.sendMessage(result);
            } catch (Exception e) {
                LOG.severe("Error in facedetection, ignoring message:" + e.getMessage());
            }
        }

        @Override
        public void onMessage(String data) {
            LOG.info("got string message");
        }
    }
    public static String convert(byte[] imageData) throws Exception {
        opencv_core.IplImage originalImage = cvDecodeImage(cvMat(1, imageData.length, CV_8UC1, new BytePointer(imageData)));
        List<Integer> points = fe.getPoints(originalImage);
        if(points == null)
            return "null";
        String ans = "";
        for (Integer point : points) {
            ans += point + ",";
        }
        return ans;
    }

    /**
     * Start the server on port 999
     */
    public static void main(String[] args) throws Exception {
        WebFeatureExtractor server = new WebFeatureExtractor(9999);
        server.start();
        server.join();
    }
}

In the following line :
public static void main(String[] args) throws Exception {

I'm getting the following error :
Exception Exception is not compatible with throws clause in Server.main(String[])

Please help me solve this.

A: There are two condition you need to check.
1) when declaring a method in interface you need to add throws exception for that method and similarly with the interface implementation class where the method is implemented.
for example
service.java
@Component
public interface UserService {

    User getUser(Login login) throws Exception;
    }

serviceimpl.java
public User getUser(Login login)throws Exception
    {

       }

2) by doing the above statement the error still doesn't vanish. make sure to save both the files.

A: Doest the server API handle all exceptions for itself. Why not try removing the throws in your code. I know its not good programming practice but might solve the problem.

A: The problem is that the Server class you are extending already contains a public static void main(String[]) method that does not have the same throws declaration. I didn't take a look at it, but I'd bet that method doesn't throw anything at all.
A solution would be to remove your throws clause in your main method and rely on try-catches instead.
EDIT: Why you cannot add a different throws clause in your case.
Let's assume the following scenario:
class A {
    public static void foo() throws SomeException { ... }
}

class B extends A {
    public static void foo() throws DifferentException { ... }
}

The Java standard says you are hiding the A.foo() method (or at least trying to). Thing is, you're only allowed to do that if the throws clause in B.foo() is already contained in the clause of A.foo(). So for the above scenario, you're perfectly legal only if DifferentException is a subclass of SomeException. Otherwise the compiler will yell.

A: I had the same issue, in my case I have implemented a method from an interface that did not declared to throw an exception.
In your case, I would guess that Server class also has a main method that didn't throw an exception.  To quickly solve it.  I would declare Server.main to throw an exception.
This link helped me
What are reasons for Exceptions not to be compatible with throws clauses?


text:
Q: python asyncio task not executing in Parallel I am creating async task so they can execute in Parallel like this
 for symbol in config.symbol_list:
                    tasks.append(asyncio.ensure_future(get_today_Data_async(symbol), loop=loop))
                loop.run_until_complete(asyncio.wait(tasks))

This is the task which i want to execute in Parallel
async def get_today_Data_async(symbol):

    periodType = 'day'
    period = 1
    frequencyType = 'minute'
    frequency = '1'
    use_last10_Min = False
    logging.info(f'Updating data {symbol} started...')
    try:
        logging.info(f'thread id - {threading.get_ident()} getting market data {symbol} periodType {periodType} period {period} frequencyType {frequencyType} frequency {frequency}')

        est = pytz.timezone('US/Eastern')
        if use_last10_Min:
            startDate = (datetime.datetime.now()- datetime.timedelta(minutes=10)).astimezone(tz=est).timestamp()
        else:
            startDate =(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)).astimezone(tz=est).timestamp()
        endDate = (datetime.datetime.now()+datetime.timedelta(hours=48)).astimezone(tz=est).timestamp()
        endDate = str(endDate).split('.')[0] + '000'
        startDate = str(startDate).split('.')[0] + '000'

        reqDict = {'apikey': '' + config.client_id + '@AMER.OAUTHAP','endDate': endDate, 'frequencyType': frequencyType,'frequency': frequency,
                   'startDate': startDate, 'needExtendedHoursData': usePreMarket}

        header = {'Authorization': 'Bearer ' + config.token['access_token'] + '', 'content-type': 'application/json'}
        logging.info(f"thread id - {threading.get_ident()} datetime check {symbol} {datetime.datetime.now()}   {reqDict}")
        with await tlock:
            resp = requests.get("https://api.tdameritrade.com/v1/marketdata/" + symbol + "/pricehistory", params=reqDict)
        logging.info(f'thread id - {threading.get_ident()} datetime check {symbol} {datetime.datetime.now()} {resp.status_code}')
        if resp.status_code == 200 and not resp.json()['empty']:
            candles = resp.json()['candles']
            logging.info(f"symbol candel {symbol} {frequencyType} {frequency} {period} {get_one_hour(resp.json()['candles'])}")
            if not usePreMarket:
                newcandles = []
                EST = pytz.timezone('us/eastern')
                time_ist_end = datetime.datetime.now(EST).replace(hour=16, minute=00, second=00)
                time_ist_start = time_ist_end.replace(hour=9, minute=30, second=00)
                for x in candles:
                    tmp_date = datetime.datetime.fromtimestamp((x.get('datetime') / 1000), tz=pytz.timezone('US/Eastern'))
                    if tmp_date > time_ist_start and tmp_date < time_ist_end:
                        newcandles.append(x)
                if len(newcandles) > 0:
                    process_price(symbol,newcandles)
            else:
                if len(candles) > 0:
                    process_price(symbol, candles)

        logging.info(f" symbol - {symbol} status code {resp.status_code} resp {resp.text}")

    except Exception as e:
        traceback.print_exc()
        logging.error(f'Error in getting price {e}')
    logging.info(f'Updating data {symbol} completed...')

But task is executing sequentially as producing following output
2020-10-14 20:22:43,293  - root - get_today_Data_async - 398 - INFO - Updating data AAPL started...
2020-10-14 20:22:45,066  - root - get_today_Data_async - 442 - INFO - Updating data AAPL completed...
2020-10-14 20:22:45,066  - root - get_today_Data_async - 398 - INFO - Updating data MSFT started...
2020-10-14 20:22:46,301  - root - get_today_Data_async - 442 - INFO - Updating data MSFT completed...
2020-10-14 20:22:46,301  - root - get_today_Data_async - 398 - INFO - Updating data AMZN started...
2020-10-14 20:22:47,573  - root - get_today_Data_async - 442 - INFO - Updating data AMZN completed...
2020-10-14 20:22:47,573  - root - get_today_Data_async - 398 - INFO - Updating data FB started...
2020-10-14 20:22:48,907  - root - get_today_Data_async - 442 - INFO - Updating data FB completed...
2020-10-14 20:22:48,907  - root - get_today_Data_async - 398 - INFO - Updating data GOOGL started...
2020-10-14 20:22:51,266  - root - get_today_Data_async - 442 - INFO - Updating data GOOGL completed...
2020-10-14 20:22:51,266  - root - get_today_Data_async - 398 - INFO - Updating data GOOG started...
2020-10-14 20:22:52,585  - root - get_today_Data_async - 442 - INFO - Updating data GOOG completed...
2020-10-14 20:22:52,585  - root - get_today_Data_async - 398 - INFO - Updating data JNJ started...
2020-10-14 20:22:54,041  - root - get_today_Data_async - 442 - INFO - Updating data JNJ completed...
2020-10-14 20:22:54,041  - root - get_today_Data_async - 398 - INFO - Updating data PG started...
2020-10-14 20:22:55,275  - root - get_today_Data_async - 442 - INFO - Updating data PG completed...
2020-10-14 20:22:55,275  - root - get_today_Data_async - 398 - INFO - Updating data V started...
2020-10-14 20:22:56,563  - root - get_today_Data_async - 442 - INFO - Updating data V completed..

It means task are executing in sequence. There are around 500 symbols. Can you please help me out so i can execute task in Parallel

A: In python there is theoretically no parallel execution at any given time.
Python's global interpreter lock (GIL) is a complex mechanism that I will not explain here, you can read about it if you would like, but it prevent python code to run in two different threads at the same time.
So why still use threading / parallel processing?
In Python, solving I/O (input output) problems, is a classic fit to parallel processing, il explain with an example.
If you have a code that make HTTP requests, because network data transfer is WAY slower than cpu processing, to make your code most efficient, you would rather make the request at one thread, than instead of making the program stuck and wait for response, continue make requests with other threads, than for each returning response, take care of the output you got from that response.
That's why in Python, a lot of problems probably should not be multithreaded, while in other languages it has some benefits.
One way you can achieve true parallel processing with python is with the multiprocessing module. But keep in mind that it will have more RAM usage than a normal python execution because you have multiple identical stacks in memory, and it will not necessarily will be quicker because it takes time to open and close processes.


text: Q: Creating an ArchLinux AUR Mirror possible? Is it possible, to mirror the AUR (Arch User Repository) like shown here for Setting up an offline AUR (mirror)? As an alternative would it be possible to use wget in some way?


text:
Q: Remote Access to Kubuntu from Windows I've got it to work so I can get to it with TightVNC but the Kubuntu machine keeps changing the password.  I want to have a fixed password for remote access to the machine which is there when it starts up.  At the moment I have to enter a password for the KDE Wallet and change the password for unattended remote access every time I restart the Linux box.  Can anyone suggest how I can get it to remember the password and or not require a password for or not use KDE Wallet?
Thanks.

A: In the official documentation for VNC servers, there's an entry about krfb which
seems to be the default vnc server for Kubuntu.
I'll assume this is what you're using.
It says:
To configure krfb, go to System Settings > Sharing > Desktop Sharing > Configure....

1. To set krfb to request access each time, tick Confirm uninvited connections before accepting

So, to get what you need (don't ask every time for a password ask every time the same configured password and not generating a different one every time), you should untick the option Confirm uninvited connections before accepting.
DISCLAIMER
Please make sure to setup a secure password on the Password field.
UPDATE
To make the password persist, the correct procedure for Kubuntu >= 17.10 looks like this:

*

*tick the option "Enable desktop sharing"

*set a password for desktop sharing

*tick the option "Enable Unattended Access"

*set the same password for unattended access

All settings will persist over KDE sessions.
In case the passwords cannot be changed in krfb, you can change them in kwallet.

A: Note that RDP would be the more natural solution over VNC. However, KRFB does not support RDP yet but only VNC. A corresponding feature request is here: https://bugs.kde.org/show_bug.cgi?id=455238


text:
Q: How can I get the text out of a  tag in Android WebView? I know nothing about HTML and I am learning Android WebView.

In my App, it displays a HTML file with WebView. In the html there is a line:

<textarea  cols=""  id="system_text" style=" border-style: none; border-width: 0px; width:300px; height:120px;"></textarea>

When the user click a button, I should store the user input somewhere. But I don't know how can I extract the text. I know how to get text from EditText, but I have no idea with WebView. Could anyone help me please?

A: You can use  JSOUP its an open source html parser then you can write like this String my_text = getElementByTagName("textarea").text();


text:
Q: How to map Enum 0 on hibernate for a String identifier I have a problem with a mapping of a Enum value.
In my Bonus.class I have the enum property Type with the enum class BonusType.
This is how I define my enum class (just enum definition, no methods or constructors are copied):
public enum EavType
{
  WORLDWIDE ("WORLDWIDE"),
  SIMPLE ("SIMPLE"),
  NOTVALID ("0");
}

So far so good. As far as I get a Bonus element of the type "WORLDWIDE" or "SIMPLE" from the DB there is no problem, but when I get a Bonus on the database with the type=0 I get an error:
Exception: java.lang.IllegalArgumentException: Unknown name value [0] for enum class [com.bosch.gam.commons.bo.remuneration.BonusType]

The problem is that I cannot set how the NOTVALID type is saved, the data I get from the database is created from another interface and they just save it as 0. I also should clarify that the Type column in the Bonus table is a VARCHAR2.
Now my question: is hibernate interpreting 0 as a number? How can I fix this?

A: If you can't use an AttributeConverters (baeldung jpa attribute converters) you can use the same approach within your bean.
In your class "Bonus":

*

*create a new field of type String, e.g. dbEavType

*map this new field to the database column "type"

*implements set and get of this new field to adapt the string value to the enum value of EavType doing the expected conversion (e.g. if setting "0" in dbEavType then set NOTVALID in eavType field)

This solution allows you to adapt the value as you want and don't break other layers of your application which can continue to use the enumeration.


text:
Q: git push heroku master error Permission denied (publickey) I am new to heroku and I can't push my rails project.
I can successfully login to heroku, and I have keys
 Keys
 ssh-rsa AAAAB3NzaC...oPiDGoh0Gt root@Slava-System-Product-Name

but when I git push heroku master I receive
 Permission denied (publickey).
 fatal: The remote end hung up unexpectedly

A:
A common key error is: Permission denied (publickey). You can fix this by using keys:add to notify Heroku of your new key.

heroku keys:add ~/.ssh/id_rsa.pub

https://devcenter.heroku.com/articles/keys
UPDATE, solution from the following blog post worked.

*

*Create a new public key
ssh-keygen -t rsa

*Upload to heroku
heroku keys:add /root/.ssh/id_rsa.pub


text:
Q: Is it possible to write C++ app for Samsung Smart TV with access to USB device Is there an easy howto on writing C++ app for Samsung Smart TV that should be able to run in background (so not an HTML/JS applet) and access /dev/ttyUSBx device plugged in the TV?
Do they have some API to access /dev/ttyUSBx or it will be a simple Linux app? Do they allow to load such apps? Is there a toolchain to compile such apps?

A: At least according to Samsung, "No."

Q: Do you support C++ in the SDK?
A: No, Samsung platform only supports web technologies based apps (JS, CSS, HTML, FLASH)

http://www.samsungdforum.com/Support/FAQList?page=1&faqCateID=2

A: In the SDK 4.5 will include Native Client technology, NaCl, Currently supported languages are C and C + +. For more information: http://www.samsungdforum.com/Guide/d17/index.html

A: For Samsung SmartTVs you cannot use C++, the only allowed language/technology is HTML/JavaScript/CSS and Flash (not used much).
Majority of the applications are JavaScript based.
Might be you can have some exclusive agreement with the Samsung, since e.g. Skype is most probably not developed in JavaScript and the AngryBirds I heard are C++ as well.
BR
STeN


text:
Q: How to reference the current active sublist in a recursive function on a list containing lists in Python? I need to be able to take lists containing strings and nested lists of strings like the following:
['parent', ['child', 'child2', ['grandchild', ['ggrandchild'], 'grandchild2'], 'child3'], '2parent', '3parent' ['3child', ['3grandchild']]]

And print strings for each parent, each parent-child, each parent-child-grandchild, etc.:
'parent'
'parent_child'
'parent_child2'
'parent_child2_grandchild'
'parent_child2_grandchild_ggrandchild'
'parent_child2_grandchild2'
'parent_child3"
'2parent'
...
etc

I have been able to get it to work to a depth of two nested levels with the following code:
def list_check(parsed_list):
    for item in parsed_list:

        if type(item) != list and prefix == []:
            prefix.append(str(item))
            print item

        elif type(item) != list and prefix != []:
            print prefix[0]+"-"+item

        elif type(item) == list:
            list_check(item)

        else:
            pass

But I'm struggling with getting it to work for arbitrary nesting depth. I've taken a basic approach of tracking the nesting depth through a stack, but my implementation is broken in an obvious way that I don't know how to fix.
It currently deletes what is in the stack even if there are still other children following. What I want it to do is only pop items out of the relevant stacks if the sublist is ending.
prefix = []
nesting_depth = []

def list_check(parsed_list):
    for item in parsed_list:

        if type(item) == list:

            nesting_depth.append('1')
            list_check(item)

        elif type(item) != list and prefix == []:
            prefix.append(str(item))
            print item

        elif type(item) != list and prefix != []: #this where i need another condition like 'and item is last in current sublist'
            print prefix[0:len(nesting_depth)]+"-"+item
            prefix.pop()

        else:
            pass

How do I reference something like 'if it's the last item in the current sublist of parsed_list' in a way that accommodates the recursion of the overall function?

A: A dictionary would be much better suited to your needs.  But here's what you can do with the data structure you have:
def format_tree(tree):
    prefix = ''
    for node in tree:
        if isinstance(node, basestring):
            prefix = node
            yield node
        else:
            for elt in format_tree(node):
                yield prefix + '_' + elt

A simple test:
>>> a = ['parent', ['child', 'child2', ['grandchild', ['ggrandchild']], 'child3']]
>>> print '\n'.join(format_tree(a))
parent
parent_child
parent_child2
parent_child2_grandchild
parent_child2_grandchild_ggrandchild
parent_child3

A: *

*You should pass in the path from the root node as an extra argument in the recursion.

*You are using the wrong datastructure; you want to be using dictionaries.

Example:
>>> tree = {1:{11:'a', 12:'b'}, 2:{22:'c'}}
>>> def visit(tree, path=[]):
...     if isinstance(tree, dict):
...         for node,subtree in tree.items():
...             visit(subtree, path=path+[node])
...     else:
...         leaf = tree
...         print(path, leaf)

>>> visit(tree)
[1, 11] a
[1, 12] b
[2, 22] c


text:
Q: Java/Android - Proper way to send and receive data at the same time through a socket I'm currently working on an android project that is a sort of P2P application (no central server, IP addresses are entered manually). I've already sorted out how two devices are able to connect to each other, but what I seem to be having trouble figuring out is the best way to send data back and forth with a socket.
Right now, I've got two separate threads, one for sending data, and one for receiving data so that neither attempt blocks the other. My receiving thread checks the output stream, looking for an int until one exists. The int is a flag for the type of data being sent, and depending on that flag, the application prepares to grab the rest of the data, it's all predictable.
My problem comes in when trying to set up the sending thread. I was originally going to have it so that a call on the Sender object (an extension of Thread) would simply send the all the data needed, but realized that doing that didn't actually function within the thread.
Instead, I changed it so that the thread constantly runs and checks for a flag that determines the data going to be sent. A function is called from the UI thread, which prepares the data as class members, and then sets the flag, where it is then "picked up" by the thread and sent off to the other device. However, I realized this would take up a really unnecessary amount of processor time since the loop would be checking the flag over and over.
I'm just wondering what the proper way to do this is since android doesn't allow network operations on the UI thread. Would I have to rewrite the Sender object to create a new thread every time it sends a message?

A: The Sender thread can be halted via wait(). The Thread can be later resumed by sending it a notify().
An short example for the sender would be:
synchronized(this){
  wait();
}

synchronized(sender){
  sender.notify();
}

Edit: Obviously, in the above case "this" and "sender" refer to the same Object (the Sender Thread).
Edit2: Clarification where you need to add those statements. Given your description i assume you have something similiar to the following
public void run(){
  while(alive){
    // synchronized(this){
    if  (getFlags()!=null){
      //send data
      setFlags(null);
    }
    // wait();}
  }
}

in your Sender class. With the synchronized and wait you can keep the Thread from consuming all available cpu resources from a core.
Additionally you will need to modify the calling Thread. You will have add the following:
public void handleEvents(..) {
  // process the event
  // determine what to send
  // synchronized(sender) {
  sender.setFlags(mydata);
  // sender.notify();}
}

Note: If you modify data here that gets accessed in the sender thread you will need to move the synchronized statement further up as this will block the current thread. If the sender blocks too long you might consider queuing the data (e.g. by having Lists of Objects instead of just Objects) and checking a boolean flag before entering the synchronized block.


text:
Q: Why can't I scanf and printf an integer? #include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <sstream>

using namespace std;

struct person
{
    int age;
    string name[20], dob[20], pob[20], gender[7];
};

int main ()
{
    person person[10];
    cout << "Please enter your name, date of birth, place of birth, gender, and age, separated by a space.\nFor example, John 1/15/1994 Maine Male 20: ";
    scanf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
    printf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
    return 0;
}

I try to scan and print the user's age but it gives me 2749536 for the person.age value. Why is that?

A: First, change string to char in the declaration of person:
struct person
{
    int age;
    char name[20], dob[20], pob[20], gender[7];
//  ^^^^
};

Then you need to remove ampersand from &person[0].age in the call to printf, because you are passing an address of the int, not its value. Also remove ampersands from strings in scanf and printf calls:
scanf("%s %s %s %s %d", person[0].name, person[0].dob, person[0].pob, person[0].gender, &person[0].age);
// Only one ampersand is needed above: -------------------------------------------------^
printf("%s %s %s %s %d", person[0].name, person[0].dob, person[0].pob, person[0].gender, person[0].age);

Demo.

A: You should change the type of age from float to int.
Otherwise, use %f for float type.
Also, as suggested by Mr. dasblinkenlight, change the string to char.
Then, remove the & from &person[0].age in case of printf(). You want to print the value of the variable, not the address. FWIW, to print an address, you should use %p format specifier and cast the argument to (void *).
DO NOT mix them up and expect them to work. If you supply improper type of arguments to the supplied format specifiers, it will eventually will cause undefined behavior.
Moral of the story: Enable compiler warnings. Most of the time, they will warn you about the potential pitfalls.

A: You are passing the address of the value to printf. Get rid of the & for all of the arguments you pass to printf and the strings you pass to scanf. Also as others have said use %f for floats or change age to be an int.

A: You have an error right here:
printf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);

It should be:
printf("%s %s %s %s %d", person[0].name, person[0].dob, person[0].pob, person[0].gender, person[0].age);

Because, when you use '&' in the printf function, you are printing the address of the variable and not his value. So remember, you only have to use the '&' to scanf for anything, not to print.

A: The reason for the odd age is that you are outputing the address of person[0].age, not value. printf() takes the value, scanf() takes the address. You also probably meant char* array instead of string object. The code below compiles (although with a few justified warnings), and does print the correct output (tested):
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <sstream>

using namespace std;

struct person
{
    int age;
    char name[20], dob[20], pob[20], gender[7];
};

int main ()
{
    person person[10];
    cout << "Please enter your name, date of birth, place of birth, gender, and age, separated by a space.\nFor example, John 1/15/1994 Maine Male 20: ";
    scanf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, &person[0].age);
    printf("%s %s %s %s %d", &person[0].name, &person[0].dob, &person[0].pob, &person[0].gender, person[0].age);
    return 0;
}


text:
Q: Warnings on startup with atomikos starter dependency I have a spring boot application with postgresql and rabbitmq. I wanted to use a best-effort JTA transaction that contains both a postgres and rabbitmq transaction.
I have added the spring-boot-started-jta-atomikos dependency. When I start my application I receive this warning multiple times:
atomikos connection proxy for Pooled connection wrapping physical connection org.postgresql.jdbc.PgConnection@99c4993: WARNING: transaction manager not running?

Do I need any additional configuration?
I also get this warning at startup:
AtomikosDataSoureBean 'dataSource': poolSize equals default - this may cause performance problems!

I run with the following settings, but setMinPoolSize is never called
spring.jta.atomikos.connectionfactory.max-pool-size: 10
spring.jta.atomikos.connectionfactory.min-pool-size: 5

The documentation at:

*

*https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.jta.atomikos

*https://www.atomikos.com/Documentation/SpringBootIntegration
just says I can add the starter dependency. But it seems like spring boot doesn't properly auto-configure some things.

A: spring.jta.atomikos.connectionfactory properties are for controlling a JMS connectionFactory.
You should use the spring.jta.atomikos.datasource properties for controlling JDBC DataSource configuration.


text:
Q: How load dynamic component in class-based vue component I have two components which are trying to load dynamicly using object map.

*

*Info (options-based)

*SearchBar (class-based)

It works for options-based, but when i trying to load similar class-based component, i getting _currentTab is undefined. I tryed to use new SearchBar, but this too not working.
Vuex Module.
export default class Sidebar extends VuexModule {
    private _currentTab: object = tabs.SearchBar;
}

Tabs map
import SearchBar from "@/components/Tabs/SearchBar.vue";
import Info      from "@/components/Tabs/Info.vue";

export default {
    SearchBar : SearchBar,
    Info      : Info,
}

Sidebar Component
<div class="tab">
    <component v-bind:is="currentTab"></component>
</div>

import {Component, Vue} from 'vue-property-decorator';
import {mapGetters}     from 'vuex';

@Component({
    computed: {
        ...mapGetters({
            currentTab    : 'currentTab',
        }),
    },
})
export default class Sidebar extends Vue {

}

Info Component (options-based)
export default {
    data() {
        return {}
    },
}

SearchBar Component (class-based)
import {Component, Vue} from 'vue-property-decorator';
import {mapActions}     from 'vuex';

@Component
export default class SearchBar extends Vue {

}

A: For dynamic import I use :
  components: {
    History: () => import("./History"),
    MenuCardRight: () => import("@/components/MenuCardRight")
  },


text:
Q: No funciona atributo "download" en etiqueta "a" en html Al momento de querer implementar la descarga de un archivo directo en el ordenador local con el atributo download, en lugar de descargar, me abre el documento en otra pestaña, estuve buscando y realmente se hace así, entonces no sé si debería hacer alguna otra configuración previa.
Adjunto el código:

<!DOCTYPE html>

 <title>Este texto es el título del documento</title>
 <meta charset="utf-8">
 <meta name="description" content="Este es un documento HTML5">
 <meta name="keywords" content="HTML, CSS, JavaScript">
 <link rel="stylesheet" href="misestilos.css">

 Este es el título

 Principal | Fotos | Videos | Contacto

 Clic

A: El atributo de descarga download solo funciona si la URL de descarga es la misma del sitio. Entonces, si el href de tu archivo a descargar no está en tu sitio, la descarga no funcionará, en su lugar simplemente te redirigirá al enlace.
En otras palabras, solo puede descargar archivos que pertenezcan a tu sitio web. Es por ello que no te funciona, ya que el archivo al que apuntas no está en tu sitio.
Puedes ver más detalles en la documentación de MDN.


text:
Q: Basic problem: Parse two-column text file into variables for use in a for loop I'm eager to learn Powershell, but don't have much time to get this working. I believe this is a basic issue that could have several solutions.
I have a text file which could easily be converted into a csv if necessary.  It contains two columns (no headers):
ABC12345:Name1
ABC12346:Name2

etc.
I need these columns read in one line at a time in a for loop and each column entry placed into a variable for execution.  At the moment I have:
$Contents = Get-Content "d:\Filename.txt" | ForEach-Object {
$Var1 = $Contents[0].split(":")[1]
$Var2 = $Contents[1].split(":")[1]
Run-command -param1 $Var1 -param2 $Var2
}

Unsurprisingly I'm getting an error:
Method invocation failed because [System.Char] does not contain a method named 'split'.

I'm likely completely wrong with the array usage and formatting.  Am I over-complicating this?

A: If you treat the file as a CSV, the you can get the items like this:
Import-Csv -Delimiter ':' -Path .\test.csv -Header 'Var1','Var2'
This will output an object for each line with properties Var1 and Var2.  Thus your code could be:
Import-Csv -Delimiter ':' -Path .\test.csv -Header 'Var1','Var2' |
  ForEach-Object {
    Run-Command -Param1 $_.Var1 -Param2 $_.Var2
  }


text:
Q: Cannot get default error page in Asp.Net 5 My asp.net 5 application is throwing a blank html page at me, if an exception occurs. My goal is to display the default error page.
This question and this question seem to be related, but it is seems to be outdated, since we don't have a web.config any longer and the second one doesnt solve my problem.
This is my Configure() method in the startup.cs:
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IHostingEnvironment env)
{
    loggerFactory.AddDebug(LogLevel.Warning);

    app.UseStaticFiles();
    app.UseMvc(config =>
    {
        //[...]
    });

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        loggerFactory.AddDebug(LogLevel.Information);
        app.UseDeveloperExceptionPage();
    }
    else
    {
        loggerFactory.AddDebug(LogLevel.Debug);
        app.UseDeveloperExceptionPage();
    }
    //[...]
}

I have confirmed, that the code is actually hitting the if condition and the UserDeveloperExceptionPage method is loaded, but to no avail.
What am I missing?

A: Ok I found a solution
Order matters. You need to instantiate the error handling middleware before the MVC middleware. Otherwise, there will be just no exception handling.
Putting the error handling configuration just before the app.UseMvc(x => {...}) does the trick:
if (env.IsDevelopment())
{
    app.UseBrowserLink();
    loggerFactory.AddDebug(LogLevel.Information);
    app.UseDeveloperExceptionPage();
}

app.UseMvc(config =>
{
    //[...]
});

Simple as that.


text:
Q: Wordpress CI in Gitlab Is there any reference of Implementing WorPress (WP_UnitTestCase) using Gitlab CI?
I have already tried configuring the .gitlab-ci.yml, it implements the build, but no test are runned.
This is the .gitlab-ci.yml file:
image: php:5.6

variables:
  # Configure mysql service (https://hub.docker.com/_/mysql/)
  MYSQL_DATABASE: wordpress_tests
  MYSQL_ROOT_PASSWORD: mysql

before_script:
  # Install dependencies
  - bash ci/docker_install.sh wordpress_tests root mysql tutum-wordpress latest

stages:
  - test

# test:PHP5.3:MySQL:
#   image: tetraweb/php:5.3
#   script:
#   - phpunit --configuration phpunit.xml.dist

test:PHP5.4:MySQL:
  image: tetraweb/php:5.4
  services:
  - tutum/wordpress:latest
  script:
  - phpunit --configuration phpunit.xml.dist

# test:PHP5.6:MySQL:
#   image: php:5.6
#   script:
#   - phpunit --configuration phpunit.xml.dist

# test:PHP7:MySQL:
#   image: php:7
#   script:
#   - phpunit --configuration phpunit.xml.dist

A: After a lot of trial and error I got it working for me, you can see the tests for PHP5.3 through PHP7.0 are running properly for a test plugin I created here
This is how my .gitlab-ci.yml looks like. and the shell script to setup the environment is here
To use this in your project,just copy the .gitlab-ci.yml, bin/install_gitlab_tests.sh to your project.

A: I had a similar issue. Looks like it was a wordpress compatibility problem with phpunit 6.0. Fixed by downgranding phpunit to 5.6. See: https://github.com/wp-cli/wp-cli/issues/3802